human/dist/human.js

4168 lines
1.2 MiB
JavaScript
Raw Normal View History

2020-11-04 16:18:22 +01:00
var Human=(()=>{var Hp=Object.defineProperty,nL=n=>Hp(n,"__esModule",{value:!0}),we=(n,t)=>()=>(t||(t={exports:{}},n(t.exports,t)),t.exports),ga=(n,t)=>{nL(n);for(var e in t)Hp(n,e,{get:t[e],enumerable:!0})},Vp=we(()=>{}),Gp=we(()=>{}),ws=we(()=>{}),ei=we(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});var uc=function(n,t){return uc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var i in r)r.hasOwnProperty(i)&&(e[i]=r[i])},uc(n,t)};function Yn(n,t){uc(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function pe(n,t,e,r){return new(e||(e=Promise))(function(i,a){function s(l){try{c(r.next(l))}catch(u){a(u)}}function o(l){try{c(r.throw(l))}catch(u){a(u)}}function c(l){l.done?i(l.value):new e(function(u){u(l.value)}).then(s,o)}c((r=r.apply(n,t||[])).next())})}function fe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;e;)try{if(r=1,i&&(a=l[0]&2?i.return:l[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,l[1])).done)return a;(i=0,a)&&(l=[l[0]&2,a.value]);switch(l[0]){case 0:case 1:a=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,i=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!a||l[1]>a[0]&&l[1]<a[3])){e.label=l[1];break}if(l[0]===6&&e.label<a[1]){e.label=a[1],a=l;break}if(a&&e.label<a[2]){e.label=a[2],e.ops.push(l);break}a[2]&&e.ops.pop(),e.trys.pop();continue}l=t.call(n,e)}catch(u){l=[6,u],i=0}finally{r=a=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}var rL=1e-7,iL=1e-4,aL=function(){function n(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return n.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},n.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},n.prototype.has=function(t){return this.data.has(t)},n.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},n.prototype.numDataIds=function(){return this.dataIdsCount},n}(),qp=function(){function n(){}return n.prototype.time=function(t){return X("time")},n.prototype.read=function(t){return X("read")},n.prototype.readSync=function(t){return X("readSync")},n.prototype.numDataIds=function(){return X("numDataIds")},n.prototype.disposeData=function(t){return X("disposeData")},n.prototype.write=function(t,e,r){return X("write")},n.prototype.move=function(t,e,r,i){return X("move")},n.prototype.memory=function(){return X("memory")},n.prototype.floatPrecision=function(){return X("floatPrecision")},n.prototype.epsilon=function(){return this.floatPrecision()===32?rL:iL},n.prototype.batchMatMul=function(t,e,r,i){return X("batchMatMul")},n.prototype.fusedBatchMatMul=function(t){var e=t.a,r=t.b,i=t.transposeA,a=t.transposeB,s=t.bias,o=t.activation,c=t.preluActivationWeights;return X("fusedBatchMatMul")},n.prototype.slice=function(t,e,r){return X("slice")},n.prototype.stridedSlice=function(t,e,r,i){return X("stridedSlice")},n.prototype.unstack=function(t,e){return X("unstack")},n.prototype.reverse=function(t,e){return X("reverse")},n.prototype.concat=function(t,e){return X("concat")},n.prototype.neg=function(t){return X("neg")},n.prototype.add=function(t,e){return X("add")},n.prototype.addN=function(t){return X("addN")},n.prototype.subtract=function(t,e){return X("subtract")},n.prototype.multiply=function(t,e){return X("multiply")},n.prototype.realDivide=function(t,e){return X("realDivide")},n.prototype.floorDiv=function(t,e){return X("floorDiv")},n.prototype.sum=function(t,e){return X("sum")},n.prototype.prod=function(t,e){return X("prod")},n.prototype.unsortedSegmentSum=funct
2020-11-03 15:34:36 +01:00
`)),c.join(`
2020-11-04 16:18:22 +01:00
`)}function WL(n,t,e,r){var i=dt(t),a=r[r.length-1],s=new Array(a).fill(0),o=t.length,c=e==="complex64"?La(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],xa(c[u+h],0,e).length);return s}function xa(n,t,e){var r;return Array.isArray(n)?r=parseFloat(n[0].toFixed(lu))+" + "+(parseFloat(n[1].toFixed(lu))+"j"):lr(n)?r="'"+n+"'":e==="bool"?r=lm(n):r=parseFloat(n.toFixed(lu)).toString(),va(r,t)}function lm(n){return n===0?"false":"true"}function Ns(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=La(n);return[xa(l[0],0,e)]}return e==="bool"?[lm(n[0])]:[n[0].toString()]}if(c===1){if(o>cm){var u=ba*s,h=Array.from(n.slice(0,u)),d=Array.from(n.slice((o-ba)*s,o*s));return e==="complex64"&&(h=La(h),d=La(d)),["["+h.map(function(I,C){return xa(I,i[C],e)}).join(", ")+", ..., "+d.map(function(I,C){return xa(I,i[o-ba+C],e)}).join(", ")+"]"]}var p=e==="complex64"?La(n):Array.from(n);return["["+p.map(function(I,C){return xa(I,i[C],e)}).join(", ")+"]"]}var f=t.slice(1),m=r.slice(1),g=r[0]*s,y=[];if(o>cm){for(var w=0;w<ba;w++){var b=w*g,x=b+g;y.push.apply(y,Ns(n.slice(b,x),f,e,m,i,!1))}y.push("...");for(var w=o-ba;w<o;w++){var b=w*g,x=b+g;y.push.apply(y,Ns(n.slice(b,x),f,e,m,i,w===o-1))}}else for(var w=0;w<o;w++){var b=w*g,x=b+g;y.push.apply(y,Ns(n.slice(b,x),f,e,m,i,w===o-1))}var L=c===2?",":"";y[0]="["+y[0]+L;for(var w=1;w<y.length-1;w++)y[w]=" "+y[w]+L;for(var N=`,
2020-11-03 15:34:36 +01:00
`,w=2;w<c;w++)N+=`
2020-11-04 16:18:22 +01:00
`;return y[y.length-1]=" "+y[y.length-1]+"]"+(a?"":N),y}function La(n){for(var t=[],e=0;e<n.length;e+=2)t.push([n[e],n[e+1]]);return t}var _s=function(){function n(t,e,r){var i=this;if(this.dtype=e,this.shape=t.slice(),this.size=dt(t),r!=null){var a=r.length;E(a===this.size,function(){return"Length of values '"+a+"' does not match the size "+("inferred by the shape '"+i.size+"'.")})}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||$p(e,this.size),this.strides=xi(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 _n().makeTensor(this.values,this.shape,this.dtype)},n}(),_n=null,Ai=null;function BL(n){_n=n}function zL(n){Ai=n}var K=function(){function n(t,e,r,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=dt(t),this.strides=xi(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,Ai.buffer(this.shape,this.dtype,t)]}})})},n.prototype.bufferSync=function(){return Ai.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,Li(this.shape,t)]}})})},n.prototype.arraySync=function(){return Li(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=_n().read(this.dataId),this.dtype==="string"?[4,t]:[3,2];case 1:e=r.sent();try{return[2,e.map(function(i){return cu(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=_n().readSync(this.dataId);if(this.dtype==="string")try{return t.map(function(e){return cu(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,_n().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;_n().disposeTensor(this),this.isDisposedInternal=!0},Object.defineProperty(n.prototype,"isDisposed",{get:function(){return this.is
`)+"Manifest JSON has weights with names: "+(c.join(", ")+"."));return u=a.reduce(function(g,y,w){return y&&g.push(w),g},[]),h=[],u.forEach(function(g){e[g].paths.forEach(function(y){var w=r+(r.endsWith("/")?"":"/")+y;h.push(w)})}),[4,n(h)];case 1:return d=m.sent(),p={},f=0,u.forEach(function(g){for(var y=e[g].paths.length,w=0,b=0;b<y;b++)w+=d[f+b].byteLength;for(var x=new ArrayBuffer(w),L=new Uint8Array(x),N=0,I=0;I<y;I++){var C=new Uint8Array(d[f+I]);L.set(C,N),N+=C.byteLength}var O=s[g];O.forEach(function(D){var F=x.slice(D.groupOffset,D.groupOffset+D.sizeBytes),k=vm(F,[D.manifestEntry]);for(var B in k)p[B]=k[B]}),f+=y}),[2,p]}})})}}var zS="application/octet-stream",PS="application/json",Em=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:PS}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:zS}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if(a=s.sent(),a.ok)return[2,{modelArtifactsInfo:Aa(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(a.status+"."))}})})},n.prototype.load=function(){return pe(this,void 0,void 0,function(){var t,e,r,i,a,s,o,c,l,u,h,d,p,f,m;return fe(this,function(g){switch(g.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(t=g.sent(),!t.ok)throw new Error("Request to "+this.path+" failed with status code "+(t.status+". Please verify this URL points to ")+"the model JSON of the model to load.");g.label=2;case 2:return g.trys.push([2,4,,5]),[4,t.json()];case 3:return e=g.sent(),[3,5];case 4:throw r=g.sent(),i="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?i+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":i+=" Please make sure the server is serving valid JSON for this request.",new Error(i);case 5:if(a=e.modelTopology,s=e.weightsManifest,o=e.generatedBy,c=e.convertedBy,l=e.format,u=e.userDefinedMetadata,a==null&&s==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return s!=null?[4,this.loadWeights(s)]:[3,7];case 6:p=g.sent(),h=p[0],d=p[1],g.label=7;case 7:return f={modelTopology:a,weightSpecs:h,weightData:d,userDefinedMetadata:u,generatedBy:o,convertedBy:c,format:l},m=e.modelInitializer,m&&(f.modelInitializer=m),[2,f]}})})},n.prototype.loadWe
2020-11-03 15:34:36 +01:00
`)+("Actual: "+c+`.
`)+("Expected: "+l+"."));for(var u=0;u<l.length;++u){var h=c[u],d=l[u];if(!e(h,d))throw new Error("Arrays differ: actual["+u+"] = "+h+", expected["+u+"] = "+d+`.
`+("Actual: "+c+`.
2020-11-04 16:18:22 +01:00
`)+("Expected: "+l+"."))}}function hI(n,t){n().then(function(){return t.fail()},function(){return t()})}function dI(n,t){var e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return lr(n)||lr(n[0])||lr(t)||lr(t[0])?Ru(n,e,function(r,i){return r==i}):Ru(n,t,function(r,i){return Ou(r,i,0)})}function pI(n,t,e){if(e==null&&(e=Cu()),!Ou(n,t,e))throw new Error("Numbers differ: actual === "+n+", expected === "+t)}function Ou(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function fI(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 mI(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var gI={__proto__:null,TEST_EPSILON_FLOAT16:Jm,expectArraysClose:uI,testEpsilon:Cu,expectPromiseToFail:hI,expectArraysEqual:dI,expectNumbersClose:pI,expectValuesInRange:fI,expectArrayBuffersEqual:mI};var yI="2.7.0";function vI(){qe().set("PROD",!0)}function wI(){qe().set("DEBUG",!0)}function bI(){qe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Nt(n){qe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function xI(){z.disposeVariables()}function LI(){return z}function SI(){return z.memory()}function II(n){return z.profile(n)}function wt(n,t){return z.tidy(n,t)}function Pt(n){var t=fu(n);t.forEach(function(e){return e.dispose()})}function Zm(n){return z.keep(n)}function AI(n){return z.time(n)}function TI(n){return z.setBackend(n)}function NI(){return z.ready()}function _I(){return z.backendName}function CI(n){z.removeBackend(n)}function RI(n){return z.findBackend(n)}function OI(n){return z.findBackendFactory(n)}function EI(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function DI(){return z.backend}function kI(n,t){qe().setPlatform(n,t)}function FI(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,Ss)}var ge=U({add_:FI});function WI(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,jc)}var Eu=U({floorDiv_:WI});function UI(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 Eu(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,Hc,o)}var Ne=U({div_:UI});function BI(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,fl)}var Z=U({mul_:BI});function zI(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,mc)}var jt=U({abs_:zI});function PI(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,gc)}var Qm=U({acos_:PI});function MI(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,yc)}var eg=U({acosh_:MI});function HI(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(!pn(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,vc)}var VI=U({addN_:HI});function Du(n,t){for(var e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function tg(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=pg(e.map(function(d){return d.shape}),c);if(dt(l)===0)return pr([],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});dg(u,c);var h=s.concat(e,c);return o(e),h},i=e,a={axis:t};return z.runKernelFunc(r,i,null,Dc,a)}var Et=U({concat_:cA});function lA(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,Wl)}var Vr=U({sigmoid_:lA});function uA(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=_u(r,t,e),u=l[0],h=l[1];return Um(r,u,h),c([r]),o.slice(r,u,h)},a={x:r},s={begin:t,size:e};return z.runKernelFunc(i,a,null,El,s)}var Me=U({slice_:uA});function hA(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,Yl)}var Ws=U({tanh_:hA});function dA(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=Et([l,h],1),p=Ue(d,o),f=ge(p,c),m=f.shape[0],g=f.shape[1]/4,y=[m,g],w=Me(f,[0,0],y),b=Me(f,[0,g],y),x=Me(f,[0,g*2],y),L=Me(f,[0,g*3],y),N=ge(Z(Vr(w),Ws(b)),Z(u,Vr(ge(s,x)))),I=Z(Ws(N),Vr(L));return[N,I]}var pA=U({basicLSTMCell_:dA});function fA(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,Cc,o)}var Us=U({batchToSpaceND_:fA});function mA(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 gA(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=mA(s),d=function(g,y){return y([h,o,c,l]),g.batchNorm(h,Bs(o),Bs(c),Bs(u),Bs(l),a)},p={x:h,scale:l,offset:u,mean:o,variance:c},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,$c,f);return Y(m,s.shape)}function Bs(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 Ca=U({batchNorm_:gA});function yA(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+".")}),Ca(s,o,c,u,l,a)}var
2020-11-03 15:34:36 +01:00
`+i+" and "+t+` for depthToSpace with input shape
`+r.shape}),E(a*t>=0,function(){return`Negative dimension size caused by overflow when multiplying
`+a+" and "+t+` for depthToSpace with input shape
2020-11-04 16:18:22 +01:00
`+r.shape}),E(s%(t*t)===0,function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+s+" for depthToSpace with input shape "+r.shape});var o=function(u){return u.depthToSpace(r,t,e)},c={x:r},l={blockSize:t,dataFormat:e};return z.runKernelFunc(o,c,null,vf,l)}var wg=U({depthToSpace_:YA});function KA(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(Mt(e,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+e+" and dilations '"+a+"'")});var y=mn(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,Pc,p);return u?Y(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Ra=U({depthwiseConv2d_:KA});function jA(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,xf)}var $A=U({diag_:jA});function XA(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(Mc,u,h);return l?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bg=U({dilation2d_:XA});function JA(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 bt(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 ZA(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,Af)}var Oa=U({equal_:ZA});function QA(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=zs(r,s),c=zs(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,Rl)}var gn=U({where_:QA});function e5(n){var t=R(n,"x","zerosLike"),e={x:t};return z.runKernelFunc(function(r){return r.zerosLike(t)},e,null,Jl)}var ke=U({zerosLike_:e5});function t5(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=Oa(i,s);return gn(o,s,a)}var xg=U({divNoNan_:t5});function n5(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,al,u);return o?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Og=U({localResponseNormalization_:N5});function _5(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,nl)}var Yr=U({log_:_5});function C5(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,rl)}var Vu=U({log1p_:C5});function R5(n){return E(ur(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)"),qs(o),o[0]})}}function O5(n){return E(ur(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=Ia(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,...])"),qs(o),o})}}function E5(n){return E(ur(n),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(t,e){E(t instanceof K,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),E(e==null||e instanceof K,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 qs(i),{grad:i[0],value:a}}}function D5(n){return E(ur(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 K}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),E(e==null||e instanceof K,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,...])"),qs(r.grads),r}}function Eg(n,t){E(ur(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 Sa}),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 En(n){return z.customGrad(n)}function qs(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 k5(n){var t=R(n,"x","neg"),e={x:t};return z.runKernelFunc(function(r){return r.neg(t)},e,null,ml)}var xt=U({neg_:k5});function F5(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,Ul)}var Gu=U({softplus_:F5});function W5(n){var t=R(n,"x","logSigmoid"),e=En(function(r){var i=xt(Gu(xt(r))),a=function(s){var o=Z(s,Vr(xt(r)));return o};return{value:i,gradFunc:a}});return e(t)}var Dg=U({logSigmoid_:W5});function U5(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=fn(u,r.rank),d=r;h!=null&&(d=Tt(r,h),u=On(u.length,d.rank));var p=o.max(d,u);h!=null&&d.dispose();var f=p;if(e){var m=an(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,sl,s)}var Kr=U({max_:U5});function B5(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,Gl)}var be=U({sub_:B5});function z5(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=fn(l,r.rank),h=l,d=r;u!=null&&(d=Tt(r,u),h=On(h.length,r.rank));var p=o.sum(d,h);if(e){var f=an(p.shape,l);p=Y(p,f)}return p},a={x:r},s={axis:t,keepDims:e};return z.runKernelFunc(i,a,null,zl,s)}var _e=U({sum_:z5});function P5(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=Kr(n,t,!0),u=be(n,l),h=be(he(u,"float32"),Yr(_e(yn(u),t,c)));return o([h]),h},i={logits:e},a={axis:t};return z.runKernelFunc(r,i,null,il,a)}var kg=U({logSoftmax_:P5});function M5(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=Kr(r,i,!0),s=be(r,a),o=yn(s),c=_e(o,i),l=Yr(c),u=ge(Y(a,l.shape),l);if(e){var h=an(u.shape,i);return Y(u,h)}return u}var qu=U({logSumExp_:M5});function H5(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,Wf)}var jr=U({logicalAnd_:H5});function V5(n){var t=R(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(r){return r.logicalNot(t)},e,null,Uf)}var Ys=U({logicalNot_:V5});function G5(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,Bf)}var Yu=U({logicalOr_:G5});function q5(n,t){var e=R(n,"a","logicalXor","bool"),r=R(t,"b","logicalXor","bool");return it(e.shape,r.shape),jr(Yu(n,t),Ys(jr(n,t)))}var Fg=U({logicalXor_:q5});function Y5(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(Mt(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=Oi(o.shape,t,e,1,r,i),g;return m.filterWidth===1&&m.filterHeight===1&&pn(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,cl,h);return c?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Ku=U({maxPool_:Y5});function K5(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]:Nt("dilations is deprecated, this field will be gone in v3.0.0.");var o=R(n,"x","maxPool3d"),c=o,l=!1;o.rank===4&&(l=!0,c=Y(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),E(c.rank===5,function(){return"Error i
2020-11-03 15:34:36 +01:00
`+("1. The "+r+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
`+("2. The custom "+r+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");return l}else{var u=n;if(u.className==null||u.config==null)throw new M(r+": Improper config format: "+(JSON.stringify(u)+`.
2020-11-04 16:18:22 +01:00
`)+"'className' and 'config' must set.");var h=u.className,d=void 0,p=void 0;if(h in e?(a=e[h],d=a[0],p=a[1]):h in un?(s=un.className,d=s[0],p=s[1]):h in t&&(o=t[h],d=o[0],p=o[1]),d==null)throw new M("Unknown "+r+": "+h+`. This may be due to one of the following reasons:
2020-11-03 15:34:36 +01:00
`+("1. The "+r+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-11-04 16:18:22 +01:00
`+("2. The custom "+r+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(p!=null){for(var f={},m=0,g=Object.keys(un);m<g.length;m++){var y=g[m];f[y]=un[y]}for(var w=0,b=Object.keys(e);w<b.length;w++){var y=b[w];f[y]=e[y]}var x=u.config;x.customObjects=f;for(var L=$t({},un),N=0,I=Object.keys(e);N<I.length;N++){var y=I[N];un[y]=e[y]}wh(u.config);var C=p(d,u.config,e,i);return un=$t({},L),C}else{for(var L=$t({},un),O=0,D=Object.keys(e);O<D.length;O++){var y=D[O];un[y]=e[y]}var C=new d(u.config);return un=$t({},L),C}}}function bO(n,t){return n<t?-1:n>t?1:0}function co(n,t){return-1*bO(n,t)}function xr(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 xO(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 Hi(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 bh(n,t,e,r){return e===void 0&&(e=0),r===void 0&&(r=Infinity),kn(e>=0),kn(r>=e),Array.isArray(n)&&n.length>=e&&n.length<=r&&n.every(function(i){return typeof i===t})}function _t(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 _t(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 "+(B0(n)+".")})}function B0(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return B0(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function LO(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 z0(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}function xh(n,t){return v.tidy(function(){return v.sqrt(v.sum(v.mul(n,n),t,!0))})}var Ba=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),P0=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=xh(e,r.axis),a=v.clipByValue(i,0,r.maxValue);return v.mul(e,v.div(a,v.add(Lt(),i)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(Ba);v.serialization.registerClass(P0);var M0=function(n){Q(t,n);function t(e){var r=n.call(this)||this;return r.defaultAxis=0,r.axis=e.axis!=null?e.axis:r.defaultAxis,r}return t.prototype.apply=function(e){var r=this;return v.tidy(function(){return v.div(e,v.add(Lt(),xh(e,r.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(Ba);v.serialization.registerClass(M0);var H0=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}(Ba);v.serialization.registerClass(H0);var V0=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=xh(e,r.axis),a=v.add(v.mul(r.rate,v.clipByValue(i,r.minValue,r.maxValue)),v.mul(1-r.rate,i));return v.mul(e,v.div(a,v.add(Lt(),i)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(Ba);v.serialization.registerClass(V0);var G0={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};fun
because the value dtype is `+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),dn(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 dn(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 dn(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,Rr(t));if(!this.dynamicSize&&r>=this.maxSize)throw new Error("Max index must be < array size ("+r+" vs. "+this.maxSize+")");this.writeMany(t,W.unstack(e,0))},n.prototype.split=function(t,e){var r=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var i=0,a=t.map(function(u){return i+=u,i});if(i!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
2020-11-03 15:34:36 +01:00
tensor.shape[0], but sum of lengths is
2020-11-04 16:18:22 +01:00
`+i+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var s=i===0?0:e.size/i,o=[];W.tidy(function(){e=W.reshape(e,[1,i,s]);for(var u=0;u<t.length;++u){var h=u===0?0:a[u-1],d=[0,h,0],p=[1,t[u],s];o[u]=W.reshape(W.slice(e,d,p),r.elementShape)}return o});for(var c=[],l=0;l<t.length;l++)c[l]=l;this.writeMany(c,o)},n}();var Do=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);dn(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(Rr(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 dn(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 dn(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(dn(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 dn(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.");dn(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 dn(this.elementShape,r,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?W.tensor([],[0].concat(this.elementShape)):W.tidy(function(){var a=t.map(function(s){return W.reshape(i.tensors[s],r)});return W.stack(a,0)})},n.prototype.concat=function(t,e){var r=this;if
2020-11-03 15:34:36 +01:00
tensor.shape[0], but sum of lengths is
2020-11-04 16:18:22 +01:00
`+r+", and tensor's shape is: "+n.shape);for(var a=r===0?0:n.size/r,s=W.tidy(function(){var l=[];n=W.reshape(n,[1,r,a]);for(var u=0;u<t.length;++u){var h=u===0?0:i[u-1],d=[0,h,0],p=[1,t[u],a];l[u]=W.reshape(W.slice(n,d,p),e)}return n.dispose(),l}),o=new Do([],e,n.dtype,t.length),c=0;c<s.length;c++)o.setItem(c,s[c]);return o}var fk=void 0,mk=function(n,t,e){return on(fk,void 0,void 0,function(){var r,i,a,s,o,c,l,u,o,h,d,c,p,f,m,m,g,y,g,w,g,g,g,b,x,L,N,I,C,O,D,F,k,B,V,P,G,j,q,H,J,$,ee,te,ne,re,ie,oe,se,me,ye,ve,Ee,Be,We,Ke,ze,Ie,k,B,ue,Ie,G,L,et,ue,te,ne,L,pt,ue,L,He,pt,ue,q,H,L,He,ue,Ie,L,He,pt,ue,Ot,L,He,ue,ie,ue,se,L,Ie,B,ue,Ie,L,et,ue,ye,L,ve,ue;return Zt(this,function(ut){switch(ut.label){case 0:r=n.op;switch(r){case"If":return[3,1];case"StatelessIf":return[3,1];case"While":return[3,3];case"StatelessWhile":return[3,3];case"LoopCond":return[3,9];case"Switch":return[3,10];case"Merge":return[3,12];case"Enter":return[3,13];case"Exit":return[3,14];case"NextIteration":return[3,15];case"TensorArrayV3":return[3,16];case"TensorArrayWriteV3":return[3,17];case"TensorArrayReadV3":return[3,18];case"TensorArrayGatherV3":return[3,19];case"TensorArrayScatterV3":return[3,20];case"TensorArrayConcatV3":return[3,21];case"TensorArraySplitV3":return[3,22];case"TensorArraySizeV3":return[3,23];case"TensorArrayCloseV3":return[3,24];case"TensorListSetItem":return[3,25];case"TensorListGetItem":return[3,26];case"TensorListScatterV2":return[3,27];case"TensorListScatter":return[3,27];case"TensorListReserve":return[3,28];case"TensorListGather":return[3,29];case"TensorListStack":return[3,30];case"TensorListFromTensor":return[3,31];case"TensorListConcat":return[3,32];case"TensorListPushBack":return[3,33];case"TensorListPopBack":return[3,34];case"TensorListSplit":return[3,35]}return[3,36];case 1:return i=T("thenBranch",n,t,e),a=T("elseBranch",n,t,e),s=T("cond",n,t,e),o=T("args",n,t,e),[4,s.data()];case 2:return c=ut.sent(),c[0]?[2,e.functionMap[i].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)]:[2,e.functionMap[a].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 3:return l=T("body",n,t,e),u=T("cond",n,t,e),o=T("args",n,t,e),[4,e.functionMap[u].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 4:return h=ut.sent(),d=o.map(function(vt){return vt.id}),[4,h[0].data()];case 5:c=ut.sent(),h.forEach(function(vt){!vt.kept&&d.indexOf(vt.id)===-1&&vt.dispose()}),p=o,f=function(){var vt,Te,ht;return Zt(this,function(ft){switch(ft.label){case 0:return vt=p,[4,e.functionMap[l].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 1:return p=ft.sent(),Te=p.map(function(Ge){return Ge.id}),vt.forEach(function(Ge){!Ge.kept&&d.indexOf(Ge.id)===-1&&Te.indexOf(Ge.id)===-1&&Ge.dispose()}),[4,e.functionMap[u].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 2:return ht=ft.sent(),[4,ht[0].data()];case 3:return c=ft.sent(),ht.forEach(function(Ge){!Ge.kept&&d.indexOf(Ge.id)===-1&&Te.indexOf(Ge.id)===-1&&Ge.dispose()}),[2]}})},ut.label=6;case 6:return c[0]?[5,f()]:[3,8];case 7:return ut.sent(),[3,6];case 8:return[2,p];case 9:return m=T("pred",n,t,e),[2,[tr(m)]];case 10:return m=T("pred",n,t,e),g=T("data",n,t,e),g.kept||(g=tr(g)),[4,m.data()];case 11:return[2,ut.sent()[0]?[void 0,g]:[g,void 0]];case 12:return y=n.inputNames.find(function(vt){return Gt(vt,t,e)!==void 0}),y?(g=Gt(y,t,e),[2,[tr(g)]]):[2,void 0];case 13:return w=T("frameName",n,t,e),g=T("tensor",n,t,e),e.enterFrame(w),[2,[tr(g)]];case 14:return g=T("tensor",n,t,e),e.exitFrame(),[2,[tr(g)]];case 15:return g=T("tensor",n,t,e),e.nextIteration(),[2,[tr(g)]];case 16:return b=T("size",n,t,e),x=T("dtype",n,t,e),L=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 lk(O,x,b,L,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),G=T("index",n,t,e),j=e.getTensorArray(P.id),[2,[j.read(G)]];case 19
`+t});var a;return this.size===Infinity||this.size==null?a=this.size:e?a=Math.ceil(this.size/t):a=Math.floor(this.size/t),en(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,v6)]}})})},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,en(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,en(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 en(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 en(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 en(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,en(function(){return ce(e,void 0,void 0,function(){var a,s=this;return le(this,function(o){return a=Ld(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,s6(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,en(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=T1(e||Ce.util.now().toString());return en(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,en(function(){return ce(e,void 0,void 0,function(){return le(this,function(a){switch(a.label){case 0:return[4,r.iterator()];case 1:return[2,a.sent().take(t)]}})})},i)},n.prototype.toArray=function(){return ce(this,void 0,void 0,function(){return le(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert
`).map(function(s){return s.endsWith("\r")&&(s=s.slice(0,-1)),s}),[2,i]}})})},t}(Ja);var Fo='"',Za=Symbol("out"),W1=Symbol("field"),Wo=Symbol("quote"),Id=Symbol("quoteafterquote"),U1=Symbol("quoteinquote"),B1=function(n){Ye(t,n);function t(e,r){var i=n.call(this)||this;return i.input=e,i.hasHeader=!0,i.fullColumnNames=null,i.columnNamesValidated=!1,i.columnConfigs=null,i.configuredColumnsOnly=!1,i.delimiter=",",i.delimWhitespace=!1,i.base=new F1(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=Za,c=0;c<s;c++)switch(o){case Za:switch(e.charAt(c)){case Fo:a=c+1,o=Wo;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-04 16:18:22 +01:00
============================`));var a={};return this.data.set(a,{values:e,dtype:i,refCount:1}),a},t.prototype.makeTensorInfo=function(e,r,i){var a;if(r==="string"&&i!=null&&i.length>0&&S.util.isString(i[0])){var s=i.map(function(o){return S.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 ow(this,void 0,void 0,function(){return cw(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 S.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 S.util.decodeString(a)})}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return S.buffer(e.shape,e.dtype,i)},t.prototype.makeOutput=function(e,r,i){var a=this.write(e,r,i);return S.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 ow(this,void 0,void 0,function(){var r,i;return cw(this,function(a){return r=S.util.now(),e(),i=S.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=S.slice_util.computeOutShape(r,i,a);if(s.some(function(p){return p===0}))return S.tensor([],s);for(var o=S.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=S.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]=S.slice(e,c,l).reshape(a);return u},t.prototype.reverse=function(e,r){ae(e,"reverse");for(var i=S.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"),S.mul(S.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=S.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=S.util.parseAxisParam([r],e.shape),a=S.max(e,i),s=S.backend_util.expandShapeToKeepDim(a.shape,i),o=S.sub(e,a.reshape(s)),c=S.exp(o),l=this.sum(c,i).reshape(s);return S.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"),S.ba
2020-11-03 15:34:36 +01:00
`),a=i.length.toString().length+2,s=i.map(function(d,p){return _.util.rightPad((p+1).toString(),a)+d}),o=0,c=0;c<s.length;c++)o=Math.max(s[c].length,o);var l=s.slice(0,r-1),u=s.slice(r-1,r),h=s.slice(r);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log("%c "+_.util.rightPad(u[0],o),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join(`
2020-11-04 16:18:22 +01:00
`))}function Yw(n){return nr(n,function(){return n.createProgram()},"Unable to create WebGLProgram.")}function Kw(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 Mo(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 jw(n,t){var e=nr(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 $w(n,t){var e=nr(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 fW(){return _.env().getNumber("WEBGL_VERSION")===2?1:4}function Xw(n){return nr(n,function(){return n.createTexture()},"Unable to create WebGLTexture.")}function Jw(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 Zw(n){return nr(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Vd(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 eb(n,t,e){Qw(n,e),de(n,function(){return n.activeTexture(n.TEXTURE0+e)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function mW(n,t){Qw(n,t),de(n,function(){return n.activeTexture(n.TEXTURE0+t)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function tb(n,t,e){return nr(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function nb(n,t,e){return n.getUniformLocation(t,e)}function rb(n,t,e,r){de(n,function(){return eb(n,t,r)}),de(n,function(){return n.uniform1i(e,r)})}function gW(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 Ho(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 Gd(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 cs(n){var t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+ib(n,t))}function ib(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 nr(n,t,e){var r=de(n,function(){return t()});if(r==null)throw new Error(e);return r}function Qw(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 fi(n,t){return t===void 0&&(t=2),_.util.sizeFromShape(n.slice(0,n.length-t))}function mi(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 Vo(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[fi(n)]
2020-11-03 15:34:36 +01:00
void main() {
`+r.join(`
`)+`
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
float result = `+i+`;
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var $W=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(`
`)+`
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
vec4 result = `+i+`;
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var XW=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+`;
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
for (int i = 0; i < `+i+`; i++) {
int inIdx = `+c+`;
float candidate = getA(batch, inIdx);
if (candidate `+o+` bestValue) {
bestValue = candidate;
bestIndex = inIdx;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(float(bestIndex));
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();function db(n,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return n+"."+e})}function Ut(n,t){return t===1?[n]:db(n,t)}function JW(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 Bt(){var n,t,e,r,i,a,s,o,c,l;return _.env().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",r="in",i="texture",a="outputColor",s="out vec4 outputColor;",o=`
2020-11-03 15:34:36 +01:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
#define isnan(value) isnan_custom(value)
`,c="",l=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
`):(n="",t="attribute",e="varying",r="varying",i="texture2D",a="gl_FragColor",s="",o=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`,c=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`,l=`
int round(float value) {
return int(floor(value + 0.5));
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-11-04 16:18:22 +01:00
`),{version:n,attribute:t,varyingVs:e,varyingFs:r,texture2D:i,output:a,defineOutput:s,defineSpecialNaN:o,defineSpecialInf:c,defineRound:l}}function gi(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 $d(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-04 16:18:22 +01:00
`}var pb=`
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-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
2020-11-04 16:18:22 +01:00
`;var fb=_.backend_util.getBroadcastDims;function sU(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 ZW(f,t,r)}).join(`
`),o=t.texShape,c=Bt(),l=tU(c),u,h,d=iU(c);t.isPacked?(u=QW(t.logicalShape,o),h=rU(c)):(u=eU(t.logicalShape,o),h=nU(c)),r&&(d+=aU);var p=[d,l,h,a,u,s,e].join(`
`);return p}function ia(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return oU(n);case 1:return cU(n);case 2:return lU(n);case 3:return uU(n);case 4:return hU(n);case 5:return dU(n);case 6:return pU(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function mb(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return fU(n);case 1:return mU(n);case 2:return gU(n);case 3:return yU(n);default:return vU(n)}}function ZW(n,t,e){e===void 0&&(e=!1);var r="";e?r+=mb(n):r+=ia(n);var i=n.shapeInfo.logicalShape,a=t.logicalShape;return i.length<=a.length&&(e?r+=wU(n,t):r+=bU(n,t)),r}function QW(n,t){switch(n.length){case 0:return gb();case 1:return xU(n,t);case 2:return IU(n,t);case 3:return LU(n,t);default:return SU(n,t)}}function eU(n,t){switch(n.length){case 0:return gb();case 1:return AU(n,t);case 2:return RU(n,t);case 3:return TU(n,t);case 4:return NU(n,t);case 5:return _U(n,t);case 6:return CU(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function tU(n){return`
2020-11-03 15:34:36 +01:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return `+n.texture2D+`(textureSampler, uv).r;
}
2020-11-04 16:18:22 +01:00
`}function nU(n){return`
2020-11-03 15:34:36 +01:00
void setOutput(float val) {
`+n.output+` = vec4(val, 0, 0, 0);
}
2020-11-04 16:18:22 +01:00
`}function rU(n){return`
2020-11-03 15:34:36 +01:00
void setOutput(vec4 val) {
`+n.output+` = val;
}
2020-11-04 16:18:22 +01:00
`}function iU(n){var t=n.version+`
2020-11-03 15:34:36 +01:00
precision highp float;
precision highp int;
precision highp sampler2D;
`+n.varyingFs+` vec2 resultUV;
`+n.defineOutput+`
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
`+n.defineSpecialNaN+`
`+n.defineSpecialInf+`
`+n.defineRound+`
int imod(int x, int y) {
return x - y * (x / y);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
return res;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
2020-11-04 16:18:22 +01:00
`+OU+`
`+EU+`
`+DU+`
`;return t}var OU=`
2020-11-03 15:34:36 +01:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-11-04 16:18:22 +01:00
`,EU=`
2020-11-03 15:34:36 +01:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-11-04 16:18:22 +01:00
`,DU=`
2020-11-03 15:34:36 +01:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-11-04 16:18:22 +01:00
`,aU=`
2020-11-03 15:34:36 +01:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2020-11-04 16:18:22 +01:00
`;function gb(){return`
2020-11-03 15:34:36 +01:00
int getOutputCoords() {
return 0;
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}function xU(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?`
2020-11-03 15:34:36 +01:00
int getOutputCoords() {
return 2 * int(resultUV.x * `+e[1]+`.0);
}
`:e[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * `+e[0]+`.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
return 2 * (resTexRC.x * `+e[1]+` + resTexRC.y);
}
2020-11-04 16:18:22 +01:00
`}function AU(n,t){return t[0]===1?`
2020-11-03 15:34:36 +01:00
int getOutputCoords() {
return int(resultUV.x * `+t[1]+`.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * `+t[0]+`.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
return resTexRC.x * `+t[1]+` + resTexRC.y;
}
2020-11-04 16:18:22 +01:00
`}function LU(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[2]/2),i=r*Math.ceil(n[1]/2);return`
2020-11-03 15:34:36 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = resTexRC.x * `+e[1]+` + resTexRC.y;
int b = index / `+i+`;
index -= b * `+i+`;
int r = 2 * (index / `+r+`);
int c = imod(index, `+r+`) * 2;
return ivec3(b, r, c);
}
2020-11-04 16:18:22 +01:00
`}function TU(n,t){var e=gi(["r","c","d"],n);return`
2020-11-03 15:34:36 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
`+e+`
return ivec3(r, c, d);
}
2020-11-04 16:18:22 +01:00
`}function SU(n,t){for(var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[n.length-1]/2),i=r*Math.ceil(n[n.length-2]/2),a=i,s="",o="b, r, c",c=2;c<n.length-1;c++)a*=n[n.length-c-1],s=`
2020-11-03 15:34:36 +01:00
int b`+c+" = index / "+a+`;
index -= b`+c+" * "+a+`;
`+s,o="b"+c+", "+o;return`
ivec`+n.length+` getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = resTexRC.x * `+e[1]+` + resTexRC.y;
`+s+`
int b = index / `+i+`;
index -= b * `+i+`;
int r = 2 * (index / `+r+`);
int c = imod(index, `+r+`) * 2;
return ivec`+n.length+"("+o+`);
}
2020-11-04 16:18:22 +01:00
`}function NU(n,t){var e=gi(["r","c","d","d2"],n);return`
2020-11-03 15:34:36 +01:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
`+e+`
return ivec4(r, c, d, d2);
}
2020-11-04 16:18:22 +01:00
`}function _U(n,t){var e=gi(["r","c","d","d2","d3"],n);return`
2020-11-03 15:34:36 +01:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+t[0]+`,
`+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
`+e+`
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}function CU(n,t){var e=gi(["r","c","d","d2","d3","d4"],n);return`
2020-11-03 15:34:36 +01:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
`+e+`
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}function IU(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(_.util.arraysEqual(n,t))return`
2020-11-03 15:34:36 +01:00
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(`+e[0]+", "+e[1]+`));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`;var r=Math.ceil(n[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = resTexRC.x * `+e[1]+` + resTexRC.y;
int r = 2 * (index / `+r+`);
int c = imod(index, `+r+`) * 2;
return ivec2(r, c);
}
2020-11-04 16:18:22 +01:00
`}function RU(n,t){return _.util.arraysEqual(n,t)?`
2020-11-03 15:34:36 +01:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(`+t[0]+", "+t[1]+`));
}
`:n[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
return ivec2(index, 0);
}
`:n[0]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+t[0]+", "+t[1]+`));
int index = resTexRC.x * `+t[1]+` + resTexRC.y;
int r = index / `+n[1]+`;
int c = index - r * `+n[1]+`;
return ivec2(r, c);
}
2020-11-04 16:18:22 +01:00
`}function yi(n){return"offset"+n}function fU(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Bt();return`
2020-11-03 15:34:36 +01:00
vec4 `+e+`() {
return `+r.texture2D+"("+t+`, halfCR);
}
2020-11-04 16:18:22 +01:00
`}function oU(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return"float "+e+"() {return "+t+";}";var r=n.shapeInfo.texShape,i=r[0],a=r[1];if(i===1&&a===1)return`
2020-11-03 15:34:36 +01:00
float `+e+`() {
return sampleTexture(`+t+`, halfCR);
}
2020-11-04 16:18:22 +01:00
`;var s=n.shapeInfo.texShape,o=s[0],c=s[1],l=yi(t);return`
2020-11-03 15:34:36 +01:00
float `+e+`() {
vec2 uv = uvFromFlat(`+o+", "+c+", "+l+`);
return sampleTexture(`+t+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function mU(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=Bt();return`
2020-11-03 15:34:36 +01:00
vec4 `+e+`(int index) {
vec2 uv = packedUVfrom1D(
`+i[0]+", "+i[1]+`, index);
return `+a.texture2D+"("+t+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function cU(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return`
2020-11-03 15:34:36 +01:00
float `+e+`(int index) {
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
`;var r=n.shapeInfo.texShape,i=r[0],a=r[1];if(a===1&&i===1)return`
float `+e+`(int index) {
return sampleTexture(`+t+`, halfCR);
}
2020-11-04 16:18:22 +01:00
`;var s=yi(t);return a===1?`
2020-11-03 15:34:36 +01:00
float `+e+`(int index) {
vec2 uv = vec2(0.5, (float(index + `+s+") + 0.5) / "+i+`.0);
return sampleTexture(`+t+`, uv);
}
`:i===1?`
float `+e+`(int index) {
vec2 uv = vec2((float(index + `+s+") + 0.5) / "+a+`.0, 0.5);
return sampleTexture(`+t+`, uv);
}
`:`
float `+e+`(int index) {
vec2 uv = uvFromFlat(`+i+", "+a+", index + "+s+`);
return sampleTexture(`+t+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function gU(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=Bt();if(i!=null&&_.util.arraysEqual(t,i))return`
2020-11-03 15:34:36 +01:00
vec4 `+r+`(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+s+".0, "+a+`.0);
return `+o.texture2D+"("+e+`, uv);
}
`;var c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=Math.ceil(t[1]/2);return`
vec4 `+r+`(int row, int col) {
vec2 uv = packedUVfrom2D(`+l+", "+c[0]+", "+c[1]+`, row, col);
return `+o.texture2D+"("+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function lU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=n.shapeInfo.texShape;if(i!=null&&_.util.arraysEqual(t,i)){var a=i[0],s=i[1];return`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+s+".0, "+a+`.0);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}var o=_.util.squeezeShape(t),c=o.newShape,l=o.keptDims,u=c;if(u.length<t.length){var h=sa(n,u),d=["row","col"];return`
`+ia(h)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(d,l)+`);
2020-11-03 15:34:36 +01:00
}
`}if(n.shapeInfo.isUniform)return`
float `+r+`(int row, int col) {
int index = round(dot(vec2(row, col), vec2(`+t[1]+`, 1)));
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
2020-11-04 16:18:22 +01:00
`;var p=i[0],f=i[1],m=yi(e);return f===1?`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col) {
float index = dot(vec3(row, col, `+m+"), vec3("+t[1]+`, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / `+p+`.0);
return sampleTexture(`+e+`, uv);
}
`:p===1?`
float `+r+`(int row, int col) {
float index = dot(vec3(row, col, `+m+"), vec3("+t[1]+`, 1, 1));
vec2 uv = vec2((index + 0.5) / `+f+`.0, 0.5);
return sampleTexture(`+e+`, uv);
}
`:`
float `+r+`(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+t[1]+" + col + "+m+`;
vec2 uv = uvFromFlat(`+p+", "+f+`, index);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function yU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=n.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){var s=t.slice(1),o=[1,2],c=sa(n,s),l=["b","row","col"];return`
`+mb(c)+`
2020-11-03 15:34:36 +01:00
vec4 `+r+`(int b, int row, int col) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(l,o)+`);
2020-11-03 15:34:36 +01:00
}
`}var u=a[0],h=a[1],d=Math.ceil(t[2]/2),p=d*Math.ceil(t[1]/2),f=Bt();return`
vec4 `+r+`(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
`+u+", "+h+", "+p+", "+d+`, b, row, col);
return `+f.texture2D+"("+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function uU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[1]*t[2],a=t[2],s=_.util.squeezeShape(t),o=s.newShape,c=s.keptDims,l=o;if(l.length<t.length){var u=sa(n,l),h=["row","col","depth"];return`
`+ia(u)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(h,c)+`);
2020-11-03 15:34:36 +01:00
}
`}if(n.shapeInfo.isUniform)return`
float `+r+`(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(`+i+", "+a+`, 1)));
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
`;var d=n.shapeInfo.texShape,p=d[0],f=d[1],m=n.shapeInfo.flatOffset;if(f===i&&m==null)return`
float `+r+`(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(`+a+`, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+f+".0, "+p+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(f===a&&m==null)return`
float `+r+`(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(`+t[1]+`, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+f+".0, "+p+`.0);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`;var g=yi(e);return`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+i+" + col * "+a+" + depth + "+g+`;
vec2 uv = uvFromFlat(`+p+", "+f+`, index);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function vU(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=Bt();return`
2020-11-03 15:34:36 +01:00
vec4 `+i+"("+h+`) {
int index = `+d+`;
int texR = index / `+c+`;
int texC = index - texR * `+c+`;
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+c+", "+o+`);
return `+f.texture2D+"("+r+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function hU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[3],a=t[2]*i,s=t[1]*a,o=_.util.squeezeShape(t),c=o.newShape,l=o.keptDims;if(c.length<t.length){var u=sa(n,c),h=["row","col","depth","depth2"];return`
`+ia(u)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(h,l)+`);
2020-11-03 15:34:36 +01:00
}
`}if(n.shapeInfo.isUniform)return`
float `+r+`(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(`+s+", "+a+", "+i+`, 1)));
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
`;var d=n.shapeInfo.flatOffset,p=n.shapeInfo.texShape,f=p[0],m=p[1];if(m===s&&d==null)return`
float `+r+`(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(`+a+", "+i+`, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+m+".0, "+f+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(m===i&&d==null)return`
float `+r+`(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(`+t[1]*t[2]+", "+t[2]+`, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+m+".0, "+f+`.0);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`;var g=yi(e);return`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+s+" + col * "+a+` +
depth * `+i+` + depth2;
vec2 uv = uvFromFlat(`+f+", "+m+", index + "+g+`);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function dU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[4],a=t[3]*i,s=t[2]*a,o=t[1]*s,c=_.util.squeezeShape(t),l=c.newShape,u=c.keptDims;if(l.length<t.length){var h=sa(n,l),d=["row","col","depth","depth2","depth3"];return`
`+ia(h)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(d,u)+`);
2020-11-03 15:34:36 +01:00
}
`}if(n.shapeInfo.isUniform)return`
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(`+o+", "+s+", "+a+", "+i+`)) +
depth3;
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
`;var p=n.shapeInfo.flatOffset,f=n.shapeInfo.texShape,m=f[0],g=f[1];if(g===o&&p==null)return`
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(`+s+", "+a+", "+i+`, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+g+".0, "+m+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(g===i&&p==null)return`
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(`+t[1]*t[2]*t[3]+`,
`+t[2]*t[3]+", "+t[3]+`, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+g+".0, "+m+`.0);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`;var y=yi(e);return`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+o+" + col * "+s+" + depth * "+a+` +
depth2 * `+i+" + depth3 + "+y+`;
vec2 uv = uvFromFlat(`+m+", "+g+`, index);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function pU(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=_.util.squeezeShape(t),a=i.newShape,s=i.keptDims;if(a.length<t.length){var o=sa(n,a),c=["row","col","depth","depth2","depth3","depth4"];return`
`+ia(o)+`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2020-11-04 16:18:22 +01:00
return `+r+"("+oa(c,s)+`);
2020-11-03 15:34:36 +01:00
}
`}var l=t[5],u=t[4]*l,h=t[3]*u,d=t[2]*h,p=t[1]*d;if(n.shapeInfo.isUniform)return`
float `+r+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(`+p+", "+d+", "+h+", "+u+`)) +
dot(
vec2(depth3, depth4),
vec2(`+l+`, 1)));
2020-11-04 16:18:22 +01:00
`+aa(n)+`
2020-11-03 15:34:36 +01:00
}
`;var f=n.shapeInfo.flatOffset,m=n.shapeInfo.texShape,g=m[0],y=m[1];if(y===p&&f==null)return`
float `+r+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(`+d+", "+h+", "+u+", "+l+`)) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+y+".0, "+g+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(y===l&&f==null)return`
float `+r+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(`+t[1]*t[2]*t[3]*t[4]+`,
`+t[2]*t[3]*t[4]+`,
`+t[3]*t[4]+`,
`+t[4]+`)) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+y+".0, "+g+`.0);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`;var w=yi(e);return`
2020-11-03 15:34:36 +01:00
float `+r+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+p+" + col * "+d+" + depth * "+h+` +
depth2 * `+u+" + depth3 * "+l+" + depth4 + "+w+`;
vec2 uv = uvFromFlat(`+g+", "+y+`, index);
return sampleTexture(`+e+`, uv);
}
2020-11-04 16:18:22 +01:00
`}function aa(n){var t=n.name,e=_.util.sizeFromShape(n.shapeInfo.logicalShape);return e<2?"return "+t+";":`
2020-11-03 15:34:36 +01:00
for (int i = 0; i < `+e+`; i++) {
if (i == index) {
return `+t+`[i];
}
}
2020-11-04 16:18:22 +01:00
`}function wU(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=fb(n.shapeInfo.logicalShape,t.logicalShape),c=Qe(s),l=s-a,u,h=["x","y","z","w","u","v"];a===0?u="":s<2&&o.length>=1?u="coords = 0;":u=o.map(function(x){return"coords."+h[x+l]+" = 0;"}).join(`
2020-11-03 15:34:36 +01:00
`);var d="";s<2&&a>0?d="coords":d=n.shapeInfo.logicalShape.map(function(x,L){return"coords."+h[L+l]}).join(", ");var p="return outputValue;",f=_.util.sizeFromShape(n.shapeInfo.logicalShape),m=f===1,g=_.util.sizeFromShape(t.logicalShape),y=g===1;if(a===1&&!m&&!y)p=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(m&&!y)s===1?p=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:p=`
return vec4(outputValue.x);
`;else if(o.length){var w=a-2,b=a-1;o.indexOf(w)>-1&&o.indexOf(b)>-1?p="return vec4(outputValue.x);":o.indexOf(w)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(b)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 `+i+`() {
`+c+` coords = getOutputCoords();
`+u+`
vec4 outputValue = get`+r+"("+d+`);
`+p+`
}
2020-11-04 16:18:22 +01:00
`}function bU(n,t){var e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),i="get"+r+"AtOutCoords",a=t.texShape,s=n.shapeInfo.texShape,o=n.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===c&&n.shapeInfo.flatOffset==null&&_.util.arraysEqual(s,a))return`
2020-11-03 15:34:36 +01:00
float `+i+`() {
return sampleTexture(`+e+`, resultUV);
}
2020-11-04 16:18:22 +01:00
`;var l=Qe(c),u=fb(n.shapeInfo.logicalShape,t.logicalShape),h=c-o,d,p=["x","y","z","w","u","v"];o===0?d="":c<2&&u.length>=1?d="coords = 0;":d=u.map(function(m){return"coords."+p[m+h]+" = 0;"}).join(`
2020-11-03 15:34:36 +01:00
`);var f="";return c<2&&o>0?f="coords":f=n.shapeInfo.logicalShape.map(function(m,g){return"coords."+p[g+h]}).join(", "),`
float `+i+`() {
`+l+` coords = getOutputCoords();
`+d+`
return get`+r+"("+f+`);
}
2020-11-04 16:18:22 +01:00
`}function Qe(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error("GPU for rank "+n+" is not yet supported")}function sa(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function oa(n,t){return t.map(function(e){return n[e]}).join(", ")}var kU=function(){function n(t,e,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,_.util.assert(t.length>2,function(){return"Packed arg"+(r.charAt(0).toUpperCase()+r.slice(1))+" supports only inputs with rank above 2."});var a=t[t.length-1],s=Math.ceil(a/e);this.outputShape=t.slice(0,-1),s>1&&this.outputShape.push(s),i||this.variableNames.push("bestIndicesA");var o=this.outputShape,c=o.length,l=Qe(c),u=Ut("coords",c),h,d;if(s===1){d=c+1;var p=Qe(d);h=`
2020-11-03 15:34:36 +01:00
`+p+" sourceLocR = "+p+"("+u.join()+`, 0);
++`+u[c-1]+`;
`+p+" sourceLocG = "+p+"("+u.join()+`, 0);
++`+u[c-2]+`;
`+p+" sourceLocA = "+p+"("+u.join()+`, 0);
--`+u[c-1]+`;
`+p+" sourceLocB = "+p+"("+u.join()+`, 0);
--`+u[c-2]+";"}else d=c,h=`
`+l+` sourceLocR = coords;
++`+u[c-1]+`;
`+l+` sourceLocG = coords;
++`+u[c-2]+`;
`+l+` sourceLocA = coords;
--`+u[c-1]+`;
`+l+` sourceLocB = coords;
--`+u[c-2]+";";var f=["x","y","z","w","u","v"].slice(0,d),m="."+f[d-1],g=f.map(function(O){return"int "+O}),y=Ut("sourceLocR",d-1).concat("inIdx.r"),w=Ut("sourceLocG",d-1).concat("inIdx.g"),b=Ut("sourceLocB",d-1).concat("inIdx.b"),x=Ut("sourceLocA",d-1).concat("inIdx.a"),L=r==="max"?"greaterThan":"lessThan",N=i?"":`
inIdx = round(vec4(getBestIndicesAChannel(`+y.join()+`),
getBestIndicesAChannel(`+w.join()+`),
getBestIndicesAChannel(`+b.join()+`),
getBestIndicesAChannel(`+x.join()+")));",I=`vec4(
getAChannel(`+y.join()+`),
hasNextCol ? getAChannel(`+w.join()+`) : 0.,
hasNextRow ? getAChannel(`+b.join()+`) : 0.,
hasNextRow && hasNextCol ? getAChannel(`+x.join()+") : 0.)",C=i?"":`
float getBestIndicesAChannel(`+g.join()+`) {
return getChannel(getBestIndicesA(`+f.join()+`),
vec2(`+f.slice(-2).join()+`));
}`;this.userCode=`
float getAChannel(`+g.join()+`) {
return getChannel(getA(`+f.join()+`),
vec2(`+f.slice(-2).join()+`));
}
`+C+`
void main() {
`+l+` coords = getOutputCoords();
bool hasNextCol = `+u[c-1]+" < "+(o[c-1]-1)+`;
bool hasNextRow = `+u[c-2]+" < "+(o[c-2]-1)+`;
`+h+`
ivec4 srcIdx = ivec4(sourceLocR`+m+", sourceLocG"+m+`,
sourceLocB`+m+", sourceLocA"+m+") * "+e+`;
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = `+I+`;
for (int i = 0; i < `+e+`; i++) {
inIdx = srcIdx;
`+N+`
vec4 candidate = `+I+`;
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(`+L+`(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
2020-11-04 16:18:22 +01:00
`}return n}();var FU=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,o=t.dilationWidth,c=t.effectiveFilterHeight,l=t.effectiveFilterWidth,u=c-1-t.padInfo.top,h=l-1-t.padInfo.left,d=1/(e*r);this.userCode=`
2020-11-03 15:34:36 +01:00
const ivec2 pads = ivec2(`+u+", "+h+`);
const float avgMultiplier = float(`+d+`);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < `+c+`;
wR += `+s+`) {
float dyR = float(dyRCorner + wR) / `+i+`.0;
if (dyR < 0.0 || dyR >= `+t.outHeight+`.0 || fract(dyR) > 0.0) {
continue;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
int idyR = int(dyR);
for (int wC = 0; wC < `+l+`;
wC+= `+o+`) {
float dyC = float(dyCCorner + wC) / `+a+`.0;
if (dyC < 0.0 || dyC >= `+t.outWidth+`.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),WU=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-10-12 01:22:43 +02:00
}
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;
}
}
}
setOutput(dotProd);
}
2020-11-04 16:18:22 +01:00
`}return n}();var yb=`
2020-11-03 15:34:36 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-11-04 16:18:22 +01:00
`,UU=`
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-04 16:18:22 +01:00
`,BU=`
2020-11-03 15:34:36 +01:00
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2020-11-04 16:18:22 +01:00
`,zU="return float(a == b);",PU="return float(a < b);",MU="return float(a <= b);",HU="return float(a > b);",VU="return float(a >= b);",GU="return float(a >= 1.0 && b >= 1.0);",qU="return float(a >= 1.0 || b >= 1.0);",YU=yb+`
2020-11-03 15:34:36 +01:00
return max(a, b);
2020-11-04 16:18:22 +01:00
`,KU=yb+`
2020-11-03 15:34:36 +01:00
return min(a, b);
2020-11-04 16:18:22 +01:00
`,jU=`if (b == 0.0) return NAN;
return mod(a, b);`,$U="return (b >= 1.0) ? a : a * (b + 1.0);",vb="return (a < 0.) ? b * a : a;",Wt=function(){function n(t,e,r){this.variableNames=["A","B"],this.outputShape=_.backend_util.assertAndGetBroadcastShape(e,r),this.userCode=`
2020-11-03 15:34:36 +01:00
float binaryOperation(float a, float b) {
`+t+`
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2020-11-04 16:18:22 +01:00
`}return n}();var Ko=`
2020-11-03 15:34:36 +01:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-11-04 16:18:22 +01:00
`,XU=`
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]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
2020-11-04 16:18:22 +01:00
`,JU=`
2020-11-03 15:34:36 +01:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2020-11-04 16:18:22 +01:00
`+Ko+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-04 16:18:22 +01:00
`,wb=`
2020-11-03 15:34:36 +01:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2020-11-04 16:18:22 +01:00
`,ZU=`
2020-11-03 15:34:36 +01:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2020-11-04 16:18:22 +01:00
`,QU=`
2020-11-03 15:34:36 +01:00
return vec4(equal(a, b));
2020-11-04 16:18:22 +01:00
`,eB=`
2020-11-03 15:34:36 +01:00
return vec4(lessThan(a, b));
2020-11-04 16:18:22 +01:00
`,tB=`
2020-11-03 15:34:36 +01:00
return vec4(lessThanEqual(a, b));
2020-11-04 16:18:22 +01:00
`,nB=`
2020-11-03 15:34:36 +01:00
return vec4(greaterThan(a, b));
2020-11-04 16:18:22 +01:00
`,rB=`
2020-11-03 15:34:36 +01:00
return vec4(greaterThanEqual(a, b));
2020-11-04 16:18:22 +01:00
`,iB=`
2020-11-03 15:34:36 +01:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-11-04 16:18:22 +01:00
`,aB=`
2020-11-03 15:34:36 +01:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2020-11-04 16:18:22 +01:00
`,sB=`
2020-11-03 15:34:36 +01:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-04 16:18:22 +01:00
`+Ko+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-04 16:18:22 +01:00
`,oB=`
2020-11-03 15:34:36 +01:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-04 16:18:22 +01:00
`+Ko+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-04 16:18:22 +01:00
`,cB=`
2020-11-03 15:34:36 +01:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-11-04 16:18:22 +01:00
`+Ko+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-04 16:18:22 +01:00
`,rr=function(){function n(t,e,r,i){i===void 0&&(i=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.backend_util.assertAndGetBroadcastShape(e,r);var a=this.outputShape.length,s="";if(i)if(a===0||_.util.sizeFromShape(this.outputShape)===1)s=`
2020-11-03 15:34:36 +01:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-11-04 07:11:24 +01:00
`;else{var o=Qe(a);if(s=`
2020-11-03 15:34:36 +01:00
`+o+` coords = getOutputCoords();
`,a===1)s+=`
result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{var c=Ut("coords",a);s+=`
bool nextRowOutOfBounds =
(`+c[a-2]+" + 1) >= "+this.outputShape[a-2]+`;
bool nextColOutOfBounds =
(`+c[a-1]+" + 1) >= "+this.outputShape[a-1]+`;
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
`+t+`
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
`+s+`
setOutput(result);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var lB=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-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput(clamp(value, minVal, maxVal));
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t,e){var r=this;return function(i,a){r.minLoc==null&&(r.minLoc=i.getUniformLocationNoThrow(a,"minVal"),r.maxLoc=i.getUniformLocationNoThrow(a,"maxVal")),i.gl.uniform1f(r.minLoc,t),i.gl.uniform1f(r.maxLoc,e)}},n}();var uB=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-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t,e){var r=this;return function(i,a){r.minLoc==null&&(r.minLoc=i.getUniformLocationNoThrow(a,"minVal"),r.maxLoc=i.getUniformLocationNoThrow(a,"maxVal")),i.gl.uniform1f(r.minLoc,t),i.gl.uniform1f(r.maxLoc,e)}},n}();var hB=function(){function n(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2020-11-04 16:18:22 +01:00
`}return n}();var dB=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,r=t.strideWidth,i=t.padInfo.top,a=t.padInfo.left,s=t.dataFormat==="channelsLast";this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < `+t.batchSize+`; b++) {
for (int yR = 0; yR < `+t.outHeight+`; yR++) {
int xR = wR + yR * `+e+" - "+i+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int yC = 0; yC < `+t.outWidth+`; yC++) {
int xC = wC + yC * `+r+" - "+a+`;
if (xC < 0 || xC >= `+t.inWidth+`) {
continue;
}
if (`+s+`) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
2020-10-27 15:06:01 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-27 15:06:01 +01:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),pB=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-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
}
2020-11-04 16:18:22 +01:00
`}return n}(),fB=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;
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
}
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),mB=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
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;
}
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;
}
2020-10-12 01:22:43 +02:00
}
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var gB=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;
}
for (int yC = 0; yC < `+t.outWidth+`; yC++) {
int xC = wC + yC * `+r+" - "+a+`;
if (xC < 0 || xC >= `+t.inWidth+`) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
2020-10-12 01:22:43 +02:00
}
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),yB=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;
2020-10-12 01:22:43 +02:00
}
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var bb=function(){function n(t,e,r,i){e===void 0&&(e=!1),r===void 0&&(r=null),i===void 0&&(i=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,s=t.padInfo.left,o=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,h=t.filterHeight,d=t.filterWidth,p=Math.floor(t.inChannels/4)*4,f=t.inChannels%4,m=t.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,w=m?3:1,b="",x="";r&&(i?b=`float activation(float a) {
2020-11-03 15:34:36 +01:00
float b = getPreluActivationWeightsAtOutCoords();
`+r+`
}`:b=`
float activation(float x) {
`+r+`
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`,x="result = activation(result);");var L=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+b+`
const ivec2 strides = ivec2(`+o+", "+c+`);
const ivec2 pads = ivec2(`+a+", "+s+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[`+w+`];
ivec2 xRCCorner =
ivec2(coords[`+g+"], coords["+y+`]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < `+h+`; wR++) {
int xR = xRCorner + wR * `+l+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
for (int wC = 0; wC < `+d+`; wC++) {
int xC = xCCorner + wC * `+u+`;
if (xC < 0 || xC >= `+t.inWidth+`) {
continue;
}
for (int d1 = 0; d1 < `+p+`; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (`+m+`) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (`+(f===1)+`) {
if (`+m+`) {
dotProd +=
getX(batch, xR, xC, `+p+`) *
getW(wR, wC, `+p+`, d2);
} else {
dotProd +=
getX(batch, `+p+`, xR, xC) *
getW(wR, wC, `+p+`, d2);
}
} else if (`+(f===2)+`) {
vec2 wValues = vec2(
getW(wR, wC, `+p+`, d2),
getW(wR, wC, `+p+` + 1, d2)
);
if (`+m+`) {
vec2 xValues = vec2(
getX(batch, xR, xC, `+p+`),
getX(batch, xR, xC, `+p+` + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, `+p+`, xR, xC),
getX(batch, `+p+` + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (`+(f===3)+`) {
vec3 wValues = vec3(
getW(wR, wC, `+p+`, d2),
getW(wR, wC, `+p+` + 1, d2),
getW(wR, wC, `+p+` + 2, d2)
);
if (`+m+`) {
vec3 xValues = vec3(
getX(batch, xR, xC, `+p+`),
getX(batch, xR, xC, `+p+` + 1),
getX(batch, xR, xC, `+p+` + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, `+p+`, xR, xC),
getX(batch, `+p+` + 1, xR, xC),
getX(batch, `+p+` + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
}
float result = dotProd;
`+L+`
`+x+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}(),vB=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
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;
}
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);
}
if (`+(m===1)+`) {
dotProd +=
getX(batch, xF, xR, xC, `+f+`) *
getW(wF, wR, wC, `+f+`, d2);
} else if (`+(m===2)+`) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, `+f+`),
getX(batch, xF, xR, xC, `+f+` + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, `+f+`, d2),
getW(wF, wR, wC, `+f+` + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (`+(m===3)+`) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, `+f+`),
getX(batch, xF, xR, xC, `+f+` + 1),
getX(batch, xF, xR, xC, `+f+` + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, `+f+`, d2),
getW(wF, wR, wC, `+f+` + 1, d2),
getW(wF, wR, wC, `+f+` + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
2020-11-04 16:18:22 +01:00
`}return n}();var xb=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
for (int wC = 0; wC < `+f+`; wC++) {
int xC = xCCorner + wC * `+d+`;
if (xC < 0 || xC >= `+s+`) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
float result = dotProd;
`+w+`
`+y+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var Lb=function(){function n(t,e,r,i){e===void 0&&(e=!1),r===void 0&&(r=null),i===void 0&&(i=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var a=t.inHeight,s=t.inWidth,o=t.padInfo.top,c=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,h=t.dilationHeight,d=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,m=f,g="int xR; int xC; int xCOffset;",y=0;y<p;y++)for(var w=0;w<f;w++)g+=`
2020-11-03 15:34:36 +01:00
vec4 xTexelR`+y+"C"+w*2+` = vec4(0.);
vec4 wR`+y+"C"+w+` = vec4(0.);
vec4 xR`+y+"C"+w+" = vec4(0.);";for(var y=0;y<p;y++)for(var b=0;b<m;b++){var w=b*2;if(g+=`
xR = xRCorner + `+y*h+`;
xC = xCCorner + `+w*d+`;
`,u===1){if(w<f&&(c%2===1?g+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < `+a+" && xCOffset >= 0 && xCOffset < "+s+`) {
xTexelR`+y+"C"+w+` = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= `+s+`) {
xTexelR`+y+"C"+w+`.zw = vec2(0.);
}
} else {
xTexelR`+y+"C"+w+` = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < `+a+" && xCOffset >= 0 && xCOffset < "+s+`) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= `+s+`) {
previous.zw = vec2(0.);
}
xR`+y+"C"+w+" = vec4(previous.zw, xTexelR"+y+"C"+w+`.xy);
} else {
xR`+y+"C"+w+" = vec4(0, 0, xTexelR"+y+"C"+w+`.xy);
}
`:g+=`
if(xR >= 0 && xR < `+a+" && xC >= 0 && xC < "+s+`) {
xTexelR`+y+"C"+w+` = getX(batch, xR, xC, d1);
} else {
xTexelR`+y+"C"+w+` = vec4(0.);
}
xR`+y+"C"+w+" = xTexelR"+y+"C"+w+`;
`,w+1<f)){var x=c%2===0?_.util.nearestLargerEven(d):d;d%2===0&&c%2===1||d%2!==0&&c%2!==1?(g+=`
xCOffset = xC + `+c%2+" + "+x+`;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+y+"C"+(w+2)+` = getX(batch, xR, xCOffset, d1);
}
`,d>1&&(g+=`
xCOffset -= 2;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+y+"C"+w+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+y+"C"+w+` = vec4(0.);
}
`),g+=`
xR`+y+"C"+(w+1)+` = vec4(
xTexelR`+y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+`.xy);
`):g+=`
xCOffset = xC + `+x+`;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+y+"C"+(w+2)+` = getX(batch, xR, xCOffset, d1);
}
xR`+y+"C"+(w+1)+" = xTexelR"+y+"C"+(w+2)+`;
`}}else w<f&&(g+=`
if(xR >= 0 && xR < `+a+`) {
`,c%2===1?(g+=`
xCOffset = xC + 1 - `+u+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+y+"C"+w+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+y+"C"+w+` = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < `+s+`) {
xTexelR`+y+"C"+(w+2)+` = getX(batch, xR, xC + 1, d1);
} else {
xTexelR`+y+"C"+(w+2)+` = vec4(0.);
}
xR`+y+"C"+w+` = vec4(
xTexelR`+y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+`.zw);
`,w+1<f&&(g+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + `+u+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
final = getX(batch, xR, xCOffset, d1);
}
xR`+y+"C"+(w+1)+" = vec4(xTexelR"+y+"C"+(w+2)+`.xy, final.xy);
`)):(g+=`
if(xC >= 0 && xC < `+s+`) {
xTexelR`+y+"C"+w+` = getX(batch, xR, xC, d1);
} else {
xTexelR`+y+"C"+w+` = vec4(0.);
}
xCOffset = xC + `+u+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+y+"C"+(w+2)+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+y+"C"+(w+2)+` = vec4(0.);
}
xR`+y+"C"+w+` = vec4(
xTexelR`+y+"C"+w+".xy, xTexelR"+y+"C"+(w+2)+`.xy);
`,w+1<f&&(g+=`
xR`+y+"C"+(w+1)+` = vec4(
xTexelR`+y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+`.zw);
`)),g+="}");w<f&&(g+=`
vec4 wTexelR`+y+"C"+w+" = getW("+y+", "+w+`, d1, q);
wR`+y+"C"+w+" = vec4(wTexelR"+y+"C"+w+".xz, wTexelR"+y+"C"+w+`.xz);
`,w+1<f&&(g+=`
vec4 wTexelR`+y+"C"+(w+1)+" = getW("+y+", "+(w+1)+`, d1, q);
wR`+y+"C"+(w+1)+` =
vec4(wTexelR`+y+"C"+(w+1)+".xz, wTexelR"+y+"C"+(w+1)+".xz);"))}for(var y=0;y<p;y++)for(var w=0;w<f;w++)g+="dotProd += xR"+y+"C"+w+" * wR"+y+"C"+w+";";var L="",N="";r&&(i?L=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
`+r+`
}`:L=`vec4 activation(vec4 x) {
`+r+`
}`,N="result = activation(result);");var I=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+L+`
const ivec2 strides = ivec2(`+l+", "+u+`);
const ivec2 pads = ivec2(`+o+", "+c+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
`+g+`
vec4 result = dotProd;
`+I+`
`+N+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var wB=function(){function n(t,e,r,i,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var s=t[0],o=t[1],c=t[2],l=t[3],u=e[0],h=r[0],d=r[1];this.outputShape=[u,h,d,l];var p=i==="bilinear"?1:0,f=[o-1+".0",c-1+".0"],m=f[0],g=f[1],y=h>1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio","y1*"+m+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+m],w=y[0],b=y[1],x=y[2],L=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=L[0],I=L[1],C=L[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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
float height_scale = `+b+`;
float width_scale = `+I+`;
float in_y = `+x+`;
if( in_y < 0.0 || in_y > `+m+` ) {
setOutput(float(`+a+`));
return;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
float in_x = `+C+`;
if( in_x < 0.0 || in_x > `+g+` ) {
setOutput(float(`+a+`));
return;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(`+p+` == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
2020-11-04 16:18:22 +01:00
`}return n}(),Ab=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=t;var i=t.length,a=e?"0.0":"getX("+Sb(i,"coords")+")",s=t[t.length-1],o="",c="";e?(o=r?"end != "+(s-1):"end != 0",c=r?"end + 1":"end - 1"):(o=r?"end + pow2 < "+s:"end >= pow2",c=r?"end + pow2":"end - pow2"),this.userCode=`
2020-11-03 15:34:36 +01:00
uniform float index;
void main() {
2020-11-04 07:11:24 +01:00
`+Qe(i)+` coords = getOutputCoords();
2020-11-04 16:18:22 +01:00
int end = `+Ib(i,"coords")+`;
2020-11-03 15:34:36 +01:00
float val = `+a+`;
int pow2 = int(pow(2.0, index));
if (`+o+`) {
int idx = `+c+`;
2020-11-04 16:18:22 +01:00
`+Ib(i,"coords")+` = idx;
val += getX(`+Sb(i,"coords")+`);
2020-11-03 15:34:36 +01:00
}
setOutput(val);
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.index==null&&(e.index=r.getUniformLocation(i,"index")),r.gl.uniform1f(e.index,t)}},n}();function Sb(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 Ib(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 bB=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=is.DENSE;var e=ss(t),r=Bt();this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-04 16:18:22 +01:00
`+gi(["r","c","d"],t)+`
2020-11-03 15:34:36 +01:00
return ivec3(r, c, d);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = 4 * (resTexRC.x * `+e[1]+` + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`+r.output+` = result;
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var xB=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=is.DENSE;var e=ss(t),r=Bt();this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-04 16:18:22 +01:00
`+gi(["r","c","d"],t)+`
2020-11-03 15:34:36 +01:00
return ivec3(r, c, d);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = 4 * (resTexRC.x * `+e[1]+` + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
`+r.output+` = result;
}
2020-11-04 16:18:22 +01:00
`}return n}();var LB=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=r,this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = `+this.getHeightCoordString()+`;
int w = `+this.getWidthCoordString()+`;
int d = `+this.getDepthCoordString()+`;
int in_h = h / `+e+`;
int offset_h = imod(h, `+e+`);
int in_w = w / `+e+`;
int offset_w = imod(w, `+e+`);
int offset_d = (offset_h * `+e+` + offset_w) *
`+this.getOutputDepthSize()+`;
int in_d = d + offset_d;
float result = `+this.getInputSamplingString()+`;
setOutput(result);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},n.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},n.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},n.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},n.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},n}();var SB=function(){function n(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var IB=function(){function n(t){this.variableNames=["A"],this.outTexUsage=cn.DOWNLOAD;var e=Bt();this.outputShape=t,this.userCode=`
`+pb+`
2020-11-03 15:34:36 +01:00
void main() {
float x = getAAtOutCoords();
`+e.output+` = encode_float(x);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var AB=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=cn.DOWNLOAD;var e=Bt();this.outputShape=t,this.userCode=`
`+pb+`
2020-11-03 15:34:36 +01:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
`+e.output+` = encode_float(x);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var TB=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"];var i=Bt(),a=e[0],s=e[1];this.outputShape=t;var o="result";r&&(o="floor(result * 255. + 0.5)"),this.userCode=`
`+$d(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];
}
`+i.output+" = vec4("+o+`, 0., 0., 0.);
}
2020-11-04 16:18:22 +01:00
`}return n}();var NB=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var i=Bt(),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];
}
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
`}this.userCode=`
2020-11-04 16:18:22 +01:00
`+$d(t)+`
2020-11-03 15:34:36 +01:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
`+o+`
`+i.output+" = "+c+`;
}
2020-11-04 16:18:22 +01:00
`}return n}();var _B=function(){function n(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.valueLoc==null&&(e.valueLoc=r.getUniformLocationNoThrow(i,"value")),r.gl.uniform1f(e.valueLoc,t)}},n}();var RB=function(){function n(t,e,r){this.variableNames=["A","indices"];var i=t.slice();i[r]=e,this.outputShape=i,this.rank=i.length;var a=Qe(this.rank),s=CB(t,r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
}
2020-11-04 16:18:22 +01:00
`}return n}();function CB(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 OB=function(){function n(t,e,r){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=r;var i=Qe(e.length),a=Qe(r.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2020-11-03 15:34:36 +01:00
`+i+" strides = "+i+"("+this.strides+`);
void main() {
`+a+` coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < `+this.sliceDim+`; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * `+s+`;
}
setOutput(getX(flattenIndex, coords[1]));
}
2020-11-04 16:18:22 +01:00
`}return n}();function Tb(n){var t=Bt(),e=t.version+`
2020-11-03 15:34:36 +01:00
precision highp float;
`+t.attribute+` vec3 clipSpacePos;
`+t.attribute+` vec2 uv;
`+t.varyingVs+` vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2020-11-04 16:18:22 +01:00
}`;return Gw(n,e)}function Nb(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 jw(n,t)}function _b(n){var t=new Uint16Array([0,1,2,2,1,3]);return $w(n,t)}function us(n,t,e,r,i,a){Jw(t,e);var s=Xw(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 Xd(n){return n.internalFormatFloat}function Cb(n,t,e,r){var i=as(t,e),a=i[0],s=i[1];return us(n,a,s,Xd(r),r.textureFormatFloat,n.FLOAT)}function Jd(n){return n.internalFormatHalfFloat}function Rb(n,t,e,r){var i=as(t,e),a=i[0],s=i[1];return us(n,a,s,Jd(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Zd(n){return n.downloadTextureFormat}function Ob(n,t,e,r){var i=as(t,e),a=i[0],s=i[1];return us(n,a,s,Zd(r),n.RGBA,n.UNSIGNED_BYTE)}function Qd(n){return n.internalFormatPackedFloat}function Eb(n,t,e,r){var i=ta(t,e),a=i[0],s=i[1];return us(n,a,s,Qd(r),n.RGBA,n.FLOAT)}function ep(n){return n.internalFormatPackedHalfFloat}function Db(n,t,e,r){var i=ta(t,e),a=i[0],s=i[1];return us(n,a,s,ep(r),n.RGBA,r.textureTypeHalfFloat)}function kb(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=Vd(n,t,"clipSpacePos",e,3,a,r);return s&&Vd(n,t,"uv",e,2,a,i)}function Fb(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 Wb(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 Ub(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 Bb(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 zb(n,t,e,r){var i=as(t,e),a=i[0],s=i[1],o=4,c=new Uint8Array(oW(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 Pb(n,t,e,r,i,a,s,o){var c=n,l=new Float32Array(cW(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 Mb(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 EB={__proto__:null,createVertexShader:Tb,createVertexBuffer:Nb,createIndexBuffer:_b,getInternalFormatForFloat32MatrixTexture:Xd,createFloat32MatrixTexture:Cb,getInternalFormatForFloat16MatrixTexture:Jd,createFloat16MatrixTexture:Rb,getInternalFormatForUnsignedBytesMatrixTexture:Zd,createUnsignedBytesMatrixTexture:Ob,getInternalFormatForPackedMatrixTexture:Qd,createPackedMatrixTexture:Eb,getInternalFormatForFloat16PackedMatrixTexture:ep,createFloat16PackedMatrixTexture:Db,bindVertexProgramAttributeStreams:kb,uploadDenseMatrixToTexture:Fb,uploadPixelDataToTexture:Wb,createBufferFromOutputTexture:Ub,downloadFloat32MatrixFromBuffer:Bb,downloadByteEncodedFloatMatrixFromOutputTexture:zb,
2020-11-03 15:34:36 +01:00
blockIndex = rc.y + `+N+`;
pos = rc.x + `+L+`;
if(blockIndex < `+t[1]+" && pos < "+t[0]+`) {
offsetY = int(blockIndex / (`+l+")) * "+o+" - "+f+`;
d0 = offsetY + `+h+" * (pos / "+m+`);
if(d0 < `+e[w]+` && d0 >= 0) {
offsetX = int(mod(float(blockIndex), `+l+".) * "+s+". - "+p+`.);
d1 = offsetX + `+u+" * (int(mod(float(pos), "+m+".) / "+a+`.));
if(d1 < `+e[b]+` && d1 >= 0) {
ch = int(mod(float(pos), `+a+`.));
if (`+y+`) {
innerDims = vec2(d1, ch);
result[`+(L*2+N)+`] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
2020-10-23 00:50:09 +02:00
} else {
2020-11-03 15:34:36 +01:00
innerDims = vec2(d0, d1);
result[`+(L*2+N)+`] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
}
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
`+x+`
`+g.output+` = result;
}
2020-11-04 16:18:22 +01:00
`}return n}();var BB=function(){function n(t,e,r,i,a){this.variableNames=["x"],this.outputShape=[];var s=e,o=t[3]-1;this.outputShape=t;var c,l="float("+r+") + float("+i+") * sum";a===.5?c="inversesqrt("+l+")":a===1?c="1.0/("+l+")":c="exp(log("+l+") * float(-"+a+"));",this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -`+s+"; j <= "+s+`; j++) {
int idx = d + j;
if (idx >= 0 && idx <= `+o+`) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * `+c+`;
setOutput(val);
}
2020-11-04 16:18:22 +01:00
`}return n}();var zB=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
else {
break;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
norm = float(`+i+") * norm + float("+r+`);
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
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;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
else {
break;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
}
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var PB=function(){function n(t,e,r,i,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var s=e,o=t[3]-1;this.outputShape=t;var c,l="float("+r+") + float("+i+") * sum";a===.5?c="inversesqrt("+l+")":a===1?c="1.0/("+l+")":c="exp(log("+l+") * float(-"+a+"));",this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < `+this.outputShape[3]+`;
bool hasNextRow = c < `+this.outputShape[2]+`;
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - `+s+`;
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
ivec2 depth = ivec2(d, d + 1);
for (int j = - `+s+"; j <= "+s+`; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+o+`));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
}
cache.xy = z.yw;
sum += z * z;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
vec4 result = xAtOutputCoords * `+c+`;
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var MB=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
int idyR = int(dyR);
for (int wC = 0; wC < `+s+`; wC++) {
float dyC = float(dyCCorner + wC) / `+r+`.0;
if (dyC < 0.0 || dyC >= `+t.outWidth+`.0 ||
fract(dyC) > 0.0) {
continue;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = `+l+` - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * `+s+` + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
2020-10-23 00:50:09 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),HB=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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
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;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
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;
2020-10-12 01:22:43 +02:00
}
2020-11-01 20:16:47 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(dotProd);
2020-11-01 20:16:47 +01:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var tp=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]+`);
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
return result;
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
`+y+`
`+g+`
setOutput(result);
2020-11-01 20:16:47 +01:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var VB=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-01 20:16:47 +01:00
}
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
// If no other event happened, last event happened.
setOutput(float(`+(e-1)+`));
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.seedLoc==null&&(e.seedLoc=r.getUniformLocation(i,"seed")),r.gl.uniform1f(e.seedLoc,t)}},n}();var GB=function(){function n(t,e,r,i){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(`+i+"), float("+r+`),
float(index == coords.y)));
}
2020-11-04 16:18:22 +01:00
`}return n}();var jB=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(e===0)this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-11-04 16:18:22 +01:00
`;else{var r=Ut("rc",e),i=Qe(e),a=qB(e,t,r),s=YB(e,t[t.length-1],t[t.length-2],r),o=KB(t,r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+i+` rc = getOutputCoords();
if(`+a+`) {
setOutput(vec4(0));
} else {
`+s+`
setOutput(vec4(`+o+`));
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
}
2020-11-04 16:18:22 +01:00
`}}return n}();function $B(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 qB(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 YB(n,t,e,r){if(n===1)return"";var i=r.slice(-2);return`
2020-11-03 15:34:36 +01:00
int r = `+i[0]+`;
int c = `+i[1]+`;
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= `+t+`;
bool rEdge = rp1 >= `+e+`;
2020-11-04 16:18:22 +01:00
`}function KB(n,t){var e=n.length,r=$B(e,t);return e===1?`getA(rc),
2020-11-03 15:34:36 +01:00
rc + 1 >= `+n[0]+` ? 0. : getA(rc + 1),
0, 0`:"getA("+r[0]+`),
cEdge ? 0. : getA(`+r[1]+`),
rEdge ? 0. : getA(`+r[2]+`),
2020-11-04 16:18:22 +01:00
rEdge || cEdge ? 0. : getA(`+r[3]+")"}var XB=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=e.map(function(l,u){return l[0]+t[u]+l[1]});var i=t.length,a=Qe(i),s=e.map(function(l){return l[0]}).join(","),o=e.map(function(l,u){return l[0]+t[u]}).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,i);if(i===1){this.userCode=`
2020-11-03 15:34:36 +01:00
int start = `+s+`;
int end = `+o+`;
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(`+r+`));
} else {
setOutput(getX(outC - start));
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
}
`;return}this.userCode=`
`+a+" start = "+a+"("+s+`);
`+a+" end = "+a+"("+o+`);
void main() {
`+a+` outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(`+r+`));
} else {
`+a+` coords = outC - start;
setOutput(getX(`+c+`));
}
}
2020-11-04 16:18:22 +01:00
`}return n}();var JB=function(){function n(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(y,w){return y[0]+t[w]+y[1]});for(var i=t.length,a=Qe(i),s=e.map(function(y){return y[0]}).join(","),o=e.map(function(y,w){return y[0]+t[w]}).join(","),c=Ut("rc",i),l=Ut("source",i),u=c[i-1]+" < "+this.outputShape[i-1],h=i===1?"source":"vec2("+l.slice(-2).join()+")",d=[a+" rc = outputLoc;",c[i-1]+` += 1;
2020-11-03 15:34:36 +01:00
if(`+u+`) {
`,i===1?"":`}
rc = outputLoc;
`+c[i-2]+` += 1;
if(`+c[i-2]+" < "+this.outputShape[i-2]+") {",i===1?"":" "+c[i-1]+` += 1;
if(`+u+") {"],p=i===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",m=0,g=i===1?2:4;m<g;m++)f+=`
`+d[m]+`
if (`+p+`) {
result[`+m+"] = float("+r+`);
} else {
`+a+` source = rc - start;
result[`+m+"] = getChannel(getX("+l.join()+"), "+h+`);
}
`;f+=i===1?"} ":"}}",this.userCode=`
const `+a+" start = "+a+"("+s+`);
const `+a+" end = "+a+"("+o+`);
void main() {
`+a+` outputLoc = getOutputCoords();
vec4 result = vec4(0.);
`+f+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();var hs=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+`);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
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-10-12 01:22:43 +02:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(float(minMaxPosition));
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
`;return}var x="max",L=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(L="avgValue / count");var N=Math.floor(s/4)*4,I=s%4,C=`
if (`+m+`) {
avgValue += dot(values, ones);
} else {
minMaxValue = `+x+`(values, minMaxValue);
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
`;this.userCode=`
const ivec2 strides = ivec2(`+o+", "+c+`);
const ivec2 pads = ivec2(`+p+", "+f+`);
const float initializationValue = `+w+`;
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= `+t.inWidth+`) {
return initializationValue;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
count += 1.0;
return getX(batch, xR, xC, d);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(`+w+`);
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < `+h+`;
wR += `+l+`) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+N+`; wC += 4) {
int xC = xCCorner + wC * `+u+`;
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+u+`, d),
getValue(batch, xR, xC + 2 * `+u+`, d),
getValue(batch, xR, xC + 3 * `+u+`, d)
);
`+C+`
}
int xC = xCCorner + `+N+`;
if (`+(I===1)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
`+C+`
} else if (`+(I===2)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+u+`, d),
initializationValue,
initializationValue
);
`+C+`
} else if (`+(I===3)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+u+`, d),
getValue(batch, xR, xC + 2 * `+u+`, d),
initializationValue
);
`+C+`
}
}
2020-11-03 15:34:36 +01:00
setOutput(`+L+`);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}(),np=function(){function n(t,e,r,i,a){if(i===void 0&&(i=!1),a===void 0&&(a=!1),this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");var s=t.filterWidth,o=t.strideDepth,c=t.strideHeight,l=t.strideWidth,u=t.dilationDepth,h=t.dilationHeight,d=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,g=t.padInfo.front,y=t.padInfo.top,w=t.padInfo.left;this.outputShape=t.outShape;var b=e==="avg",x="0.0";if(b||(x="-1.0 / 1e-20"),r){var L=">=";this.userCode=`
2020-11-03 15:34:36 +01:00
const ivec3 strides =
ivec3(`+o+", "+c+", "+l+`);
const ivec3 pads = ivec3(`+g+", "+y+", "+w+`);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < `+p+`;
wD += `+u+`) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= `+t.inDepth+`) {
continue;
}
for (int wR = 0; wR < `+f+`;
wR += `+h+`) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+m+`;
wC += `+d+`) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= `+t.inWidth+`) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value `+L+` currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = `+(i?a?"(((batch * "+t.inDepth+" + xD) * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"((xD * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"wD * "+f+" * "+m+` +
wR * `+m+" + wC")+`;
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}var N="max",I=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(I="avgValue / count");var C=Math.floor(s/4)*4,O=s%4,D=`
if (`+b+`) {
avgValue += dot(values, ones);
} else {
minMaxValue = `+N+`(values, minMaxValue);
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`;this.userCode=`
const ivec3 strides =
ivec3(`+o+", "+c+", "+l+`);
const ivec3 pads = ivec3(`+g+", "+y+", "+w+`);
const float initializationValue = `+x+`;
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= `+t.inWidth+`) {
return initializationValue;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
count += 1.0;
return getX(batch, xD, xR, xC, ch);
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(`+x+`);
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < `+p+`;
wD += `+u+`) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= `+t.inDepth+`) {
continue;
}
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+`
}
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput(`+I+`);
2020-10-12 01:22:43 +02:00
}
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var Gb=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];
} else {
minMaxValue = `+c+`(values, minMaxValue);
2020-10-23 00:50:09 +02: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-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
`),this.userCode=`
const float initializationValue = `+o+`;
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
`+f+`
return getX(batch, inIdx);
2020-10-12 01:22:43 +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+`;
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-12 01:22:43 +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-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput(`+l+`);
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var qb=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r="",i=0;i<4;i++){var a="thisRC = rc;";i%2===1&&(a+="thisRC.z += 1;"),i>1&&(a+="thisRC.y += 1;"),r+=`
2020-11-03 15:34:36 +01:00
`+a+`
`+(i>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+`
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[`+i+`] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
`+(i>0?"}":"")+`
`}this.userCode=`
2020-11-04 16:18:22 +01:00
`+ZB(e)+`
`+$d(t)+`
2020-11-03 15:34:36 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = `+t[1]+`;
int cols = `+t[2]+`;
`+r+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();function ZB(n){var t=gi(["r","c","d"],n);return`
2020-11-03 15:34:36 +01:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
`+t+`
return ivec3(r, c, d);
}
2020-11-04 16:18:22 +01:00
`}var QB=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;
2020-10-12 01:22:43 +02:00
}
2020-11-03 15:34:36 +01:00
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-12 01:22:43 +02:00
}
}
2020-11-03 15:34:36 +01:00
// End loop over dy
setOutput(accumulator);
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var ez=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);
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 four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
2020-11-04 16:18:22 +01:00
`}return n}();var tz=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-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < `+(c-1)+`;
bool hasNextRow = coords.z < `+(r-1)+`;
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
2020-11-04 16:18:22 +01:00
`}return n}();var nz=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]+`));
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
float sourceFracCol =
float(`+u[1]+`) *
(float(dyC) / float(`+h[1]+`));
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
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-12 01:22:43 +02:00
}
}
}
2020-11-03 15:34:36 +01:00
// End loop over dy
setOutput(accumulator);
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var rz=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);
2020-10-12 01:22:43 +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-11-01 19:07:53 +01:00
2020-11-03 15:34:36 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + `+h+`)));
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
setOutput(newValue);
}
2020-11-04 16:18:22 +01:00
`}return n}();var iz=function(){function n(t,e){this.variableNames=["x"];var r=t.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");if(this.outputShape=t,r===1){this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
int coord = getOutputCoords();
setOutput(getX(`+t[0]+` - coord - 1));
}
2020-11-04 07:11:24 +01:00
`;return}var i=function(o){return e.indexOf(o)!==-1&&t[o]!==1?t[o]+" - coords["+o+"] - 1":"coords["+o+"]"},a=t.map(function(o,c){return i(c)}).join(","),s=Qe(r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+s+` coords = getOutputCoords();
setOutput(getX(`+a+`));
}
2020-11-04 16:18:22 +01:00
`}return n}();var az=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=Ut("rc",r),a=i[r-1]+" + 1 < "+this.outputShape[r-1],s=i[r-2]+" + 1 < "+this.outputShape[r-2],o=Qe(r);r===1?this.userCode=`
2020-11-03 15:34:36 +01:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(`+t[0]+` - rc - 1),
`+t[0]+` - rc - 1);
if(`+a+`){
result.g = getChannel(getX(`+t[0]+` - (rc + 1) - 1),
`+t[0]+` - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
`+o+` rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = `+c(i.slice())+`;
if(`+a+`){
result.g = `+l(i.slice())+`;
}
if(`+s+`) {
result.b = `+u(i.slice())+`;
if(`+a+`) {
result.a = `+h(i.slice())+`;
}
}
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`;function c(f){return d(f)}function l(f){return f[r-1]="("+f[r-1]+" + 1)",d(f)}function u(f){return f[r-2]="("+f[r-2]+" + 1)",d(f)}function h(f){return f[r-1]="("+f[r-1]+" + 1)",f[r-2]="("+f[r-2]+" + 1)",d(f)}function d(f){var m=t.map(function(w,b){return p(b,f)}),g=m.join(","),y=m.slice(-2).join(",");return"getChannel(getX("+g+"), vec2("+y+"))"}function p(f,m){return e.indexOf(f)!==-1&&t[f]!==1?t[f]+" - "+m[f]+" - 1":""+m[f]}}return n}();var Yb=function(){function n(t,e,r,i,a,s,o){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;var c=Qe(a.length),l=Qe(s.length),u="";r===1?u="i":r===2&&(u="i, j");var h="getIndices("+u+")",d="";i===1?d="i":i===2&&(d="i, coords[1]");var p="getUpdates("+d+")",f=e>1?"strides[j]":"strides";this.userCode=`
2020-11-03 15:34:36 +01:00
`+c+" strides = "+c+"("+a+`);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
`+l+` coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < `+t+`; i++) {
int flattenedIndex = 0;
for (int j = 0; j < `+e+`; j++) {
int index = round(`+h+`);
flattenedIndex += index * `+f+`;
}
if (flattenedIndex == coords[0]) {
sum += `+p+`;
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2020-11-04 16:18:22 +01:00
`}return n}();var sz=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-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
float getSegmentIdAtIndex(int inIdx) {
`+f+`
return getSegmentIds(inIdx);
2020-10-23 00:50:09 +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-23 00:50:09 +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+`
}
setOutput(`+l+`);
}
2020-11-04 16:18:22 +01:00
`}return n}();var oz=function(){function n(t,e,r){this.variableNames=["c","a","b"],this.outputShape=e;var i,a;if(r>4)throw Error("Where for rank "+r+" is not yet supported");if(r===1)a="resRC",i="resRC";else{for(var s=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],c=[],l=0;l<e.length;l++)c.push(""+s[l]),l<t&&o.push(""+s[l]);i=o.join(),a=c.join()}var u=Qe(r);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+u+` resRC = getOutputCoords();
float cVal = getC(`+i+`);
if (cVal >= 1.0) {
setOutput(getA(`+a+`));
} else {
setOutput(getB(`+a+`));
}
}
2020-11-04 16:18:22 +01:00
`}return n}();var lz=function(){function n(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e=Qe(this.rank),r="uniform int start["+this.rank+"];",i=cz(this.rank),a,s=t.map(function(o,c){return"sourceLoc."+rp[c]+" = start["+c+"] + coords."+rp[c]+";"});a=`
2020-11-03 15:34:36 +01:00
`+e+` sourceLoc;
`+e+` coords = getOutputCoords();
`+s.join(`
`)+`
`,this.userCode=`
`+r+`
void main() {
`+a+`
setOutput(getSource(`+i+`));
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+t.length+")"));return function(r,i){if(e.startLoc==null&&(e.startLoc=r.getUniformLocationNoThrow(i,"start"),e.startLoc==null))return;r.gl.uniform1iv(e.startLoc,t)}},n}(),rp=["x","y","z","w","u","v"];function cz(n){if(n===1)return"sourceLoc";if(n<=6)return rp.slice(0,n).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+n+" is not yet supported")}var uz=function(){function n(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Qe(this.rank),r=Ut("coords",this.rank),i=Ut("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+i.slice(-2).join()+")",s="getChannel(getSource("+i.join()+"), "+a+")",o=`
2020-11-03 15:34:36 +01:00
result.x = `+s+`;
if (++`+r[this.rank-1]+" < "+t[this.rank-1]+`) {
++`+i[this.rank-1]+`;
result.y = `+s+`;
--`+i[this.rank-1]+`;
}
`,c=this.rank===1?"":`
--`+r[this.rank-1]+`;
if (++`+r[this.rank-2]+" < "+t[this.rank-2]+`) {
++`+i[this.rank-2]+`;
result.z = `+s+`;
if (++`+r[this.rank-1]+" < "+t[this.rank-1]+`) {
++`+i[this.rank-1]+`;
result.w = `+s+`;
}
}
`,l=this.rank<=4?`sourceLoc = coords +
`+e+"("+t.map(function(u,h){return"start["+h+"]"}).join()+");":t.map(function(u,h){return i[h]+" = "+r[h]+" + start["+h+"];"}).join(`
`);this.userCode=`
uniform int start[`+this.rank+`];
void main() {
`+e+` coords = getOutputCoords();
`+e+` sourceLoc;
`+l+`
vec4 result = vec4(0.);
`+o+`
`+c+`
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+t.length+")"));return function(r,i){if(e.startLoc==null&&(e.startLoc=r.getUniformLocationNoThrow(i,"start"),e.startLoc==null))return;r.gl.uniform1iv(e.startLoc,t)}},n}();var hz=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=r;var i=r.length,a=Qe(r.length),s=Qe(r.length),o="";if(i===1)o="coords * strides + begin";else{var c=0;o=r.map(function(l,u){return c++,r.length===1?"coords * strides["+u+"] + begin["+u+"]":"coords["+(c-1)+"] * strides["+u+"] + begin["+u+"]"}).join(",")}this.userCode=`
2020-11-03 15:34:36 +01:00
`+a+" begin = "+a+"("+t+`);
`+a+" strides = "+a+"("+e+`);
void main() {
`+s+` coords = getOutputCoords();
setOutput(getX(`+o+`));
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var dz=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=jb(e,r),a=$b(t,i,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);var s=Kb(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===Dt.PACKED_2X2_FLOAT32?c=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Dt.PACKED_2X2_FLOAT16?c=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Dt.UNPACKED_FLOAT32?c=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Dt.UNPACKED_FLOAT16?c=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Dt.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=jb(r,i),s=$b(e,a,i);s in this.freeTextures||(this.freeTextures[s]=[]);var o=Kb(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 pz(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 Kb(n,t,e,r,i){var a=fz(t,r),s;if(i){var o=ta(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=pz(e,a);return s*p}function fz(n,t){switch(n){case Dt.PACKED_2X2_FLOAT32:return Qd(t);case Dt.PACKED_2X2_FLOAT16:return ep(t);case Dt.UNPACKED_FLOAT32:return Xd(t);case Dt.UNPACKED_FLOAT16:return Jd(t);case Dt.PACKED_4X1_UNSIGNED_BYTE:return Zd(t);default:throw new Error("Unknown physical texture type "+n)}}function mz(n){return _.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Dt.PACKED_2X2_FLOAT32:Dt.UNPACKED_FLOAT32:n?Dt.PACKED_2X2_FLOAT16:Dt.UNPACKED_FLOAT16}function jb(n,t){if(n===cn.UPLOAD)return Dt.PACKED_2X2_FLOAT32;if(n===cn.RENDER||n==null)return mz(t);if(n===cn.DOWNLOAD||n===cn.PIXELS)return Dt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function $b(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var yz=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-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();function gz(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+`
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
setOutput(y);
}
2020-11-04 16:18:22 +01:00
`}return n}(),ir="if (isnan(x)) return x;",vz="return x;",Xb="return abs(x);",Jb=ir+`
2020-11-03 15:34:36 +01:00
return (x < 0.0) ? 0.0 : x;
2020-11-04 16:18:22 +01:00
`,Zb=ir+`
2020-11-03 15:34:36 +01:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-11-04 16:18:22 +01:00
`,Qb="return (x >= 0.0) ? x : (exp(x) - 1.0);",wz=`
2020-11-03 15:34:36 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = `+_.backend_util.SELU_SCALEALPHA+`;
float scale = `+_.backend_util.SELU_SCALE+`;
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-11-04 16:18:22 +01:00
`;function bz(n){return n===void 0&&(n=0),ir+(`
2020-11-03 15:34:36 +01:00
return x > 0.0 ? 1.0 : float(`+n+`);
2020-11-04 16:18:22 +01:00
`)}var e2="return -x;",t2="return ceil(x);",n2="return floor(x);",xz=`
2020-11-03 15:34:36 +01:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-11-04 16:18:22 +01:00
`,Lz="return float(isnan(x));",Sz="return float(isinf(x));",Iz="return float(!isnan(x) && !isinf(x));",Az=`
2020-11-03 15:34:36 +01:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
2020-11-04 16:18:22 +01:00
`,r2="return exp(x);",i2="return exp(x) - 1.0;",Tz=`if (x < 0.0) return NAN;
return log(x);`,Nz="return log(1.0 + x);",_z="return sqrt(x);",Cz="return inversesqrt(x);",Rz="return 1.0 / (1.0 + exp(-1.0 * x));",Oz=`
2020-11-03 15:34:36 +01:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-11-04 16:18:22 +01:00
`,Ez=ir+`
2020-11-03 15:34:36 +01:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-11-04 16:18:22 +01:00
`,Dz=ir+`
2020-11-03 15:34:36 +01:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-11-04 16:18:22 +01:00
`,kz=ir+`
2020-11-03 15:34:36 +01:00
return atan(x);
2020-11-04 16:18:22 +01:00
`,Fz=`
2020-11-03 15:34:36 +01:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-11-04 16:18:22 +01:00
`,Wz=`
2020-11-03 15:34:36 +01:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-11-04 16:18:22 +01:00
`,Uz=`
2020-11-03 15:34:36 +01:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2020-11-04 16:18:22 +01:00
`,Bz=ir+"return log(x + sqrt(x * x + 1.0));",zz=ir+`
2020-11-03 15:34:36 +01:00
if (x < 1.0) return NAN;
2020-11-04 16:18:22 +01:00
return log(x + sqrt(x * x - 1.0));`,Pz=ir+`
2020-11-03 15:34:36 +01:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-11-04 16:18:22 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Mz=`
2020-11-03 15:34:36 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = `+_.backend_util.ERF_P+`;
float a1 = `+_.backend_util.ERF_A1+`;
float a2 = `+_.backend_util.ERF_A2+`;
float a3 = `+_.backend_util.ERF_A3+`;
float a4 = `+_.backend_util.ERF_A4+`;
float a5 = `+_.backend_util.ERF_A5+`;
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2020-11-04 16:18:22 +01:00
`,Hz="return 1.0 / x;",Vz="return float(!(x >= 1.0));",jo="return x;";var Gz="return x;",qz=`
2020-11-03 15:34:36 +01:00
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
2020-11-04 16:18:22 +01:00
`,a2=`
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;
return result;
2020-11-04 16:18:22 +01:00
`,s2=`
2020-11-03 15:34:36 +01:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-11-04 16:18:22 +01:00
`,o2=`
2020-11-03 15:34:36 +01:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2020-11-04 16:18:22 +01:00
`,ds=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-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var Yz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,r=Ut("rc",e),i=Qe(e),a=JW(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+`);
setOutput(getChannel(packedInput, `+o+`));
}
2020-11-04 16:18:22 +01:00
`}return n}();var c2=_.backend_util.segment_util,Kz=_.kernel_impls.split,jz=_.kernel_impls.tile,$z=_.kernel_impls.topkImpl,Xz=_.kernel_impls.whereImpl,Jz=1e-7,Zz=1e-4,$o={};function Qz(n){return n in $o||($o[n]={}),$o[n]}function Xo(n,t){if(t===void 0&&(t=!1),n==="linear")return t?Gz:vz;if(n==="relu")return t?a2:Jb;if(n==="elu")return t?o2:Qb;if(n==="relu6")return t?s2:Zb;if(n==="prelu")return t?wb:vb;throw new Error("Activation "+n+" has not been implemented for the WebGL backend.")}var eP=128,tP=600;function nP(){return _.env().global.screen==null?1024:_.env().global.screen.height*_.env().global.screen.width*window.devicePixelRatio*tP/1024/1024}var l2=1e3,u2=function(n){iW(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=zn(_.env().getNumber("WEBGL_VERSION"));r.binaryCache=Qz(_.env().getNumber("WEBGL_VERSION")),r.gpgpu=new Hb(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 dz(r.gpgpu),r.numMBBeforeWarning=nP(),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:cn.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:cn.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 ds(c,jo):u=new De(c,jo);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 zo(this,void 0,void 0,function(){var r,i,a,s,o,c,l,u,h,d,p,f,m,g,y,w,b,x,L,N,I,C;return Po(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 ds(s,jo):h=new De(s,jo),d=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:c}],c),p=this.read(d.dataId),this.disposeIntermediateTensorInfo(d),[2,p];if(a!=null)return[2,this.convertAndCacheOnCPU(e)];if(!_.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&_.env().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,c!=="comple
2020-11-03 15:34:36 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-11-04 16:18:22 +01:00
`,lP=`
2020-11-03 15:34:36 +01:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-11-04 16:18:22 +01:00
`;function Jo(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 la(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],G=V[1],j={dataId:P.dataId,dtype:P.dtype,shape:p.shape},q={dataId:G.dataId,dtype:G.dtype,shape:f.shape},H=new Wt(t,p.shape,f.shape);return m.runWebGLProgram(H,[j,q],_.upcastType(P.dtype,G.dtype))}),b=w[0],x=w[1],L=ca({inputs:{real:b,imag:x},backend:m});return m.disposeIntermediateTensorInfo(b),m.disposeIntermediateTensorInfo(x),L}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 rr(e,p.shape,f.shape,i):B=new Wt(t,p.shape,f.shape),m.runWebGLProgram(B,[p,f],N)}}var p2="return a + b;",uP=la({opSnippet:p2,packedOpSnippet:p2,supportsComplex:!0,cpuKernelImpl:WW}),hP={kernelName:_.Add,backendName:"webgl",kernelFunc:uP};var dP=cP+`
2020-11-03 15:34:36 +01:00
return atan(a, b);
2020-11-04 16:18:22 +01:00
`,pP=`
2020-11-03 15:34:36 +01:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-04 16:18:22 +01:00
`+lP+`
2020-11-03 15:34:36 +01:00
return result;
2020-11-04 16:18:22 +01:00
`,fP=la({opSnippet:dP,packedOpSnippet:pP}),mP={kernelName:_.Atan2,backendName:"webgl",kernelFunc:fP};function gP(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;na(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 ar({inputs:{x:i},backend:e});var h=new hs(u,"avg",!1);return e.runWebGLProgram(h,[i],"float32")}var yP={kernelName:_.AvgPool,backendName:"webgl",kernelFunc:gP};function vP(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=a;na([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 FU(u);return e.runWebGLProgram(h,[i],s.dtype)}var wP={kernelName:_.AvgPoolBackprop,backendName:"webgl",kernelFunc:vP};var bP=function(){function n(t,e,r,i,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.backend_util.assertAndGetBroadcastShape(t,e),_.backend_util.assertAndGetBroadcastShape(t,r);var o="0.0";i!=null&&(_.backend_util.assertAndGetBroadcastShape(t,i),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var c="1.0";a!=null&&(_.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = `+o+`;
float scale = `+c+`;
float inv = scale * inversesqrt(variance + float(`+s+`));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
2020-11-04 16:18:22 +01:00
`}return n}();var xP=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+`;
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(`+s+`));
setOutput((x - mean) * inv + offset);
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var LP=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 xP(i.shape,a.shape,s.shape,h,d,l):new bP(i.shape,a.shape,s.shape,h,d,l),f=e.runWebGLProgram(p,u,u[0].dtype);return f},SP={kernelName:_.FusedBatchNorm,backendName:"webgl",kernelFunc:LP};var IP="return float(a != b);",f2=la({opSnippet:IP,dtype:"bool"}),AP={kernelName:_.NotEqual,backendName:"webgl",kernelFunc:f2};function ip(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return ar({inputs:{x:i.complexTensorInfos.real},backend:e})}var TP={kernelName:_.Real,backendName:"webgl",kernelFunc:ip};var NP="return float(int(x));";function _P(n,t){var e=new De(n.shape,NP),r=t.runWebGLProgram(e,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function ap(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 ar({inputs:{x:i},backend:e});var s=_.zeros(i.shape),o=ap({inputs:{x:i},backend:e,attrs:{dtype:"float32"}}),c=ca({inputs:{real:o,imag:s},backend:e});return s.dispose(),e.disposeIntermediateTensorInfo(o),c}if(i.dtype==="complex64"){var l=ip({inputs:{input:i},backend:e}),c=ap({inputs:{x:l},backend:e,attrs:{dtype:a}});return e.disposeIntermediateTensorInfo(l),c}if(!_.util.hasEncodingLoss(i.dtype,a)){var c=ar({inputs:{x:i},backend:e});return{dataId:c.dataId,shape:c.shape,dtype:a}}if(a==="int32")return _P(i,e);if(a==="bool"){var u=e.makeTensorInfo([],"bool",_.util.getTypedArrayFromDType("bool",1)),h={a:i,b:u},c=f2({inputs:h,backend:e});return e.disposeIntermediateTensorInfo(u),c}throw new Error("Error in Cast: failed to cast "+i.dtype+" to "+a)}var CP={kernelName:_.Cast,backendName:"webgl",kernelFunc:ap};var RP=function(){function n(t){this.outputShape=[],this.outputShape=_.backend_util.computeOutShape(t,1),this.variableNames=t.map(function(c,l){return"T"+l});var e=new Array(t.length-1);e[0]=t[0][1];for(var r=1;r<e.length;r++)e[r]=e[r-1]+t[r][1];for(var i=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"],r=1;r<e.length;r++){var a=e[r-1];i.push("else if (yC < "+e[r]+") "+("setOutput(getT"+r+"(yR, yC-"+a+"));"))}var s=e.length,o=e[e.length-1];i.push("else setOutput(getT"+s+"(yR, yC-"+o+"));"),this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
`+i.join(`
`)+`
}
2020-11-04 16:18:22 +01:00
`}return n}();var OP=function(){function n(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.backend_util.computeOutShape(t,e);var r=this.outputShape,i=r.length,a=Qe(i),s=Ut("coords",i),o=["x","y","z","w","u","v"].slice(0,i);this.variableNames=t.map(function(y,w){return"T"+w});var c=new Array(t.length-1);c[0]=t[0][e];for(var l=1;l<c.length;l++)c[l]=c[l-1]+t[l][e];for(var u=o[e],h=o.slice(-2),d=o.join(),p="if ("+u+" < "+c[0]+`) {
2020-11-03 15:34:36 +01:00
return getChannel(
getT0(`+d+"), vec2("+h.join()+`));
}`,l=1;l<c.length;l++){var f=c[l-1];p+=`
if (`+u+" < "+c[l]+" && "+u+" >= "+c[l-1]+`) {
return getChannel(
2020-11-04 16:18:22 +01:00
getT`+l+"("+Zo(o,u,f)+`),
vec2(`+Zo(h,u,f)+`));
2020-11-03 15:34:36 +01:00
}`}var m=c.length,g=c[c.length-1];p+=`
return getChannel(
2020-11-04 16:18:22 +01:00
getT`+m+"("+Zo(o,u,g)+`),
vec2(`+Zo(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-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
`+a+` coords = getOutputCoords();
vec4 result = vec4(getValue(`+s+`), 0., 0., 0.);
`+s[i-1]+" = "+s[i-1]+` + 1;
if (`+s[i-1]+" < "+r[i-1]+`) {
result.g = getValue(`+s+`);
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +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+`);
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
`+s[i-1]+" = "+s[i-1]+` - 1;
if (`+s[i-2]+" < "+r[i-2]+` &&
`+s[i-1]+" < "+r[i-1]+`) {
result.b = getValue(`+s+`);
}
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();function Zo(n,t,e){var r=n.indexOf(t),i=n.map(function(a,s){return s===r?a+" - "+e:a});return i.join()}function m2(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return ar({inputs:{x:i.complexTensorInfos.imag},backend:e})}var EP={kernelName:_.Imag,backendName:"webgl",kernelFunc:m2};function DP(n,t,e){var r=[fi(n.shape)].concat(mi(n.shape)),i={dtype:n.dtype,shape:r,dataId:n.dataId},a=[fi(t)].concat(mi(t)),s=new qb(a,r),o=!0,c=e.runWebGLProgram(s,[i],n.dtype,null,o);return{dataId:c.dataId,shape:t,dtype:c.dtype}}function sr(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&&!ls(i.shape,c)&&!(u.texture!==null&&ls(u.shape,c))?DP(i,c,s):(s.incRef(i.dataId),{dataId:i.dataId,shape:c,dtype:i.dtype})}var kP={kernelName:_.Reshape,backendName:"webgl",kernelFunc:sr};function ua(n,t,e){var r=n[0].dtype;if(r==="complex64"){var i=n.map(function(b){return ip({inputs:{input:b},backend:e})}),a=n.map(function(b){return m2({inputs:{input:b},backend:e})}),s=ua(i,t,e),o=ua(a,t,e),c=ca({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=ua(n.slice(0,l),t,e),h=ua(n.slice(l),t,e),d=ua([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 OP(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 sr({inputs:{x:b},attrs:{shape:[-1,_.util.sizeFromShape(b.shape.slice(t))]},backend:e})}),g=new RP(m.map(function(b){return b.shape})),y=e.runWebGLProgram(g,m,r);m.forEach(function(b){return e.disposeIntermediateTensorInfo(b)});var w=sr({inputs:{x:y},attrs:{shape:f},backend:e});return e.disposeIntermediateTensorInfo(y),w}function FP(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),ua(o,a,e)}var WP={kernelName:_.Concat,backendName:"webgl",kernelFunc:FP};var UP=d2+`
2020-11-03 15:34:36 +01:00
return cos(x);
2020-11-04 16:18:22 +01:00
`,BP=Jo(UP),zP={kernelName:_.Cos,backendName:"webgl",kernelFunc:BP};var PP=`
2020-11-03 15:34:36 +01:00
if (a == b) {
return 1.0;
};
2020-11-04 16:18:22 +01:00
return a / b;`,MP=`
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.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
2020-11-04 16:18:22 +01:00
`,HP=la({opSnippet:PP,packedOpSnippet:MP,checkOutOfBounds:!0}),VP={kernelName:_.Div,backendName:"webgl",kernelFunc:HP};var g2=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+`;
float unaryOpComplex(float real, float expR, float imag, float expI) {
`+o+`
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +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-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
float result = 0.0;
2020-10-12 01:22:43 +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);
result +=
unaryOpComplex(real, expR, imag, expI) / `+s+`;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
return result;
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
2020-11-04 16:18:22 +01:00
`}return n}();function y2(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=sr({inputs:{x:n},backend:e,attrs:{shape:[s,a]}}),c=o.shape,l=new g2("real",c,t),u=new g2("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=ca({inputs:{real:d,imag:p},backend:e});e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p);var m=sr({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(m),m}function GP(n){var t=n.inputs,e=n.backend,r=t.input;return y2(r,!1,e)}var qP={kernelName:_.FFT,backendName:"webgl",kernelFunc:GP};var YP=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];
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
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-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var KP={kernelName:_.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=t.image,i=e,a=new YP(r.shape),s=i.runWebGLProgram(a,[r],r.dtype);return s}};var jP=function(){function n(t){this.variableNames=["A"];var e=Bt(),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);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
vec4 values = `+e.texture2D+`(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput(floor(value * 255.0 + 0.5));
}
2020-11-04 16:18:22 +01:00
`}return n}();var $P=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Bt(),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;
2020-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
result[row * 2 + col] = floor(value * 255.0 + 0.5);
2020-10-23 00:50:09 +02:00
}
}
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
`+e.output+` = result;
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var JP={kernelName:_.FromPixels,backendName:"webgl",kernelFunc:XP},ha;function XP(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)&&(ha==null&&(ha=document.createElement("canvas").getContext("2d")),ha.canvas.width=l,ha.canvas.height=u,ha.drawImage(i,0,0,l,u),i=ha.canvas);var p=e.makeTensorInfo(h,"int32");e.texData.get(p.dataId).usage=cn.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),i);var f=_.env().getBool("WEBGL_PACK")?new $P(d):new jP(d),m=e.runWebGLProgram(f,[p],"int32");return e.disposeData(p.dataId),m}function ZP(n){var t=n.inputs,e=n.backend,r=t.input;return y2(r,!0,e)}var QP={kernelName:_.IFFT,backendName:"webgl",kernelFunc:ZP};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=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-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-10-12 01:22:43 +02:00
2020-11-03 15:34:36 +01:00
float getValue(int batch, int inIdx) {
`+h+`
return getX(batch, inIdx);
2020-10-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +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-23 00:50:09 +02:00
}
2020-10-12 01:22:43 +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-12 01:22:43 +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);
`+l+`
} else if (`+(c===3)+`) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
`+l+`
}
setOutput(sumValue);
2020-10-12 01:22:43 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();function eM(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 w2(n,t,e,r){for(var i=eM(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 v2({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u},c):new v2({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u}):h=new Gb({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 tM(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=sr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=w2(o,n.dtype,"max",r),l=sr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var rM=function(){function n(t,e){this.variableNames=["A"];for(var r=new Array(t.length),i=0;i<r.length;i++)r[i]=t[e[i]];this.outputShape=r,this.rank=r.length;var a=Qe(this.rank),s=nM(e);this.userCode=`
2020-11-03 15:34:36 +01:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
2020-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();function nM(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 iM=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var r=new Array(t.length),i=0;i<r.length;i++)r[i]=t[e[i]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var a=Qe(this.rank),s=db("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-10-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
--`+s[this.rank-1]+`;
if(++`+s[this.rank-2]+" < "+r[this.rank-2]+`) {
result[2] = `+u+`;
if(`+l+`) {
result[3] = `+u+`;
2020-10-30 15:23:49 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput(result);
}
2020-11-04 16:18:22 +01:00
`}return n}();function sp(n,t,e){var r=_.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iM(n.shape,t):new rM(n.shape,t);return e.runWebGLProgram(r,[n],n.dtype)}var aM={kernelName:_.Max,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e,s=a.reductionIndices,o=a.keepDims,c=r,l=i.shape.length,u=_.util.parseAxisParam(s,i.shape),h=u,d=_.backend_util.getAxesPermutation(h,l),p=d!=null,f=c.shouldExecuteOnCPU([i]),m=i;if(p){if(f){for(var g=c.texData.get(m.dataId),y=g.values,w=new Array(l),b=0;b<w.length;b++)w[b]=i.shape[d[b]];var x=jd(y,i.shape,i.dtype,d,w);m=c.makeTensorInfo(w,i.dtype);var L=c.texData.get(m.dataId);L.values=x}else m=sp(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=HW(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=tM(m,C,O,c);return p&&c.disposeIntermediateTensorInfo(m),D}};function sM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;na(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 ar({inputs:{x:i},backend:e});var h=new hs(u,"max",!1);return e.runWebGLProgram(h,[i],i.dtype)}var oM={kernelName:_.MaxPool,backendName:"webgl",kernelFunc:sM};function cM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=t.output,o=a;na([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 hs(d,"max",p),m=e.runWebGLProgram(f,[o],o.dtype),g=new MB(d),y=e.runWebGLProgram(g,[i,m],o.dtype);return e.disposeIntermediateTensorInfo(m),y}var lM={kernelName:_.MaxPoolBackprop,backendName:"webgl",kernelFunc:cM};function uM(n,t,e,r){var i=new hs(e,"max",!1),a=r.runWebGLProgram(i,[n],"float32");i=new hs(e,"max",!0,!0,t);var s=r.runWebGLProgram(i,[n],"float32");return[a,s]}var hM={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=uM(i,l,d,u),f=p[0],m=p[1];return[f,m]}};function dM(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=sr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=w2(o,"float32","mean",r),l=sr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var pM={kernelName:_.Mean,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e,s=a.keepDims,o=a.axis,c=r,l=i.shape.length,u=_.util.parseAxisParam(o,i.shape),h=u,d=_.backend_util.getAxesPermutation(h,l),p=d!=null,f=c.shouldExecuteOnCPU([i]),m=[],g=i;if(p){if(f){for(var y=c.texData.get(g.dataId),w=y.values,b=new Array(l),x=0;x<b.length;x++)b[x]=i.shape[d[x]];var L=jd(w,i.shape,i.dtype,d,b);g=c.makeTensorInfo(b,i.dtype);var N=c.texData.get(g.dataId);N.values=L}else g=sp(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=dM(g,O,D,c),k=0,B=m;k<B.length;k++){var
2020-11-03 15:34:36 +01:00
int start = `+s+`;
int end = `+o+`;
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - `+l+`;
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + `+l+`;
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
`+a+" start = "+a+"("+s+`);
`+a+" end = "+a+"("+o+`);
void main() {
`+a+` outC = getOutputCoords();
for (int i = 0; i < `+i+`; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - `+l+`;
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + `+l+`;
}
}
`+a+` coords = outC - start;
setOutput(getX(`+c+`));
}
2020-11-04 16:18:22 +01:00
`}return n}();var mM=function(){function n(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(m,g){return m[0]+t[g]+m[1]});var i=t.length,a=Qe(i),s=e.map(function(m){return m[0]}).join(","),o=e.map(function(m,g){return m[0]+t[g]}).join(","),c=Ut("rc",i),l=Ut("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-10-23 00:50:09 +02:00
}
2020-11-04 16:18:22 +01:00
`}return n}();var gM=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 mM(i.shape,a,s):new fM(i.shape,a,s),c=e.runWebGLProgram(o,[i],i.dtype);return c},yM={kernelName:_.MirrorPad,backendName:"webgl",kernelFunc:gM};var b2={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},x2=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-23 00:50:09 +02:00
}
2020-11-03 15:34:36 +01:00
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2020-11-04 16:18:22 +01:00
`}return n}();var L2="return a * b;";function vM(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 x2(b2.REAL,r.shape,i.shape),l=new x2(b2.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=ca({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=VW(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 rr(L2,r.shape,i.shape):b=new Wt(L2,r.shape,i.shape),e.runWebGLProgram(b,[r,i],a)}var wM={kernelName:_.Multiply,backendName:"webgl",kernelFunc:vM};var bM={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 xM=_.kernel_impls.nonMaxSuppressionV4Impl,LM={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=xM(p,f,c,l,u,h),g=m.selectedIndices,y=m.validOutputs;return[g,y]}};var SM=_.kernel_impls.nonMaxSuppressionV5Impl,IM={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=SM(p,f,m,g,y,w),x=b.selectedIndices,L=b.selectedScores;return[x,L]}};var AM=function(){function n(t,e,r,i){this.variableNames=["Image"],this.outputShape=[];var a=t[1],s=t[2],o=Math.sin(e).toFixed(3),c=Math.cos(e).toFixed(3);this.outputShape=t;var l=_.backend_util.getImageCenter(i,a,s),u=l[0],h=l[1],d=u.toFixed(3),p=h.toFixed(3),f="";typeof r=="number"?f="float outputValue = "+r.toFixed(2)+";":f=`
2020-11-03 15:34:36 +01:00
vec3 fill = vec3(`+r.join(",")+`);
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - `+d+") * "+c+" - (float(y) - "+p+") * "+o+`;
float coordYFloat = (float(x) - `+d+") * "+o+" + (float(y) - "+p+") * "+c+`;
int coordX = int(round(coordXFloat + `+d+`));
int coordY = int(round(coordYFloat + `+p+`));
`+f+`
if(coordX >= 0 && coordX < `+s+" && coordY >= 0 && coordY < "+a+`) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2020-11-04 16:18:22 +01:00
`}return n}();var TM={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 AM(i.shape,s,o,c),h=l.runWebGLProgram(u,[i],i.dtype);return h}};var NM=d2+`
2020-11-03 15:34:36 +01:00
return sin(x);
2020-11-04 16:18:22 +01:00
`,_M=Jo(NM),CM={kernelName:_.Sin,backendName:"webgl",kernelFunc:_M};var RM="return x * x;",OM=Jo(RM),EM={kernelName:_.Square,backendName:"webgl",kernelFunc:OM};var S2="return (a - b) * (a - b);",DM=la({opSnippet:S2,packedOpSnippet:S2}),kM={kernelName:_.SquaredDifference,backendName:"webgl",kernelFunc:DM};var I2="return a - b;",FM=la({opSnippet:I2,packedOpSnippet:I2,supportsComplex:!0,cpuKernelImpl:YW}),WM={kernelName:_.Sub,backendName:"webgl",kernelFunc:FM};var UM="return tan(x);",BM=Jo(UM),zM={kernelName:_.Tan,backendName:"webgl",kernelFunc:BM};var PM={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=jd(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=sp(i,a,s);return u}};function MM(n){var t=n.inputs,e=n.attrs,r=n.backend,i=e.axis,a=t.x;na(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");var s=r.readSync(a.dataId),o=KW(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 HM={kernelName:_.Unique,backendName:"webgl",kernelFunc:MM};var VM=[hP,mP,yP,wP,SP,CP,oP,WP,zP,VP,qP,KP,JP,sP,QP,EP,aM,oM,lM,hM,pM,yM,wM,bM,LM,IM,AP,TP,kP,TM,CM,EM,WM,kM,zM,PM,HM];for(var op=0,A2=VM;op<A2.length;op++){var GM=A2[op];_.registerKernel(GM)}Bn.GPGPUContext=Hb;Bn.MathBackendWebGL=u2;Bn.forceHalfFloat=h2;Bn.gpgpu_util=EB;Bn.setWebGLContext=Mw;Bn.version_webgl=iP;Bn.webgl=aP;Bn.webgl_util=bW}),zt=we(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var cp=ei(),lp=l1(),up=I1(),N2=q1(),qM=Pw(),YM=T2();var KM="2.7.0";var jM={"tfjs-core":cp.version_core,"tfjs-backend-cpu":qM.version_cpu,"tfjs-backend-webgl":YM.version_webgl,"tfjs-data":N2.version_data,"tfjs-layers":lp.version_layers,"tfjs-converter":up.version_converter,tfjs:KM};Object.keys(cp).forEach(function(n){n!=="default"&&Object.defineProperty(vi,n,{enumerable:!0,get:function(){return cp[n]}})});Object.keys(lp).forEach(function(n){n!=="default"&&Object.defineProperty(vi,n,{enumerable:!0,get:function(){return lp[n]}})});Object.keys(up).forEach(function(n){n!=="default"&&Object.defineProperty(vi,n,{enumerable:!0,get:function(){return up[n]}})});vi.data=N2;vi.version=jM}),D2=we(Qo=>{const Ve=zt(),_2=6;function $M(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 C2=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},R2=n=>({startEndTensor:n,startPoint:Ve.slice(n,[0,0],[-1,2]),endPoint:Ve.slice(n,[0,2],[-1,2])}),O2=(n,t)=>{const e=Ve.mul(n.startPoint,t),r=Ve.mul(n.endPoint,t),i=Ve.concat2d([e,r],1);return R2(i)};function XM(n,t,e){const r=Ve.slice(n,[0,1],[-1,2]),i=Ve.add(r,t),a=Ve.slice(n,[0,3],[-1,2]),s=Ve.div(a,e),o=Ve.div(i,e),c=Ve.div(s,2),l=Ve.sub(o,c),u=Ve.add(o,c),h=Ve.mul(l,e),d=Ve.mul(u,e),p=1;return Ve.concat2d([h,d],p)}function JM(n,t){return Ve.tidy(()=>{const e=n.box?n.box:n;return O2(e,t).startEndTensor.squeeze()})}class E2{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=$M(t.detector.inputSize),this.anchors=Ve.tensor2d(this.anchorsData),this.inputSize=Ve.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n){if(!n||n.isDisposedInternal||n.shape.length!==4||n.shape[1]<1||n.shape[2]<1)return null;const[t,e,r]=Ve.tidy(()=>{const l=n.resizeBilinear([this.width,this.height]),u=Ve.mul(Ve.sub(l.div(255),.5),2),h=this.blazeFaceModel.predict(u);let d;if(Array.isArray(h)){co
2020-11-03 15:34:36 +01:00
`),x.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join(`
`);let L={};L.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?L.colorMatrix.SHADER.WITHOUT_ALPHA:L.colorMatrix.SHADER.WITH_ALPHA,O=w(C);p.uniform1fv(O.uniform.m,I),y()},L.colorMatrix.SHADER={},L.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(`
`),L.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(`
`),L.brightness=function(N){const I=(N||0)+1;L.colorMatrix([I,0,0,0,0,0,I,0,0,0,0,0,I,0,0,0,0,0,1,0])},L.saturation=function(N){const I=(N||0)*2/3+1,C=(I-1)*-.5;L.colorMatrix([I,C,C,0,0,C,I,C,0,0,C,C,I,0,0,0,0,0,1,0])},L.desaturate=function(){L.saturation(-1)},L.contrast=function(N){const I=(N||0)+1,C=-128*(I-1);L.colorMatrix([I,0,0,0,C,0,I,0,0,C,0,0,I,0,C,0,0,0,1,0])},L.negative=function(){L.contrast(-2)},L.hue=function(N){N=(N||0)/180*Math.PI;const I=Math.cos(N),C=Math.sin(N),O=.213,D=.715,F=.072;L.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])},L.desaturateLuminance=function(){L.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},L.sepia=function(){L.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},L.brownie=function(){L.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},L.vintagePinhole=function(){L.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},L.kodachrome=function(){L.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])},L.technicolor=function(){L.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])},L.polaroid=function(){L.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},L.shiftToBGR=function(){L.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},L.convolution=function(N){const I=new Float32Array(N),C=1/o,O=1/c,D=w(L.convolution.SHADER);p.uniform1fv(D.uniform.m,I),p.uniform2f(D.uniform.px,C,O),y()},L.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(`
`),L.detectEdges=function(){L.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},L.sobelX=function(){L.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},L.sobelY=function(){L.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},L.sharpen=function(N){const I=N||1;L.convolution.call(this,[0,-1*I,0,-1*I,1+4*I,-1*I,0,-1*I,0])},L.emboss=function(N){const I=N||1;L.convolution.call(this,[-2*I,-1*I,0,-1*I,1,1*I,0,1*I,2*I])},L.blur=function(N){const I=N/7/o,C=N/7/c,O=w(L.blur.SHADER);p.uniform2f(O.uniform.px,0,C),y(b.INTERMEDIATE),p.uniform2f(O.uniform.px,I,0),y()},L.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(`
`),L.pixelate=function(N){const I=N/o,C=N/c,O=w(L.pixelate.SHADER);p.uniform2f(O.uniform.size,I,C),y()},L.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join(`
2020-11-04 18:10:26 +01:00
`)};Vx.Canvas=qV}),Yx=we(qx=>{const vs=zt(),YV=Gx();let yt=null,Yt=null;function KV(n,t){let e;if(n instanceof vs.Tensor)e=vs.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)),(!yt||yt.width!==a||yt.height!==s)&&(yt=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(a,s):document.createElement("canvas"),yt.width!==a&&(yt.width=a),yt.height!==s&&(yt.height=s));const o=yt.getContext("2d");n instanceof ImageData?o.putImageData(n,0,0):o.drawImage(n,0,0,r,i,0,0,yt.width,yt.height),t.filter.enabled&&((!this.fx||!Yt||yt.width!==Yt.width||yt.height!==Yt.height)&&(Yt=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(yt.width,yt.height):document.createElement("canvas"),Yt.width!==yt.width&&(Yt.width=yt.width),Yt.height!==yt.height&&(Yt.height=yt.height),this.fx=vs.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new YV.Canvas({canvas:Yt}):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(yt)),Yt||(Yt=yt);let c;if(t.backend==="webgl"||Yt instanceof ImageData)c=vs.browser.fromPixels(Yt);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(Yt,0,0);const d=h.getImageData(0,0,a,s);c=vs.browser.fromPixels(d)}const l=c.toFloat();e=l.expandDims(0),c.dispose(),l.dispose()}return{tensor:e,canvas:t.filter.return?Yt:null}}qx.process=KV}),Kx=we(jV=>{ga(jV,{default:()=>$V});var $V={backend:"webgl",console:!0,async:!1,profile:!1,deallocate:!1,scoped:!1,videoOptimized:!0,filter:{enabled:!0,width:0,height:0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"../models/blazeface-back.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5},mesh:{enabled:!0,modelPath:"../models/facemesh.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age-imdb.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender-imdb.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion.json"}},body:{enabled:!0,modelPath:"../models/posenet.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.5,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5,enlargeFactor:1.65,maxHands:10,detector:{modelPath:"../models/handdetect.json"},skeleton:{modelPath:"../models/handskeleton.json"}}}}),$x=we((QG,jx)=>{jx.exports={name:"@vladmandic/human",version:"0.7.1",description:"human: 3D Face Detection, Body Pose, Hand & Finger Tracking, Iris Tracking, Age & Gender Prediction, Emotion Prediction & Gesture Recognition",sideEffects:!1,main:"dist/human.node.js",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic <mandic00@live.com>",bugs:{url:"https://
2020-11-03 15:34:36 +01:00
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2020-11-04 07:11:24 +01:00
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2020-11-03 15:34:36 +01:00
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
2020-10-12 01:22:43 +02:00
//# sourceMappingURL=human.js.map