human/dist/human.node.js

4168 lines
1.2 MiB
JavaScript
Raw Normal View History

2020-11-09 12:32:11 +01:00
var XS=Object.create,Ys=Object.defineProperty,JS=Object.getPrototypeOf,ZS=Object.prototype.hasOwnProperty,QS=Object.getOwnPropertyNames,eL=Object.getOwnPropertyDescriptor,Ff=n=>Ys(n,"__esModule",{value:!0}),we=(n,t)=>()=>(t||(t={exports:{}},n(t.exports,t)),t.exports),Di=(n,t)=>{Ff(n);for(var e in t)Ys(n,e,{get:t[e],enumerable:!0})},tL=(n,t,e)=>{if(Ff(n),typeof t=="object"||typeof t=="function")for(let r of QS(t))!ZS.call(n,r)&&r!=="default"&&Ys(n,r,{get:()=>t[r],enumerable:!(e=eL(t,r))||e.enumerable});return n},Ea=n=>n&&n.__esModule?n:tL(Ys(XS(JS(n)),"default",{value:n,enumerable:!0}),n),Gf=we(nL=>{Di(nL,{FetchError:()=>Pt,Headers:()=>vn,Request:()=>$r,Response:()=>Fn,default:()=>fL});const fn=Ea(require("stream")),Bc=Ea(require("http")),js=Ea(require("url")),Wf=Ea(require("https")),gr=Ea(require("zlib")),rL=fn.default.Readable,Jn=Symbol("buffer"),zc=Symbol("type");class Da{constructor(){this[zc]="";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[Jn]:l=Buffer.from(typeof c=="string"?c:String(c)),r+=l.length,e.push(l)}}this[Jn]=Buffer.concat(e);let i=t&&t.type!==void 0&&String(t.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[zc]=i)}get size(){return this[Jn].length}get type(){return this[zc]}text(){return Promise.resolve(this[Jn].toString())}arrayBuffer(){const n=this[Jn],t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return Promise.resolve(t)}stream(){const n=new rL;return n._read=function(){},n.push(this[Jn]),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[Jn],o=s.slice(r,r+a),c=new Da([],{type:arguments[2]});return c[Jn]=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 Pt(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)}Pt.prototype=Object.create(Error.prototype);Pt.prototype.constructor=Pt;Pt.prototype.name="FetchError";let Pc;try{Pc=require("encoding").convert}catch(n){}const Zn=Symbol("Body internals"),Uf=fn.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:Bf(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 fn.default||(n=Buffer.from(String(n))))),this[Zn]={body:n,disturbed:!1,error:null},this.size=i,this.timeout=s,n instanceof fn.default&&n.on("error",function(o){const c=o.name==="AbortError"?o:new Pt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o);t[Zn].error=c})}Dt.prototype={get body(){return this[Zn].body},get bodyUsed(){return this[Zn].disturbed},arrayBuffer(){return ki.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 ki.call(this).then(function(t){return Object.assign(new Da([],{type:n.toLowerCase()}),{[Jn]:t})})},json(){var n=this;return ki.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(e){return Dt.Promise.reject(new Pt(`invalid json response body at ${n.url} reason: ${e.message}`,"invalid-json"))}})},text(){return ki.call(this).then(function(n){return n.toString()})},buffer(){return ki.call(this)},textConverted(){var n=this;return ki.call(this).then(function(t){return iL(t,n.headers)})}};Object.defineProperties(Dt.prototype,{
2020-11-03 15:34:36 +01:00
`)),c.join(`
2020-11-09 12:32:11 +01:00
`)}function KL(n,t,e,r){var i=pt(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(Yu))+" + "+(parseFloat(n[1].toFixed(Yu))+"j"):wr(n)?r="'"+n+"'":e==="bool"?r=lg(n):r=parseFloat(n.toFixed(Yu)).toString(),Ba(r,t)}function lg(n){return n===0?"false":"true"}function no(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"?[lg(n[0])]:[n[0].toString()]}if(c===1){if(o>cg){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>cg){for(var w=0;w<Pa;w++){var b=w*g,S=b+g;y.push.apply(y,no(n.slice(b,S),f,e,m,i,!1))}y.push("...");for(var w=o-Pa;w<o;w++){var b=w*g,S=b+g;y.push.apply(y,no(n.slice(b,S),f,e,m,i,w===o-1))}}else for(var w=0;w<o;w++){var b=w*g,S=b+g;y.push.apply(y,no(n.slice(b,S),f,e,m,i,w===o-1))}var x=c===2?",":"";y[0]="["+y[0]+x;for(var w=1;w<y.length-1;w++)y[w]=" "+y[w]+x;for(var N=`,
2020-11-03 15:34:36 +01:00
`,w=2;w<c;w++)N+=`
2020-11-09 12:32:11 +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 ro=function(){function n(t,e,r){var i=this;if(this.dtype=e,this.shape=t.slice(),this.size=pt(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||Xf(e,this.size),this.strides=Wi(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 Wn().makeTensor(this.values,this.shape,this.dtype)},n}(),Wn=null,Pi=null;function XL(n){Wn=n}function JL(n){Pi=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=pt(t),this.strides=Wi(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,Pi.buffer(this.shape,this.dtype,t)]}})})},n.prototype.bufferSync=function(){return Pi.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,Ui(this.shape,t)]}})})},n.prototype.arraySync=function(){return Ui(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=Wn().read(this.dataId),this.dtype==="string"?[4,t]:[3,2];case 1:e=r.sent();try{return[2,e.map(function(i){return Gu(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=Wn().readSync(this.dataId);if(this.dtype==="string")try{return t.map(function(e){return Gu(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,Wn().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;Wn().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 S=new ArrayBuffer(w),x=new Uint8Array(S),N=0,I=0;I<y;I++){var C=new Uint8Array(d[f+I]);x.set(C,N),N+=C.byteLength}var O=s[g];O.forEach(function(D){var F=S.slice(D.groupOffset,D.groupOffset+D.sizeBytes),k=vg(F,[D.manifestEntry]);for(var B in k)p[B]=k[B]}),f+=y}),[2,p]}})})}}var JI="application/octet-stream",ZI="application/json",Eg=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=qe().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:ZI}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:JI}),"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-09 12:32:11 +01:00
`)+("Expected: "+l+"."))}}function LA(n,t){n().then(function(){return t.fail()},function(){return t()})}function IA(n,t){var e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return wr(n)||wr(n[0])||wr(t)||wr(t[0])?ph(n,e,function(r,i){return r==i}):ph(n,t,function(r,i){return fh(r,i,0)})}function AA(n,t,e){if(e==null&&(e=dh()),!fh(n,t,e))throw new Error("Numbers differ: actual === "+n+", expected === "+t)}function fh(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function TA(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 NA(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var _A={__proto__:null,TEST_EPSILON_FLOAT16:Jg,expectArraysClose:SA,testEpsilon:dh,expectPromiseToFail:LA,expectArraysEqual:IA,expectNumbersClose:AA,expectValuesInRange:TA,expectArrayBuffersEqual:NA};var CA="2.7.0";function RA(){qe().set("PROD",!0)}function OA(){qe().set("DEBUG",!0)}function EA(){qe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function _t(n){qe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function DA(){z.disposeVariables()}function kA(){return z}function FA(){return z.memory()}function WA(n){return z.profile(n)}function xt(n,t){return z.tidy(n,t)}function Vt(n){var t=Ju(n);t.forEach(function(e){return e.dispose()})}function Zg(n){return z.keep(n)}function UA(n){return z.time(n)}function BA(n){return z.setBackend(n)}function zA(){return z.ready()}function PA(){return z.backendName}function MA(n){z.removeBackend(n)}function HA(n){return z.findBackend(n)}function VA(n){return z.findBackendFactory(n)}function qA(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function GA(){return z.backend}function YA(n,t){qe().setPlatform(n,t)}function jA(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,Zs)}var ge=U({add_:jA});function KA(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,Ol)}var mh=U({floorDiv_:KA});function $A(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 mh(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,Al,o)}var Ne=U({div_:$A});function XA(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,Jl)}var Z=U({mul_:XA});function JA(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,Zc)}var Zt=U({abs_:JA});function ZA(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,Qc)}var Qg=U({acos_:ZA});function QA(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,el)}var e0=U({acosh_:QA});function e5(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(!wn(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,tl)}var t5=U({addN_:e5});function gh(n,t){for(var e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function t0(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=p0(e.map(function(d){return d.shape}),c);if(pt(l)===0)return Lr([],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});d0(u,c);var h=s.concat(e,c);return o(e),h},i=e,a={axis:t};return z.runKernelFunc(r,i,null,gl,a)}var kt=U({concat_:b5});function x5(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,wu)}var ti=U({sigmoid_:x5});function S5(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=hh(r,t,e),u=l[0],h=l[1];return Ug(r,u,h),c([r]),o.slice(r,u,h)},a={x:r},s={begin:t,size:e};return z.runKernelFunc(i,a,null,mu,s)}var Me=U({slice_:S5});function L5(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,Cu)}var ho=U({tanh_:L5});function I5(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),S=Me(f,[0,g*2],y),x=Me(f,[0,g*3],y),N=ge(Z(ti(w),ho(b)),Z(u,ti(ge(s,S)))),I=Z(ho(N),ti(x));return[N,I]}var A5=U({basicLSTMCell_:I5});function T5(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,dl,o)}var po=U({batchToSpaceND_:T5});function N5(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 _5(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=N5(s),d=function(g,y){return y([h,o,c,l]),g.batchNorm(h,fo(o),fo(c),fo(u),fo(l),a)},p={x:h,scale:l,offset:u,mean:o,variance:c},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,El,f);return Y(m,s.shape)}function fo(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_:_5});function C5(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-09 12:32:11 +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,vm,l)}var w0=U({depthToSpace_:iT});function aT(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=xn(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,Ll,p);return u?Y(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Xa=U({depthwiseConv2d_:aT});function sT(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,xm)}var oT=U({diag_:sT});function cT(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(Il,u,h);return l?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var b0=U({dilation2d_:cT});function lT(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 St(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 uT(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,Am)}var Ja=U({equal_:uT});function hT(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=mo(r,s),c=mo(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,pu)}var Sn=U({where_:hT});function dT(n){var t=R(n,"x","zerosLike"),e={x:t};return z.runKernelFunc(function(r){return r.zerosLike(t)},e,null,ku)}var ke=U({zerosLike_:dT});function pT(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 Sn(o,s,a)}var x0=U({divNoNan_:pT});function fT(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,Hl,u);return o?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var O0=U({localResponseNormalization_:zT});function PT(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,zl)}var ii=U({log_:PT});function MT(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,Pl)}var Th=U({log1p_:MT});function HT(n){return E(br(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)"),xo(o),o[0]})}}function VT(n){return E(br(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,...])"),xo(o),o})}}function qT(n){return E(br(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 xo(i),{grad:i[0],value:a}}}function GT(n){return E(br(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,...])"),xo(r.grads),r}}function E0(n,t){E(br(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 Pn(n){return z.customGrad(n)}function xo(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 YT(n){var t=R(n,"x","neg"),e={x:t};return z.runKernelFunc(function(r){return r.neg(t)},e,null,Zl)}var Lt=U({neg_:YT});function jT(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,bu)}var Nh=U({softplus_:jT});function KT(n){var t=R(n,"x","logSigmoid"),e=Pn(function(r){var i=Lt(Nh(Lt(r))),a=function(s){var o=Z(s,ti(Lt(r)));return o};return{value:i,gradFunc:a}});return e(t)}var D0=U({logSigmoid_:KT});function $T(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=bn(u,r.rank),d=r;h!=null&&(d=Nt(r,h),u=zn(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,Vl,s)}var ai=U({max_:$T});function XT(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,Nu)}var be=U({sub_:XT});function JT(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=bn(l,r.rank),h=l,d=r;u!=null&&(d=Nt(r,u),h=zn(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,Su,s)}var _e=U({sum_:JT});function ZT(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=ai(n,t,!0),u=be(n,l),h=be(he(u,"float32"),ii(_e(Ln(u),t,c)));return o([h]),h},i={logits:e},a={axis:t};return z.runKernelFunc(r,i,null,Ml,a)}var k0=U({logSoftmax_:ZT});function QT(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=ai(r,i,!0),s=be(r,a),o=Ln(s),c=_e(o,i),l=ii(c),u=ge(Y(a,l.shape),l);if(e){var h=cn(u.shape,i);return Y(u,h)}return u}var _h=U({logSumExp_:QT});function eN(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,Wm)}var si=U({logicalAnd_:eN});function tN(n){var t=R(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(r){return r.logicalNot(t)},e,null,Um)}var So=U({logicalNot_:tN});function nN(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,Bm)}var Ch=U({logicalOr_:nN});function rN(n,t){var e=R(n,"a","logicalXor","bool"),r=R(t,"b","logicalXor","bool");return it(e.shape,r.shape),si(Ch(n,t),So(si(n,t)))}var F0=U({logicalXor_:rN});function iN(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=Yi(o.shape,t,e,1,r,i),g;return m.filterWidth===1&&m.filterHeight===1&&wn(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,Gl,h);return c?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Rh=U({maxPool_:iN});function aN(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-08 18:32:31 +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 mn?(s=mn.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-09 12:32:11 +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(mn);m<g.length;m++){var y=g[m];f[y]=mn[y]}for(var w=0,b=Object.keys(e);w<b.length;w++){var y=b[w];f[y]=e[y]}var S=u.config;S.customObjects=f;for(var x=Qt({},mn),N=0,I=Object.keys(e);N<I.length;N++){var y=I[N];mn[y]=e[y]}nd(u.config);var C=p(d,u.config,e,i);return mn=Qt({},x),C}else{for(var x=Qt({},mn),O=0,D=Object.keys(e);O<D.length;O++){var y=D[O];mn[y]=e[y]}var C=new d(u.config);return mn=Qt({},x),C}}}function EE(n,t){return n<t?-1:n>t?1:0}function Bo(n,t){return-1*EE(n,t)}function Or(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 DE(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 ra(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 rd(n,t,e,r){return e===void 0&&(e=0),r===void 0&&(r=Infinity),Hn(e>=0),Hn(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 "+(By(n)+".")})}function By(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return By(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function kE(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 zy(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}function id(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),Py=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=id(e,r.axis),a=v.clipByValue(i,0,r.maxValue);return v.mul(e,v.div(a,v.add(It(),i)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(is);v.serialization.registerClass(Py);var My=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(It(),id(e,r.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(is);v.serialization.registerClass(My);var Hy=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(Hy);var Vy=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=id(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(It(),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(Vy);var qy={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};fun
2020-11-08 18:32:31 +01:00
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),yn(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 yn(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 yn(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,Pr(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-09 12:32:11 +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 cc=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);yn(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(Pr(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 yn(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 yn(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(yn(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 yn(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.");yn(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 yn(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-09 12:32:11 +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 cc([],e,n.dtype,t.length),c=0;c<s.length;c++)o.setItem(c,s[c]);return o}var T6=void 0,N6=function(n,t,e){return un(T6,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,S,x,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,x,Qe,ue,te,ne,x,ft,ue,x,He,ft,ue,G,H,x,He,ue,Ie,x,He,ft,ue,Et,x,He,ue,ie,ue,se,x,Ie,B,ue,Ie,x,Qe,ue,ye,x,ve,ue;return nn(this,function(ht){switch(ht.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=ht.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=ht.sent(),d=o.map(function(bt){return bt.id}),[4,h[0].data()];case 5:c=ht.sent(),h.forEach(function(bt){!bt.kept&&d.indexOf(bt.id)===-1&&bt.dispose()}),p=o,f=function(){var bt,Te,dt;return nn(this,function(mt){switch(mt.label){case 0:return bt=p,[4,e.functionMap[l].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 1:return p=mt.sent(),Te=p.map(function(Ve){return Ve.id}),bt.forEach(function(Ve){!Ve.kept&&d.indexOf(Ve.id)===-1&&Te.indexOf(Ve.id)===-1&&Ve.dispose()}),[4,e.functionMap[u].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 2:return dt=mt.sent(),[4,dt[0].data()];case 3:return c=mt.sent(),dt.forEach(function(Ve){!Ve.kept&&d.indexOf(Ve.id)===-1&&Te.indexOf(Ve.id)===-1&&Ve.dispose()}),[2]}})},ht.label=6;case 6:return c[0]?[5,f()]:[3,8];case 7:return ht.sent(),[3,6];case 8:return[2,p];case 9:return m=T("pred",n,t,e),[2,[lr(m)]];case 10:return m=T("pred",n,t,e),g=T("data",n,t,e),g.kept||(g=lr(g)),[4,m.data()];case 11:return[2,ht.sent()[0]?[void 0,g]:[g,void 0]];case 12:return y=n.inputNames.find(function(bt){return jt(bt,t,e)!==void 0}),y?(g=jt(y,t,e),[2,[lr(g)]]):[2,void 0];case 13:return w=T("frameName",n,t,e),g=T("tensor",n,t,e),e.enterFrame(w),[2,[lr(g)]];case 14:return g=T("tensor",n,t,e),e.exitFrame(),[2,[lr(g)]];case 15:return g=T("tensor",n,t,e),e.nextIteration(),[2,[lr(g)]];case 16:return b=T("size",n,t,e),S=T("dtype",n,t,e),x=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 x6(O,S,b,x,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
2020-11-08 18:32:31 +01:00
`+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),an(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,R8)]}})})},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,an(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,an(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 an(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 an(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 an(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,an(function(){return ce(e,void 0,void 0,function(){var a,s=this;return le(this,function(o){return a=ap(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,v8(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,an(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=Aw(e||Ce.util.now().toString());return an(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,an(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
2020-11-09 12:32:11 +01:00
`).map(function(s){return s.endsWith("\r")&&(s=s.slice(0,-1)),s}),[2,i]}})})},t}(ys);var uc='"',vs=Symbol("out"),Fw=Symbol("field"),hc=Symbol("quote"),op=Symbol("quoteafterquote"),Ww=Symbol("quoteinquote"),Uw=function(n){Ge(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 kw(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 uc:a=c+1,o=hc;break;case this.delimiter:if(a=c+1,this.delimiter===" "&&this
2020-11-03 15:34:36 +01:00
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
2020-11-09 12:32:11 +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 sb(this,void 0,void 0,function(){return ob(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 sb(this,void 0,void 0,function(){var r,i;return ob(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-09 12:32:11 +01:00
`))}function Gb(n){return ur(n,function(){return n.createProgram()},"Unable to create WebGLProgram.")}function Yb(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 gc(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 jb(n,t){var e=ur(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 Kb(n,t){var e=ur(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 TU(){return _.env().getNumber("WEBGL_VERSION")===2?1:4}function $b(n){return ur(n,function(){return n.createTexture()},"Unable to create WebGLTexture.")}function Xb(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 Jb(n){return ur(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Tp(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 Qb(n,t,e){Zb(n,e),de(n,function(){return n.activeTexture(n.TEXTURE0+e)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function NU(n,t){Zb(n,t),de(n,function(){return n.activeTexture(n.TEXTURE0+t)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function e2(n,t,e){return ur(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function t2(n,t,e){return n.getUniformLocation(t,e)}function n2(n,t,e,r){de(n,function(){return Qb(n,t,r)}),de(n,function(){return n.uniform1i(e,r)})}function _U(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 yc(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 Np(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: "+r2(n,t))}function r2(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 ur(n,t,e){var r=de(n,function(){return t()});if(r==null)throw new Error(e);return r}function Zb(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 Ti(n,t){return t===void 0&&(t=2),_.util.sizeFromShape(n.slice(0,n.length-t))}function Ni(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 vc(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[Ti(n)]
2020-11-03 15:34:36 +01:00
void main() {
`+r.join(`
`)+`
2020-11-03 15:34:36 +01:00
float result = `+i+`;
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var oB=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-08 18:32:31 +01:00
`}return n}();var cB=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-11-03 15:34:36 +01:00
setOutput(float(bestIndex));
}
2020-11-08 18:32:31 +01:00
`}return n}();function h2(n,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return n+"."+e})}function Mt(n,t){return t===1?[n]:h2(n,t)}function lB(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 Ht(){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-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-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-11-03 15:34:36 +01:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
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-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-11-03 15:34:36 +01:00
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
2020-11-03 15:34:36 +01:00
`,l=`
int round(float value) {
return int(floor(value + 0.5));
}
2020-11-03 15:34:36 +01:00
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-11-06 22:21:20 +01:00
`),{version:n,attribute:t,varyingVs:e,varyingFs:r,texture2D:i,output:a,defineOutput:s,defineSpecialNaN:o,defineSpecialInf:c,defineRound:l}}function _i(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 Ep(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-11-08 18:32:31 +01:00
`}var d2=`
2020-11-03 15:34:36 +01:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
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-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-08 18:32:31 +01:00
`;var p2=_.backend_util.getBroadcastDims;function vB(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 uB(f,t,r)}).join(`
`),o=t.texShape,c=Ht(),l=pB(c),u,h,d=gB(c);t.isPacked?(u=hB(t.logicalShape,o),h=mB(c)):(u=dB(t.logicalShape,o),h=fB(c)),r&&(d+=yB);var p=[d,l,h,a,u,s,e].join(`
`);return p}function wa(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return wB(n);case 1:return bB(n);case 2:return xB(n);case 3:return SB(n);case 4:return LB(n);case 5:return IB(n);case 6:return AB(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function f2(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return TB(n);case 1:return NB(n);case 2:return _B(n);case 3:return CB(n);default:return RB(n)}}function uB(n,t,e){e===void 0&&(e=!1);var r="";e?r+=f2(n):r+=wa(n);var i=n.shapeInfo.logicalShape,a=t.logicalShape;return i.length<=a.length&&(e?r+=OB(n,t):r+=EB(n,t)),r}function hB(n,t){switch(n.length){case 0:return m2();case 1:return DB(n,t);case 2:return WB(n,t);case 3:return kB(n,t);default:return FB(n,t)}}function dB(n,t){switch(n.length){case 0:return m2();case 1:return UB(n,t);case 2:return HB(n,t);case 3:return BB(n,t);case 4:return zB(n,t);case 5:return PB(n,t);case 6:return MB(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function pB(n){return`
2020-11-03 15:34:36 +01:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return `+n.texture2D+`(textureSampler, uv).r;
}
2020-11-08 18:32:31 +01:00
`}function fB(n){return`
2020-11-03 15:34:36 +01:00
void setOutput(float val) {
`+n.output+` = vec4(val, 0, 0, 0);
}
2020-11-08 18:32:31 +01:00
`}function mB(n){return`
2020-11-03 15:34:36 +01:00
void setOutput(vec4 val) {
`+n.output+` = val;
}
2020-11-08 18:32:31 +01:00
`}function gB(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-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-11-03 15:34:36 +01:00
return res;
}
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-11-03 15:34:36 +01:00
2020-11-06 17:39:39 +01:00
`+VB+`
2020-11-06 22:21:20 +01:00
`+qB+`
2020-11-08 18:32:31 +01:00
`+GB+`
`;return t}var VB=`
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-08 18:32:31 +01:00
`,qB=`
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-08 18:32:31 +01:00
`,GB=`
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-08 18:32:31 +01:00
`,yB=`
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-08 18:32:31 +01:00
`;function m2(){return`
2020-11-03 15:34:36 +01:00
int getOutputCoords() {
return 0;
}
2020-11-08 18:32:31 +01:00
`}function DB(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-08 18:32:31 +01:00
`}function UB(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-08 18:32:31 +01:00
`}function kB(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-08 18:32:31 +01:00
`}function BB(n,t){var e=_i(["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-08 18:32:31 +01:00
`}function FB(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-08 18:32:31 +01:00
`}function zB(n,t){var e=_i(["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-08 18:32:31 +01:00
`}function PB(n,t){var e=_i(["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-11-08 18:32:31 +01:00
`}function MB(n,t){var e=_i(["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-11-08 18:32:31 +01:00
`}function WB(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-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-08 18:32:31 +01:00
`}function HB(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-08 18:32:31 +01:00
`}function Ci(n){return"offset"+n}function TB(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Ht();return`
2020-11-03 15:34:36 +01:00
vec4 `+e+`() {
return `+r.texture2D+"("+t+`, halfCR);
}
2020-11-08 18:32:31 +01:00
`}function wB(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-06 22:21:20 +01:00
`;var s=n.shapeInfo.texShape,o=s[0],c=s[1],l=Ci(t);return`
2020-11-03 15:34:36 +01:00
float `+e+`() {
vec2 uv = uvFromFlat(`+o+", "+c+", "+l+`);
return sampleTexture(`+t+`, uv);
}
2020-11-08 18:32:31 +01:00
`}function NB(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=Ht();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-08 18:32:31 +01:00
`}function bB(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-06 22:21:20 +01:00
`+ba(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-06 22:21:20 +01:00
`;var s=Ci(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-08 18:32:31 +01:00
`}function _B(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=Ht();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-08 18:32:31 +01:00
`}function xB(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-06 22:21:20 +01:00
`}var o=_.util.squeezeShape(t),c=o.newShape,l=o.keptDims,u=c;if(u.length<t.length){var h=xa(n,u),d=["row","col"];return`
`+wa(h)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col) {
2020-11-06 22:21:20 +01:00
return `+r+"("+Sa(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-06 22:21:20 +01:00
`+ba(n)+`
2020-11-03 15:34:36 +01:00
}
2020-11-06 22:21:20 +01:00
`;var p=i[0],f=i[1],m=Ci(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-08 18:32:31 +01:00
`}function CB(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=xa(n,s),l=["b","row","col"];return`
`+f2(c)+`
2020-11-03 15:34:36 +01:00
vec4 `+r+`(int b, int row, int col) {
2020-11-06 22:21:20 +01:00
return `+r+"("+Sa(l,o)+`);
2020-11-03 15:34:36 +01:00
}
2020-11-06 17:39:39 +01:00
`}var u=a[0],h=a[1],d=Math.ceil(t[2]/2),p=d*Math.ceil(t[1]/2),f=Ht();return`
2020-11-03 15:34:36 +01:00
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-08 18:32:31 +01:00
`}function SB(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=xa(n,l),h=["row","col","depth"];return`
2020-11-06 22:21:20 +01:00
`+wa(u)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth) {
2020-11-06 22:21:20 +01:00
return `+r+"("+Sa(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-06 22:21:20 +01:00
`+ba(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-06 22:21:20 +01:00
`;var g=Ci(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-08 18:32:31 +01:00
`}function RB(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=Ht();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-08 18:32:31 +01:00
`}function LB(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=xa(n,c),h=["row","col","depth","depth2"];return`
2020-11-06 22:21:20 +01:00
`+wa(u)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2) {
2020-11-06 22:21:20 +01:00
return `+r+"("+Sa(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-06 22:21:20 +01:00
`+ba(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-06 22:21:20 +01:00
`;var g=Ci(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-08 18:32:31 +01:00
`}function IB(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=xa(n,l),d=["row","col","depth","depth2","depth3"];return`
2020-11-06 22:21:20 +01:00
`+wa(h)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
2020-11-06 22:21:20 +01:00
return `+r+"("+Sa(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-06 22:21:20 +01:00
`+ba(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-06 22:21:20 +01:00
`;var y=Ci(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-08 18:32:31 +01:00
`}function AB(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=xa(n,a),c=["row","col","depth","depth2","depth3","depth4"];return`
2020-11-06 22:21:20 +01:00
`+wa(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-06 22:21:20 +01:00
return `+r+"("+Sa(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-06 22:21:20 +01:00
`+ba(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-06 22:21:20 +01:00
`;var w=Ci(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-06 22:21:20 +01:00
`}function ba(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-08 18:32:31 +01:00
`}function OB(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=p2(n.shapeInfo.logicalShape,t.logicalShape),c=Ze(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(S){return"coords."+h[S+l]+" = 0;"}).join(`
2020-11-06 22:21:20 +01:00
`);var d="";s<2&&a>0?d="coords":d=n.shapeInfo.logicalShape.map(function(S,x){return"coords."+h[x+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=`
2020-11-03 15:34:36 +01:00
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-08 18:32:31 +01:00
`}function EB(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-08 18:32:31 +01:00
`;var l=Ze(c),u=p2(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-08 18:32:31 +01:00
`}function Ze(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 xa(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function Sa(n,t){return t.map(function(e){return n[e]}).join(", ")}var YB=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=Ze(c),u=Mt("coords",c),h,d;if(s===1){d=c+1;var p=Ze(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;
2020-11-06 22:21:20 +01:00
--`+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=Mt("sourceLocR",d-1).concat("inIdx.r"),w=Mt("sourceLocG",d-1).concat("inIdx.g"),b=Mt("sourceLocB",d-1).concat("inIdx.b"),S=Mt("sourceLocA",d-1).concat("inIdx.a"),x=r==="max"?"greaterThan":"lessThan",N=i?"":`
2020-11-03 15:34:36 +01:00
inIdx = round(vec4(getBestIndicesAChannel(`+y.join()+`),
getBestIndicesAChannel(`+w.join()+`),
getBestIndicesAChannel(`+b.join()+`),
2020-11-06 22:21:20 +01:00
getBestIndicesAChannel(`+S.join()+")));",I=`vec4(
2020-11-03 15:34:36 +01:00
getAChannel(`+y.join()+`),
hasNextCol ? getAChannel(`+w.join()+`) : 0.,
hasNextRow ? getAChannel(`+b.join()+`) : 0.,
2020-11-06 22:21:20 +01:00
hasNextRow && hasNextCol ? getAChannel(`+S.join()+") : 0.)",C=i?"":`
2020-11-03 15:34:36 +01:00
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(
2020-11-06 22:21:20 +01:00
vec4(`+x+`(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2020-11-03 15:34:36 +01:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
2020-11-08 18:32:31 +01:00
`}return n}();var jB=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-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-11-03 15:34:36 +01:00
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
}
2020-11-08 18:32:31 +01:00
`}return n}(),KB=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) {
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-11-03 15:34:36 +01:00
setOutput(dotProd);
}
2020-11-08 18:32:31 +01:00
`}return n}();var g2=`
2020-11-03 15:34:36 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-11-08 18:32:31 +01:00
`,$B=`
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-11-08 18:32:31 +01:00
`,XB=`
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-08 18:32:31 +01:00
`,JB="return float(a == b);",ZB="return float(a < b);",QB="return float(a <= b);",ez="return float(a > b);",tz="return float(a >= b);",nz="return float(a >= 1.0 && b >= 1.0);",rz="return float(a >= 1.0 || b >= 1.0);",iz=g2+`
2020-11-03 15:34:36 +01:00
return max(a, b);
2020-11-08 18:32:31 +01:00
`,az=g2+`
2020-11-03 15:34:36 +01:00
return min(a, b);
2020-11-08 18:32:31 +01:00
`,sz=`if (b == 0.0) return NAN;
return mod(a, b);`,oz="return (b >= 1.0) ? a : a * (b + 1.0);",y2="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-11-03 15:34:36 +01:00
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2020-11-09 12:32:11 +01:00
`}return n}();var Sc=`
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-08 18:32:31 +01:00
`,cz=`
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-11-03 15:34:36 +01:00
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
2020-11-03 15:34:36 +01:00
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
2020-11-03 15:34:36 +01:00
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
2020-11-03 15:34:36 +01:00
return vec4(result);
2020-11-08 18:32:31 +01:00
`,lz=`
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-09 12:32:11 +01:00
`+Sc+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-08 18:32:31 +01:00
`,v2=`
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-08 18:32:31 +01:00
`,uz=`
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-06 17:39:39 +01:00
`,hz=`
2020-11-08 18:32:31 +01:00
return vec4(equal(a, b));
2020-11-06 17:39:39 +01:00
`,dz=`
2020-11-08 18:32:31 +01:00
return vec4(lessThan(a, b));
2020-11-06 17:39:39 +01:00
`,pz=`
2020-11-08 18:32:31 +01:00
return vec4(lessThanEqual(a, b));
2020-11-06 17:39:39 +01:00
`,fz=`
2020-11-08 18:32:31 +01:00
return vec4(greaterThan(a, b));
2020-11-06 22:21:20 +01:00
`,mz=`
2020-11-08 18:32:31 +01:00
return vec4(greaterThanEqual(a, b));
`,gz=`
2020-11-03 15:34:36 +01:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-11-08 18:32:31 +01:00
`,yz=`
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-08 18:32:31 +01:00
`,vz=`
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-09 12:32:11 +01:00
`+Sc+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-08 18:32:31 +01:00
`,wz=`
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-09 12:32:11 +01:00
`+Sc+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-08 18:32:31 +01:00
`,bz=`
2020-11-03 15:34:36 +01:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-11-09 12:32:11 +01:00
`+Sc+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-06 22:21:20 +01:00
`,hr=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 20:59:30 +01:00
`;else{var o=Ze(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.;
2020-11-06 17:39:39 +01:00
`;else{var c=Mt("coords",a);s+=`
2020-11-03 15:34:36 +01:00
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-11-03 15:34:36 +01:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
`+s+`
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var xz=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);
return;
}
2020-11-03 15:34:36 +01:00
setOutput(clamp(value, minVal, maxVal));
}
2020-11-08 18:32:31 +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 Sz=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);
return;
}
2020-11-03 15:34:36 +01:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2020-11-08 18:32:31 +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 Lz=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-08 18:32:31 +01:00
`}return n}();var Iz=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-11-03 15:34:36 +01:00
setOutput(dotProd);
}
2020-11-08 18:32:31 +01:00
`}return n}(),Az=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-11-03 15:34:36 +01:00
setOutput(dotProd);
}
2020-11-08 18:32:31 +01:00
`}return n}(),Tz=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-11-08 18:32:31 +01:00
`}return n}(),Nz=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) {
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-08 18:32:31 +01:00
`}return n}();var _z=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+`) {
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+`) {
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-08 18:32:31 +01:00
`}return n}(),Cz=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-08 18:32:31 +01:00
`}return n}();var w2=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="",S="";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+`
}
2020-11-06 22:21:20 +01:00
`,S="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
2020-11-03 15:34:36 +01:00
`+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-11-03 15:34:36 +01:00
}
}
}
float result = dotProd;
`+x+`
2020-11-06 22:21:20 +01:00
`+S+`
2020-11-03 15:34:36 +01:00
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}(),Rz=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-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-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-08 18:32:31 +01:00
`}return n}();var b2=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+`) {
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-11-03 15:34:36 +01:00
float result = dotProd;
`+w+`
`+y+`
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var x2=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+`;
2020-11-06 22:21:20 +01:00
`,w+1<f)){var S=c%2===0?_.util.nearestLargerEven(d):d;d%2===0&&c%2===1||d%2!==0&&c%2!==1?(g+=`
xCOffset = xC + `+c%2+" + "+S+`;
2020-11-03 15:34:36 +01:00
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+=`
2020-11-06 22:21:20 +01:00
xCOffset = xC + `+S+`;
2020-11-03 15:34:36 +01:00
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)+` =
2020-11-06 22:21:20 +01:00
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 x="",N="";r&&(i?x=`vec4 activation(vec4 a) {
2020-11-03 15:34:36 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords();
`+r+`
2020-11-06 22:21:20 +01:00
}`:x=`vec4 activation(vec4 x) {
2020-11-03 15:34:36 +01:00
`+r+`
}`,N="result = activation(result);");var I=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
2020-11-06 22:21:20 +01:00
`+x+`
2020-11-03 15:34:36 +01:00
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-08 18:32:31 +01:00
`}return n}();var Oz=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],S=y[2],x=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=x[0],I=x[1],C=x[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+`;
2020-11-06 22:21:20 +01:00
float in_y = `+S+`;
2020-11-03 15:34:36 +01:00
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-08 18:32:31 +01:00
`}return n}(),I2=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=t;var i=t.length,a=e?"0.0":"getX("+S2(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 20:59:30 +01:00
`+Ze(i)+` coords = getOutputCoords();
2020-11-08 18:32:31 +01:00
int end = `+L2(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-08 18:32:31 +01:00
`+L2(i,"coords")+` = idx;
val += getX(`+S2(i,"coords")+`);
2020-11-03 15:34:36 +01:00
}
setOutput(val);
}
2020-11-08 18:32:31 +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 S2(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 L2(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 Ez=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Is.DENSE;var e=Ts(t),r=Ht();this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-06 22:21:20 +01:00
`+_i(["r","c","d"],t)+`
2020-11-03 15:34:36 +01:00
return ivec3(r, c, d);
}
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-08 18:32:31 +01:00
`}return n}();var Dz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Is.DENSE;var e=Ts(t),r=Ht();this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-06 22:21:20 +01:00
`+_i(["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-08 18:32:31 +01:00
`}return n}();var kz=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-11-08 18:32:31 +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 Fz=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-11-08 18:32:31 +01:00
`}return n}();var Wz=function(){function n(t){this.variableNames=["A"],this.outTexUsage=hn.DOWNLOAD;var e=Ht();this.outputShape=t,this.userCode=`
`+d2+`
2020-11-03 15:34:36 +01:00
void main() {
float x = getAAtOutCoords();
`+e.output+` = encode_float(x);
}
2020-11-08 18:32:31 +01:00
`}return n}();var Uz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=hn.DOWNLOAD;var e=Ht();this.outputShape=t,this.userCode=`
`+d2+`
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-11-08 18:32:31 +01:00
`}return n}();var Bz=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"];var i=Ht(),a=e[0],s=e[1];this.outputShape=t;var o="result";r&&(o="floor(result * 255. + 0.5)"),this.userCode=`
2020-11-06 17:39:39 +01:00
`+Ep(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-11-03 15:34:36 +01:00
`+i.output+" = vec4("+o+`, 0., 0., 0.);
}
2020-11-08 18:32:31 +01:00
`}return n}();var zz=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var i=Ht(),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-06 17:39:39 +01:00
`+Ep(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-08 18:32:31 +01:00
`}return n}();var Pz=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-08 18:32:31 +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 Hz=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=Ze(this.rank),s=Mz(t,r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
}
2020-11-08 18:32:31 +01:00
`}return n}();function Mz(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 Vz=function(){function n(t,e,r){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=r;var i=Ze(e.length),a=Ze(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-08 18:32:31 +01:00
`}return n}();function A2(n){var t=Ht(),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-09 12:32:11 +01:00
}`;return Vb(n,e)}function T2(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 jb(n,t)}function N2(n){var t=new Uint16Array([0,1,2,2,1,3]);return Kb(n,t)}function Rs(n,t,e,r,i,a){Xb(t,e);var s=$b(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 Dp(n){return n.internalFormatFloat}function _2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,Dp(r),r.textureFormatFloat,n.FLOAT)}function kp(n){return n.internalFormatHalfFloat}function C2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,kp(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Fp(n){return n.downloadTextureFormat}function R2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,Fp(r),n.RGBA,n.UNSIGNED_BYTE)}function Wp(n){return n.internalFormatPackedFloat}function O2(n,t,e,r){var i=ga(t,e),a=i[0],s=i[1];return Rs(n,a,s,Wp(r),n.RGBA,n.FLOAT)}function Up(n){return n.internalFormatPackedHalfFloat}function E2(n,t,e,r){var i=ga(t,e),a=i[0],s=i[1];return Rs(n,a,s,Up(r),n.RGBA,r.textureTypeHalfFloat)}function D2(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=Tp(n,t,"clipSpacePos",e,3,a,r);return s&&Tp(n,t,"uv",e,2,a,i)}function k2(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 F2(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 W2(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 U2(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 B2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1],o=4,c=new Uint8Array(wU(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 z2(n,t,e,r,i,a,s,o){var c=n,l=new Float32Array(bU(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 P2(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 qz={__proto__:null,createVertexShader:A2,createVertexBuffer:T2,createIndexBuffer:N2,getInternalFormatForFloat32MatrixTexture:Dp,createFloat32MatrixTexture:_2,getInternalFormatForFloat16MatrixTexture:kp,createFloat16MatrixTexture:C2,getInternalFormatForUnsignedBytesMatrixTexture:Fp,createUnsignedBytesMatrixTexture:R2,getInternalFormatForPackedMatrixTexture:Wp,createPackedMatrixTexture:O2,getInternalFormatForFloat16PackedMatrixTexture:Up,createFloat16PackedMatrixTexture:E2,bindVertexProgramAttributeStreams:D2,uploadDenseMatrixToTexture:k2,uploadPixelDataToTexture:F2,createBufferFromOutputTexture:W2,downloadFloat32MatrixFromBuffer:U2,downloadByteEncodedFloatMatrixFromOutputTexture:B2,
2020-11-03 15:34:36 +01:00
blockIndex = rc.y + `+N+`;
2020-11-06 22:21:20 +01:00
pos = rc.x + `+x+`;
2020-11-03 15:34:36 +01:00
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);
2020-11-06 22:21:20 +01:00
result[`+(x*2+N)+`] = getChannel(
2020-11-03 15:34:36 +01:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2020-11-06 22:21:20 +01:00
result[`+(x*2+N)+`] = getChannel(
2020-11-03 15:34:36 +01:00
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;
2020-11-06 22:21:20 +01:00
`+S+`
2020-11-03 15:34:36 +01:00
`+g.output+` = result;
}
2020-11-08 18:32:31 +01:00
`}return n}();var Xz=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-08 18:32:31 +01:00
`}return n}();var Jz=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)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * `+a+`);
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
2020-11-03 15:34:36 +01:00
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var Zz=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-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-11-03 15:34:36 +01:00
vec4 result = xAtOutputCoords * `+c+`;
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var Qz=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-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-11-03 15:34:36 +01:00
}
setOutput(dotProd);
}
2020-11-08 18:32:31 +01:00
`}return n}(),eP=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-11-06 17:39:39 +01:00
`}return n}();var Bp=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-11-03 15:34:36 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
`+y+`
`+g+`
setOutput(result);
}
2020-11-08 18:32:31 +01:00
`}return n}();var tP=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-11-03 15:34:36 +01:00
// If no other event happened, last event happened.
setOutput(float(`+(e-1)+`));
}
2020-11-08 18:32:31 +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 nP=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-08 18:32:31 +01:00
`}return n}();var sP=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-08 18:32:31 +01:00
`;else{var r=Mt("rc",e),i=Ze(e),a=rP(e,t,r),s=iP(e,t[t.length-1],t[t.length-2],r),o=aP(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-11-08 18:32:31 +01:00
`}}return n}();function oP(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 rP(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 iP(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-08 18:32:31 +01:00
`}function aP(n,t){var e=n.length,r=oP(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-08 18:32:31 +01:00
rEdge || cEdge ? 0. : getA(`+r[3]+")"}var cP=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=Ze(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-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-08 18:32:31 +01:00
`}return n}();var lP=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=Ze(i),s=e.map(function(y){return y[0]}).join(","),o=e.map(function(y,w){return y[0]+t[w]}).join(","),c=Mt("rc",i),l=Mt("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-06 22:21:20 +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-06 22:21:20 +01:00
`;return}var S="max",x=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(x="avgValue / count");var N=Math.floor(s/4)*4,I=s%4,C=`
2020-11-03 15:34:36 +01:00
if (`+m+`) {
avgValue += dot(values, ones);
2020-11-01 20:16:47 +01:00
} else {
2020-11-06 22:21:20 +01:00
minMaxValue = `+S+`(values, minMaxValue);
}
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-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-11-06 22:21:20 +01:00
setOutput(`+x+`);
}
2020-11-06 22:21:20 +01:00
`}return n}(),zp=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",S="0.0";if(b||(S="-1.0 / 1e-20"),r){var x=">=";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);
2020-11-06 22:21:20 +01:00
if (value `+x+` currMinMaxValue) {
2020-11-03 15:34:36 +01:00
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);
} else {
2020-11-03 15:34:36 +01:00
minMaxValue = `+N+`(values, minMaxValue);
}
2020-11-03 15:34:36 +01:00
`;this.userCode=`
const ivec3 strides =
ivec3(`+o+", "+c+", "+l+`);
const ivec3 pads = ivec3(`+g+", "+y+", "+w+`);
2020-11-06 22:21:20 +01:00
const float initializationValue = `+S+`;
2020-11-03 15:34:36 +01:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= `+t.inWidth+`) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
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
2020-11-06 22:21:20 +01:00
vec4 minMaxValue = vec4(`+S+`);
2020-11-03 15:34:36 +01:00
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-08 18:32:31 +01:00
`}return n}();var V2=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-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-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-08 18:32:31 +01:00
`}return n}();var q2=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-08 18:32:31 +01:00
`+uP(e)+`
2020-11-06 17:39:39 +01:00
`+Ep(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-08 18:32:31 +01:00
`}return n}();function uP(n){var t=_i(["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-08 18:32:31 +01:00
`}var hP=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-08 18:32:31 +01:00
`}return n}();var dP=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-08 18:32:31 +01:00
`}return n}();var pP=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-08 18:32:31 +01:00
`}return n}();var fP=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-08 18:32:31 +01:00
`}return n}();var mP=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-08 18:32:31 +01:00
`}return n}();var gP=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 20:59:30 +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=Ze(r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+s+` coords = getOutputCoords();
setOutput(getX(`+a+`));
}
2020-11-08 18:32:31 +01:00
`}return n}();var yP=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=Mt("rc",r),a=i[r-1]+" + 1 < "+this.outputShape[r-1],s=i[r-2]+" + 1 < "+this.outputShape[r-2],o=Ze(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-08 18:32:31 +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 G2=function(){function n(t,e,r,i,a,s,o){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;var c=Ze(a.length),l=Ze(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-08 18:32:31 +01:00
`}return n}();var vP=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-08 18:32:31 +01:00
`}return n}();var wP=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=Ze(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-08 18:32:31 +01:00
`}return n}();var xP=function(){function n(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e=Ze(this.rank),r="uniform int start["+this.rank+"];",i=bP(this.rank),a,s=t.map(function(o,c){return"sourceLoc."+Pp[c]+" = start["+c+"] + coords."+Pp[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-08 18:32:31 +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}(),Pp=["x","y","z","w","u","v"];function bP(n){if(n===1)return"sourceLoc";if(n<=6)return Pp.slice(0,n).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+n+" is not yet supported")}var SP=function(){function n(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Ze(this.rank),r=Mt("coords",this.rank),i=Mt("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-08 18:32:31 +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 LP=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=r;var i=r.length,a=Ze(r.length),s=Ze(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-08 18:32:31 +01:00
`}return n}();var IP=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=j2(e,r),a=K2(t,i,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);var s=Y2(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=j2(r,i),s=K2(e,a,i);s in this.freeTextures||(this.freeTextures[s]=[]);var o=Y2(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 AP(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 Y2(n,t,e,r,i){var a=TP(t,r),s;if(i){var o=ga(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=AP(e,a);return s*p}function TP(n,t){switch(n){case Ft.PACKED_2X2_FLOAT32:return Wp(t);case Ft.PACKED_2X2_FLOAT16:return Up(t);case Ft.UNPACKED_FLOAT32:return Dp(t);case Ft.UNPACKED_FLOAT16:return kp(t);case Ft.PACKED_4X1_UNSIGNED_BYTE:return Fp(t);default:throw new Error("Unknown physical texture type "+n)}}function NP(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 j2(n,t){if(n===hn.UPLOAD)return Ft.PACKED_2X2_FLOAT32;if(n===hn.RENDER||n==null)return NP(t);if(n===hn.DOWNLOAD||n===hn.PIXELS)return Ft.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function K2(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var CP=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-08 18:32:31 +01:00
`}return n}();function _P(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-08 18:32:31 +01:00
`}return n}(),dr="if (isnan(x)) return x;",RP="return x;",$2="return abs(x);",X2=dr+`
2020-11-03 15:34:36 +01:00
return (x < 0.0) ? 0.0 : x;
2020-11-08 18:32:31 +01:00
`,J2=dr+`
2020-11-03 15:34:36 +01:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-11-08 18:32:31 +01:00
`,Z2="return (x >= 0.0) ? x : (exp(x) - 1.0);",OP=`
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-08 18:32:31 +01:00
`;function EP(n){return n===void 0&&(n=0),dr+(`
2020-11-03 15:34:36 +01:00
return x > 0.0 ? 1.0 : float(`+n+`);
2020-11-08 18:32:31 +01:00
`)}var Q2="return -x;",ex="return ceil(x);",tx="return floor(x);",DP=`
2020-11-03 15:34:36 +01:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-11-08 18:32:31 +01:00
`,kP="return float(isnan(x));",FP="return float(isinf(x));",WP="return float(!isnan(x) && !isinf(x));",UP=`
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-08 18:32:31 +01:00
`,nx="return exp(x);",rx="return exp(x) - 1.0;",BP=`if (x < 0.0) return NAN;
return log(x);`,zP="return log(1.0 + x);",PP="return sqrt(x);",MP="return inversesqrt(x);",HP="return 1.0 / (1.0 + exp(-1.0 * x));",VP=`
2020-11-03 15:34:36 +01:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-11-08 18:32:31 +01:00
`,qP=dr+`
2020-11-03 15:34:36 +01:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-11-08 18:32:31 +01:00
`,GP=dr+`
2020-11-03 15:34:36 +01:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-11-08 18:32:31 +01:00
`,YP=dr+`
2020-11-03 15:34:36 +01:00
return atan(x);
2020-11-08 18:32:31 +01:00
`,jP=`
2020-11-03 15:34:36 +01:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-11-08 18:32:31 +01:00
`,KP=`
2020-11-03 15:34:36 +01:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-11-08 18:32:31 +01:00
`,$P=`
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-08 18:32:31 +01:00
`,XP=dr+"return log(x + sqrt(x * x + 1.0));",JP=dr+`
2020-11-03 15:34:36 +01:00
if (x < 1.0) return NAN;
2020-11-08 18:32:31 +01:00
return log(x + sqrt(x * x - 1.0));`,ZP=dr+`
2020-11-03 15:34:36 +01:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-11-08 18:32:31 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,QP=`
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-09 12:32:11 +01:00
`,eM="return 1.0 / x;",tM="return float(!(x >= 1.0));",Lc="return x;";var nM="return x;",rM=`
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-08 18:32:31 +01:00
`,ix=`
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-08 18:32:31 +01:00
`,ax=`
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-08 18:32:31 +01:00
`,sx=`
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-06 22:21:20 +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-08 18:32:31 +01:00
`}return n}();var iM=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,r=Mt("rc",e),i=Ze(e),a=lB(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-09 12:32:11 +01:00
`}return n}();var ox=_.backend_util.segment_util,aM=_.kernel_impls.split,sM=_.kernel_impls.tile,oM=_.kernel_impls.topkImpl,cM=_.kernel_impls.whereImpl,lM=1e-7,uM=1e-4,Ic={};function hM(n){return n in Ic||(Ic[n]={}),Ic[n]}function Ac(n,t){if(t===void 0&&(t=!1),n==="linear")return t?nM:RP;if(n==="relu")return t?ix:X2;if(n==="elu")return t?sx:Z2;if(n==="relu6")return t?ax:J2;if(n==="prelu")return t?v2:y2;throw new Error("Activation "+n+" has not been implemented for the WebGL backend.")}var dM=128,pM=600;function fM(){return _.env().global.screen==null?1024:_.env().global.screen.height*_.env().global.screen.width*window.devicePixelRatio*pM/1024/1024}var cx=1e3,lx=function(n){gU(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=jn(_.env().getNumber("WEBGL_VERSION"));r.binaryCache=hM(_.env().getNumber("WEBGL_VERSION")),r.gpgpu=new M2(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 IP(r.gpgpu),r.numMBBeforeWarning=fM(),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,Lc):u=new De(c,Lc);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 fc(this,void 0,void 0,function(){var r,i,a,s,o,c,l,u,h,d,p,f,m,g,y,w,b,S,x,N,I,C;return mc(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,Lc):h=new De(s,Lc),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-08 18:32:31 +01:00
`,xM=`
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-09 12:32:11 +01:00
`;function Tc(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 Ia(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],S=w[1],x=La({inputs:{real:b,imag:S},backend:m});return m.disposeIntermediateTensorInfo(b),m.disposeIntermediateTensorInfo(S),x}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 hr(e,p.shape,f.shape,i):B=new Bt(t,p.shape,f.shape),m.runWebGLProgram(B,[p,f],N)}}var dx="return a + b;",SM=Ia({opSnippet:dx,packedOpSnippet:dx,supportsComplex:!0,cpuKernelImpl:KU}),LM={kernelName:_.Add,backendName:"webgl",kernelFunc:SM};var IM=bM+`
2020-11-03 15:34:36 +01:00
return atan(a, b);
2020-11-08 18:32:31 +01:00
`,AM=`
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-08 18:32:31 +01:00
`+xM+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-08 18:32:31 +01:00
`,TM=Ia({opSnippet:IM,packedOpSnippet:AM}),NM={kernelName:_.Atan2,backendName:"webgl",kernelFunc:TM};function _M(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;ya(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 pr({inputs:{x:i},backend:e});var h=new Os(u,"avg",!1);return e.runWebGLProgram(h,[i],"float32")}var CM={kernelName:_.AvgPool,backendName:"webgl",kernelFunc:_M};function RM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=a;ya([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 jB(u);return e.runWebGLProgram(h,[i],s.dtype)}var OM={kernelName:_.AvgPoolBackprop,backendName:"webgl",kernelFunc:RM};var EM=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-08 18:32:31 +01:00
`}return n}();var DM=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-08 18:32:31 +01:00
`}return n}();var kM=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 DM(i.shape,a.shape,s.shape,h,d,l):new EM(i.shape,a.shape,s.shape,h,d,l),f=e.runWebGLProgram(p,u,u[0].dtype);return f},FM={kernelName:_.FusedBatchNorm,backendName:"webgl",kernelFunc:kM};var WM="return float(a != b);",px=Ia({opSnippet:WM,dtype:"bool"}),UM={kernelName:_.NotEqual,backendName:"webgl",kernelFunc:px};function Mp(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return pr({inputs:{x:i.complexTensorInfos.real},backend:e})}var BM={kernelName:_.Real,backendName:"webgl",kernelFunc:Mp};var zM="return float(int(x));";function PM(n,t){var e=new De(n.shape,zM),r=t.runWebGLProgram(e,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function Hp(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 pr({inputs:{x:i},backend:e});var s=_.zeros(i.shape),o=Hp({inputs:{x:i},backend:e,attrs:{dtype:"float32"}}),c=La({inputs:{real:o,imag:s},backend:e});return s.dispose(),e.disposeIntermediateTensorInfo(o),c}if(i.dtype==="complex64"){var l=Mp({inputs:{input:i},backend:e}),c=Hp({inputs:{x:l},backend:e,attrs:{dtype:a}});return e.disposeIntermediateTensorInfo(l),c}if(!_.util.hasEncodingLoss(i.dtype,a)){var c=pr({inputs:{x:i},backend:e});return{dataId:c.dataId,shape:c.shape,dtype:a}}if(a==="int32")return PM(i,e);if(a==="bool"){var u=e.makeTensorInfo([],"bool",_.util.getTypedArrayFromDType("bool",1)),h={a:i,b:u},c=px({inputs:h,backend:e});return e.disposeIntermediateTensorInfo(u),c}throw new Error("Error in Cast: failed to cast "+i.dtype+" to "+a)}var MM={kernelName:_.Cast,backendName:"webgl",kernelFunc:Hp};var HM=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-08 18:32:31 +01:00
`}return n}();var VM=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=Ze(i),s=Mt("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-09 12:32:11 +01:00
getT`+l+"("+Nc(o,u,f)+`),
vec2(`+Nc(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-09 12:32:11 +01:00
getT`+m+"("+Nc(o,u,g)+`),
vec2(`+Nc(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-09 12:32:11 +01:00
`}return n}();function Nc(n,t,e){var r=n.indexOf(t),i=n.map(function(a,s){return s===r?a+" - "+e:a});return i.join()}function fx(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return pr({inputs:{x:i.complexTensorInfos.imag},backend:e})}var qM={kernelName:_.Imag,backendName:"webgl",kernelFunc:fx};function GM(n,t,e){var r=[Ti(n.shape)].concat(Ni(n.shape)),i={dtype:n.dtype,shape:r,dataId:n.dataId},a=[Ti(t)].concat(Ni(t)),s=new q2(a,r),o=!0,c=e.runWebGLProgram(s,[i],n.dtype,null,o);return{dataId:c.dataId,shape:t,dtype:c.dtype}}function fr(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))?GM(i,c,s):(s.incRef(i.dataId),{dataId:i.dataId,shape:c,dtype:i.dtype})}var YM={kernelName:_.Reshape,backendName:"webgl",kernelFunc:fr};function Aa(n,t,e){var r=n[0].dtype;if(r==="complex64"){var i=n.map(function(b){return Mp({inputs:{input:b},backend:e})}),a=n.map(function(b){return fx({inputs:{input:b},backend:e})}),s=Aa(i,t,e),o=Aa(a,t,e),c=La({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=Aa(n.slice(0,l),t,e),h=Aa(n.slice(l),t,e),d=Aa([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 VM(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 fr({inputs:{x:b},attrs:{shape:[-1,_.util.sizeFromShape(b.shape.slice(t))]},backend:e})}),g=new HM(m.map(function(b){return b.shape})),y=e.runWebGLProgram(g,m,r);m.forEach(function(b){return e.disposeIntermediateTensorInfo(b)});var w=fr({inputs:{x:y},attrs:{shape:f},backend:e});return e.disposeIntermediateTensorInfo(y),w}function jM(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),Aa(o,a,e)}var KM={kernelName:_.Concat,backendName:"webgl",kernelFunc:jM};var $M=hx+`
2020-11-03 15:34:36 +01:00
return cos(x);
2020-11-09 12:32:11 +01:00
`,XM=Tc($M),JM={kernelName:_.Cos,backendName:"webgl",kernelFunc:XM};var ZM=`
2020-11-03 15:34:36 +01:00
if (a == b) {
return 1.0;
};
2020-11-08 18:32:31 +01:00
return a / b;`,QM=`
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-08 18:32:31 +01:00
`,eH=Ia({opSnippet:ZM,packedOpSnippet:QM,checkOutOfBounds:!0}),tH={kernelName:_.Div,backendName:"webgl",kernelFunc:eH};var mx=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-08 18:32:31 +01:00
`}return n}();function gx(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=fr({inputs:{x:n},backend:e,attrs:{shape:[s,a]}}),c=o.shape,l=new mx("real",c,t),u=new mx("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=La({inputs:{real:d,imag:p},backend:e});e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p);var m=fr({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(m),m}function nH(n){var t=n.inputs,e=n.backend,r=t.input;return gx(r,!1,e)}var rH={kernelName:_.FFT,backendName:"webgl",kernelFunc:nH};var iH=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-08 18:32:31 +01:00
`}return n}();var aH={kernelName:_.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=t.image,i=e,a=new iH(r.shape),s=i.runWebGLProgram(a,[r],r.dtype);return s}};var sH=function(){function n(t){this.variableNames=["A"];var e=Ht(),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-08 18:32:31 +01:00
`}return n}();var oH=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Ht(),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-08 18:32:31 +01:00
`}return n}();var lH={kernelName:_.FromPixels,backendName:"webgl",kernelFunc:cH},Ta;function cH(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)&&(Ta==null&&(Ta=document.createElement("canvas").getContext("2d")),Ta.canvas.width=l,Ta.canvas.height=u,Ta.drawImage(i,0,0,l,u),i=Ta.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 oH(d):new sH(d),m=e.runWebGLProgram(f,[p],"int32");return e.disposeData(p.dataId),m}function uH(n){var t=n.inputs,e=n.backend,r=t.input;return gx(r,!0,e)}var hH={kernelName:_.IFFT,backendName:"webgl",kernelFunc:uH};var yx=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-08 18:32:31 +01:00
`}return n}();function dH(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 vx(n,t,e,r){for(var i=dH(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 yx({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u},c):new yx({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u}):h=new V2({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 pH(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=fr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=vx(o,n.dtype,"max",r),l=fr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var mH=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=Ze(this.rank),s=fH(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-08 18:32:31 +01:00
`}return n}();function fH(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 gH=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=Ze(this.rank),s=h2("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 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-11-08 18:32:31 +01:00
`}return n}();function Vp(n,t,e){var r=_.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new gH(n.shape,t):new mH(n.shape,t);return e.runWebGLProgram(r,[n],n.dtype)}var yH={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 S=Op(y,i.shape,i.dtype,d,w);m=c.makeTensorInfo(w,i.dtype);var x=c.texData.get(m.dataId);x.values=S}else m=Vp(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=eB(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=pH(m,C,O,c);return p&&c.disposeIntermediateTensorInfo(m),D}};function vH(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;ya(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 pr({inputs:{x:i},backend:e});var h=new Os(u,"max",!1);return e.runWebGLProgram(h,[i],i.dtype)}var wH={kernelName:_.MaxPool,backendName:"webgl",kernelFunc:vH};function bH(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=t.output,o=a;ya([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 Qz(d),y=e.runWebGLProgram(g,[i,m],o.dtype);return e.disposeIntermediateTensorInfo(m),y}var xH={kernelName:_.MaxPoolBackprop,backendName:"webgl",kernelFunc:bH};function SH(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 LH={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=SH(i,l,d,u),f=p[0],m=p[1];return[f,m]}};function IH(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=fr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=vx(o,"float32","mean",r),l=fr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var AH={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),S=0;S<b.length;S++)b[S]=i.shape[d[S]];var x=Op(w,i.shape,i.dtype,d,b);g=c.makeTensorInfo(b,i.dtype);var N=c.texData.get(g.dataId);N.values=x}else g=Vp(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=IH(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-08 18:32:31 +01:00
`}return n}();var NH=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=Ze(i),s=e.map(function(m){return m[0]}).join(","),o=e.map(function(m,g){return m[0]+t[g]}).join(","),c=Mt("rc",i),l=Mt("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-08 18:32:31 +01:00
`}return n}();var _H=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 NH(i.shape,a,s):new TH(i.shape,a,s),c=e.runWebGLProgram(o,[i],i.dtype);return c},CH={kernelName:_.MirrorPad,backendName:"webgl",kernelFunc:_H};var wx={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},bx=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-08 18:32:31 +01:00
`}return n}();var xx="return a * b;";function RH(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 bx(wx.REAL,r.shape,i.shape),l=new bx(wx.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=La({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=tB(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 hr(xx,r.shape,i.shape):b=new Bt(xx,r.shape,i.shape),e.runWebGLProgram(b,[r,i],a)}var OH={kernelName:_.Multiply,backendName:"webgl",kernelFunc:RH};var EH={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 DH=_.kernel_impls.nonMaxSuppressionV4Impl,kH={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=DH(p,f,c,l,u,h),g=m.selectedIndices,y=m.validOutputs;return[g,y]}};var FH=_.kernel_impls.nonMaxSuppressionV5Impl,WH={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=FH(p,f,m,g,y,w),S=b.selectedIndices,x=b.selectedScores;return[S,x]}};var UH=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-08 18:32:31 +01:00
`}return n}();var BH={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 UH(i.shape,s,o,c),h=l.runWebGLProgram(u,[i],i.dtype);return h}};var zH=hx+`
2020-11-03 15:34:36 +01:00
return sin(x);
2020-11-09 14:57:24 +01:00
`,PH=Tc(zH),MH={kernelName:_.Sin,backendName:"webgl",kernelFunc:PH};var HH="return x * x;",VH=Tc(HH),qH={kernelName:_.Square,backendName:"webgl",kernelFunc:VH};var Sx="return (a - b) * (a - b);",GH=Ia({opSnippet:Sx,packedOpSnippet:Sx}),YH={kernelName:_.SquaredDifference,backendName:"webgl",kernelFunc:GH};var Lx="return a - b;",jH=Ia({opSnippet:Lx,packedOpSnippet:Lx,supportsComplex:!0,cpuKernelImpl:iB}),KH={kernelName:_.Sub,backendName:"webgl",kernelFunc:jH};var $H="return tan(x);",XH=Tc($H),JH={kernelName:_.Tan,backendName:"webgl",kernelFunc:XH};var ZH={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=Op(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=Vp(i,a,s);return u}};function QH(n){var t=n.inputs,e=n.attrs,r=n.backend,i=e.axis,a=t.x;ya(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");var s=r.readSync(a.dataId),o=aB(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 eV={kernelName:_.Unique,backendName:"webgl",kernelFunc:QH};var tV=[LM,NM,CM,OM,FM,MM,wM,KM,JM,tH,rH,aH,lH,vM,hH,qM,yH,wH,xH,LH,AH,CH,OH,EH,kH,WH,UM,BM,YM,BH,MH,qH,KH,YH,JH,ZH,eV];for(var qp=0,Ix=tV;qp<Ix.length;qp++){var nV=Ix[qp];_.registerKernel(nV)}Yn.GPGPUContext=M2;Yn.MathBackendWebGL=lx;Yn.forceHalfFloat=ux;Yn.gpgpu_util=qz;Yn.setWebGLContext=Pb;Yn.version_webgl=gM;Yn.webgl=yM;Yn.webgl_util=EU}),zt=we(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var Gp=di(),Yp=lw(),jp=Iw(),Tx=qw(),rV=zb(),iV=Ax();var aV="2.7.0";var sV={"tfjs-core":Gp.version_core,"tfjs-backend-cpu":rV.version_cpu,"tfjs-backend-webgl":iV.version_webgl,"tfjs-data":Tx.version_data,"tfjs-layers":Yp.version_layers,"tfjs-converter":jp.version_converter,tfjs:aV};Object.keys(Gp).forEach(function(n){n!=="default"&&Object.defineProperty(Ri,n,{enumerable:!0,get:function(){return Gp[n]}})});Object.keys(Yp).forEach(function(n){n!=="default"&&Object.defineProperty(Ri,n,{enumerable:!0,get:function(){return Yp[n]}})});Object.keys(jp).forEach(function(n){n!=="default"&&Object.defineProperty(Ri,n,{enumerable:!0,get:function(){return jp[n]}})});Ri.data=Tx;Ri.version=sV}),Ex=we(_c=>{const Ye=zt(),Nx=6;function oV(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 _x=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},Cx=n=>({startEndTensor:n,startPoint:Ye.slice(n,[0,0],[-1,2]),endPoint:Ye.slice(n,[0,2],[-1,2])}),Rx=(n,t)=>{const e=Ye.mul(n.startPoint,t),r=Ye.mul(n.endPoint,t),i=Ye.concat2d([e,r],1);return Cx(i)};function cV(n,t,e){const r=Ye.slice(n,[0,1],[-1,2]),i=Ye.add(r,t),a=Ye.slice(n,[0,3],[-1,2]),s=Ye.div(a,e),o=Ye.div(i,e),c=Ye.div(s,2),l=Ye.sub(o,c),u=Ye.add(o,c),h=Ye.mul(l,e),d=Ye.mul(u,e),p=1;return Ye.concat2d([h,d],p)}function lV(n,t){return Ye.tidy(()=>{const e=n.box?n.box:n;return Rx(e,t).startEndTensor.squeeze()})}class Ox{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.anchorsData=oV(t.detector.inputSize),this.anchors=Ye.tensor2d(this.anchorsData),this.inputSize=Ye.tensor1d([this.width,this.height]),this.config=t,this.scaleFaces=.8}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]=Ye.tidy(()=>{const l=n.resizeBilinear([this.width,this.height]),u=Ye.sub(l.div(127.5),1),h=this.blazeFaceModel.predict(u);let d;if(Array.isArray(h)){const g=h.sort((S,x)=>S.size-x.size),y=Ye.concat([g[0],g[2]],2),w=Ye.concat([g[1],g[3]],2),b=Ye.concat([w,y],1);d=b.squ
2020-11-06 22:21:20 +01:00
`),S.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join(`
`);let x={};x.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?x.colorMatrix.SHADER.WITHOUT_ALPHA:x.colorMatrix.SHADER.WITH_ALPHA,O=w(C);p.uniform1fv(O.uniform.m,I),y()},x.colorMatrix.SHADER={},x.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(`
`),x.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(`
`),x.brightness=function(N){const I=(N||0)+1;x.colorMatrix([I,0,0,0,0,0,I,0,0,0,0,0,I,0,0,0,0,0,1,0])},x.saturation=function(N){const I=(N||0)*2/3+1,C=(I-1)*-.5;x.colorMatrix([I,C,C,0,0,C,I,C,0,0,C,C,I,0,0,0,0,0,1,0])},x.desaturate=function(){x.saturation(-1)},x.contrast=function(N){const I=(N||0)+1,C=-128*(I-1);x.colorMatrix([I,0,0,0,C,0,I,0,0,C,0,0,I,0,C,0,0,0,1,0])},x.negative=function(){x.contrast(-2)},x.hue=function(N){N=(N||0)/180*Math.PI;const I=Math.cos(N),C=Math.sin(N),O=.213,D=.715,F=.072;x.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])},x.desaturateLuminance=function(){x.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},x.sepia=function(){x.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},x.brownie=function(){x.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},x.vintagePinhole=function(){x.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},x.kodachrome=function(){x.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])},x.technicolor=function(){x.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])},x.polaroid=function(){x.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},x.shiftToBGR=function(){x.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},x.convolution=function(N){const I=new Float32Array(N),C=1/o,O=1/c,D=w(x.convolution.SHADER);p.uniform1fv(D.uniform.m,I),p.uniform2f(D.uniform.px,C,O),y()},x.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(`
`),x.detectEdges=function(){x.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},x.sobelX=function(){x.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},x.sobelY=function(){x.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},x.sharpen=function(N){const I=N||1;x.convolution.call(this,[0,-1*I,0,-1*I,1+4*I,-1*I,0,-1*I,0])},x.emboss=function(N){const I=N||1;x.convolution.call(this,[-2*I,-1*I,0,-1*I,1,1*I,0,1*I,2*I])},x.blur=function(N){const I=N/7/o,C=N/7/c,O=w(x.blur.SHADER);p.uniform2f(O.uniform.px,0,C),y(b.INTERMEDIATE),p.uniform2f(O.uniform.px,I,0),y()},x.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(`
`),x.pixelate=function(N){const I=N/o,C=N/c,O=w(x.pixelate.SHADER);p.uniform2f(O.uniform.size,I,C),y()},x.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-09 14:57:24 +01:00
`)};HS.Canvas=rG}),GS=we(qS=>{const Ms=zt(),iG=VS();let wt=null,$t=null;function aG(n,t){let e;if(n instanceof Ms.Tensor)e=Ms.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)),(!wt||wt.width!==a||wt.height!==s)&&(wt=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(a,s):document.createElement("canvas"),wt.width!==a&&(wt.width=a),wt.height!==s&&(wt.height=s));const o=wt.getContext("2d");n instanceof ImageData?o.putImageData(n,0,0):o.drawImage(n,0,0,r,i,0,0,wt.width,wt.height),t.filter.enabled&&((!this.fx||!$t||wt.width!==$t.width||wt.height!==$t.height)&&($t=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(wt.width,wt.height):document.createElement("canvas"),$t.width!==wt.width&&($t.width=wt.width),$t.height!==wt.height&&($t.height=wt.height),this.fx=Ms.ENV.flags.IS_BROWSER?new iG.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(wt)),$t||($t=wt);let c;if(t.backend==="webgl"||$t instanceof ImageData)c=Ms.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=Ms.browser.fromPixels(d)}const l=c.toFloat();e=l.expandDims(0),c.dispose(),l.dispose()}return{tensor:e,canvas:t.filter.return?$t:null}}qS.process=aG}),YS=we(sG=>{Di(sG,{default:()=>oG});var oG={backend:"webgl",console:!0,async:!0,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:15,minConfidence:.1,iouThreshold:.1,scoreThreshold:.2},mesh:{enabled:!0,modelPath:"../models/facemesh.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris.json",inputSize:64},age:{enabled:!0,modelPath:"../models/age-ssrnet-imdb.json",inputSize:64,skipFrames:15},gender:{enabled:!0,minConfidence:.1,modelPath:"../models/gender-ssrnet-imdb.json",inputSize:64,skipFrames:15},emotion:{enabled:!0,inputSize:64,minConfidence:.2,skipFrames:15,modelPath:"../models/emotion-large.json"}},body:{enabled:!0,modelPath:"../models/posenet.json",inputSize:257,maxDetections:10,scoreThreshold:.8,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:15,minConfidence:.5,iouThreshold:.1,scoreThreshold:.8,maxHands:1,landmarks:!0,detector:{modelPath:"../models/handdetect.json"},skeleton:{modelPath:"../models/handskeleton.json"}}}}),KS=we((sY,jS)=>{jS.exports={name:"@vladmandic/human",version:"0.8.3",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://github.com/vladmandic/human/issues"},homepag
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