human/dist/human.js

4007 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-15 15:43:16 +02:00
var human=(()=>{var Ip=Object.defineProperty;var Se=(n,t)=>()=>(t||(t={exports:{}},n(t.exports,t)),t.exports),AI=n=>Ip(n,"__esModule",{value:!0}),Ap=(n,t)=>{AI(n);for(var e in t)Ip(n,e,{get:t[e],enumerable:!0})};var Tp=Se(()=>{});var Np=Se(()=>{});var cs=Se(()=>{});var ji=Se(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});var Jo=function(n,t){return Jo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},Jo(n,t)};function Mn(n,t){Jo(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function de(n,t,e,i){return new(e||(e=Promise))(function(r,a){function s(u){try{l(i.next(u))}catch(c){a(c)}}function o(u){try{l(i.throw(u))}catch(c){a(c)}}function l(u){u.done?r(u.value):new e(function(c){c(u.value)}).then(s,o)}l((i=i.apply(n,t||[])).next())})}function pe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,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(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]<a[3])){e.label=u[1];break}if(u[0]===6&&e.label<a[1]){e.label=a[1],a=u;break}if(a&&e.label<a[2]){e.label=a[2],e.ops.push(u);break}a[2]&&e.ops.pop(),e.trys.pop();continue}u=t.call(n,e)}catch(c){u=[6,c],r=0}finally{i=a=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}var TI=1e-7,NI=1e-4,xI=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}(),xp=function(){function n(){}return n.prototype.time=function(t){return $("time")},n.prototype.read=function(t){return $("read")},n.prototype.readSync=function(t){return $("readSync")},n.prototype.numDataIds=function(){return $("numDataIds")},n.prototype.disposeData=function(t){return $("disposeData")},n.prototype.write=function(t,e,i){return $("write")},n.prototype.move=function(t,e,i,r){return $("move")},n.prototype.memory=function(){return $("memory")},n.prototype.floatPrecision=function(){return $("floatPrecision")},n.prototype.epsilon=function(){return this.floatPrecision()===32?TI:NI},n.prototype.batchMatMul=function(t,e,i,r){return $("batchMatMul")},n.prototype.fusedBatchMatMul=function(t){var e=t.a,i=t.b,r=t.transposeA,a=t.transposeB,s=t.bias,o=t.activation,l=t.preluActivationWeights;return $("fusedBatchMatMul")},n.prototype.slice=function(t,e,i){return $("slice")},n.prototype.stridedSlice=function(t,e,i,r){return $("stridedSlice")},n.prototype.unstack=function(t,e){return $("unstack")},n.prototype.reverse=function(t,e){return $("reverse")},n.prototype.concat=function(t,e){return $("concat")},n.prototype.neg=function(t){return $("neg")},n.prototype.add=function(t,e){return $("add")},n.prototype.addN=function(t){return $("addN")},n.prototype.subtract=function(t,e){return $("subtract")},n.prototype.multiply=function(t,e){return $("multiply")},n.prototype.realDivide=function(t,e){return $("realDivide")},n.prototype.floorDiv=function(t,e){return $("floorDiv")},n.prototype.sum=function(t,e){return $("sum")},n.prototype.prod=function(t,e){return $("prod")},n.prototype.unso
2020-10-12 01:22:43 +02:00
`)),l.join(`
2020-10-15 15:43:16 +02:00
`)}function a2(n,t,e,i){var r=st(t),a=i[i.length-1],s=new Array(a).fill(0),o=t.length,l=e==="complex64"?ma(n):n;if(o>1)for(var u=0;u<r/a;u++)for(var c=u*a,h=0;h<a;h++)s[h]=Math.max(s[h],fa(l[c+h],0,e).length);return s}function fa(n,t,e){var i;return Array.isArray(n)?i=parseFloat(n[0].toFixed(ju))+" + "+(parseFloat(n[1].toFixed(ju))+"j"):ei(n)?i="'"+n+"'":e==="bool"?i=qf(n):i=parseFloat(n.toFixed(ju)).toString(),da(i,t)}function qf(n){return n===0?"false":"true"}function ys(n,t,e,i,r,a){a===void 0&&(a=!0);var s=e==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(e==="complex64"){var u=ma(n);return[fa(u[0],0,e)]}return e==="bool"?[qf(n[0])]:[n[0].toString()]}if(l===1){if(o>Vf){var c=pa*s,h=Array.from(n.slice(0,c)),d=Array.from(n.slice((o-pa)*s,o*s));return e==="complex64"&&(h=ma(h),d=ma(d)),["["+h.map(function(C,R){return fa(C,r[R],e)}).join(", ")+", ..., "+d.map(function(C,R){return fa(C,r[o-pa+R],e)}).join(", ")+"]"]}var p=e==="complex64"?ma(n):Array.from(n);return["["+p.map(function(C,R){return fa(C,r[R],e)}).join(", ")+"]"]}var f=t.slice(1),m=i.slice(1),g=i[0]*s,v=[];if(o>Vf){for(var b=0;b<pa;b++){var w=b*g,S=w+g;v.push.apply(v,ys(n.slice(w,S),f,e,m,r,!1))}v.push("...");for(var b=o-pa;b<o;b++){var w=b*g,S=w+g;v.push.apply(v,ys(n.slice(w,S),f,e,m,r,b===o-1))}}else for(var b=0;b<o;b++){var w=b*g,S=w+g;v.push.apply(v,ys(n.slice(w,S),f,e,m,r,b===o-1))}var L=l===2?",":"";v[0]="["+v[0]+L;for(var b=1;b<v.length-1;b++)v[b]=" "+v[b]+L;for(var x=`,
2020-10-12 01:22:43 +02:00
`,b=2;b<l;b++)x+=`
2020-10-15 15:43:16 +02:00
`;return v[v.length-1]=" "+v[v.length-1]+"]"+(a?"":x),v}function ma(n){for(var t=[],e=0;e<n.length;e+=2)t.push([n[e],n[e+1]]);return t}var bs=function(){function n(t,e,i){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=st(t),i!=null){var a=i.length;E(a===this.size,function(){return"Length of values '"+a+"' does not match the size "+("inferred by the shape '"+r.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=i||Ff(e,this.size),this.strides=yr(t)}return n.prototype.set=function(t){for(var e=this,i=[],r=1;r<arguments.length;r++)i[r-1]=arguments[r];i.length===0&&(i=[0]),E(i.length===this.rank,function(){return"The number of provided coordinates ("+i.length+") must "+("match the rank ("+e.rank+")")});var a=this.locToIndex(i);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 i=0,r=0,a=t;r<a.length;r++){var s=a[r];if(s<0||s>=this.shape[i]){var o="Requested out of range element at "+t+". "+(" Buffer shape="+this.shape);throw new Error(o)}i++}for(var l=t[t.length-1],u=0;u<t.length-1;++u)l+=this.strides[u]*t[u];return this.values[l]},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],i=0;i<t.length-1;++i)e+=this.strides[i]*t[i];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),i=0;i<e.length-1;++i)e[i]=Math.floor(t/this.strides[i]),t-=e[i]*this.strides[i];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 Nn().makeTensor(this.values,this.shape,this.dtype)},n}(),Nn=null,Sr=null;function o2(n){Nn=n}function l2(n){Sr=n}var Y=function(){function n(t,e,i,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=st(t),this.strides=yr(t),this.dataId=i,this.id=r,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 de(this,void 0,void 0,function(){var t;return pe(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,Sr.buffer(this.shape,this.dtype,t)]}})})},n.prototype.bufferSync=function(){return Sr.buffer(this.shape,this.dtype,this.dataSync())},n.prototype.array=function(){return de(this,void 0,void 0,function(){var t;return pe(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,br(this.shape,t)]}})})},n.prototype.arraySync=function(){return br(this.shape,this.dataSync())},n.prototype.data=function(){return de(this,void 0,void 0,function(){var t,e;return pe(this,function(i){switch(i.label){case 0:return this.throwIfDisposed(),t=Nn().read(this.dataId),this.dtype==="string"?[4,t]:[3,2];case 1:e=i.sent();try{return[2,e.map(function(r){return Ku(r)})]}catch(r){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}i.label=2;case 2:return[2,t]}})})},n.prototype.dataSync=function(){this.throwIfDisposed();var t=Nn().readSync(this.dataId);if(this.dtype==="string")try{return t.map(function(e){return Ku(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 de(this,void 0,void 0,function(){var t;return pe(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,Nn().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;Nn().disposeTensor(this),this.isDisposedInternal=!0},Object.defineProperty(n.prototype,"isDisposed",{get:function(){return this.is
`)+"Manifest JSON has weights with names: "+(l.join(", ")+"."));return c=a.reduce(function(g,v,b){return v&&g.push(b),g},[]),h=[],c.forEach(function(g){e[g].paths.forEach(function(v){var b=i+(i.endsWith("/")?"":"/")+v;h.push(b)})}),[4,n(h)];case 1:return d=m.sent(),p={},f=0,c.forEach(function(g){for(var v=e[g].paths.length,b=0,w=0;w<v;w++)b+=d[f+w].byteLength;for(var S=new ArrayBuffer(b),L=new Uint8Array(S),x=0,C=0;C<v;C++){var R=new Uint8Array(d[f+C]);L.set(R,x),x+=R.byteLength}var D=s[g];D.forEach(function(k){var W=S.slice(k.groupOffset,k.groupOffset+k.sizeBytes),F=Qf(W,[k.manifestEntry]);for(var P in F)p[P]=F[P]}),f+=v}),[2,p]}})})}}var lA="application/octet-stream",uA="application/json",pm=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=Me().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 de(this,void 0,void 0,function(){var e,i,r,a;return pe(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,i=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:i},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:uA}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:lA}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if(a=s.sent(),a.ok)return[2,{modelArtifactsInfo:ya(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(a.status+"."))}})})},n.prototype.load=function(){return de(this,void 0,void 0,function(){var t,e,i,r,a,s,o,l,u,c,h,d,p,f,m;return pe(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 i=g.sent(),r="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?r+=" 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.":r+=" Please make sure the server is serving valid JSON for this request.",new Error(r);case 5:if(a=e.modelTopology,s=e.weightsManifest,o=e.generatedBy,l=e.convertedBy,u=e.format,c=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:c,generatedBy:o,convertedBy:l,format:u},m=e.modelInitializer,m&&(f.modelInitializer=m),[2,f]}})})},n.prototype.loadWe
2020-10-12 01:22:43 +02:00
`)+("Actual: "+l+`.
`)+("Expected: "+u+"."));for(var c=0;c<u.length;++c){var h=l[c],d=u[c];if(!e(h,d))throw new Error("Arrays differ: actual["+c+"] = "+h+", expected["+c+"] = "+d+`.
`+("Actual: "+l+`.
2020-10-15 15:43:16 +02:00
`)+("Expected: "+u+"."))}}function FA(n,t){n().then(function(){return t.fail()},function(){return t()})}function WA(n,t){var e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ei(n)||ei(n[0])||ei(t)||ei(t[0])?mc(n,e,function(i,r){return i==r}):mc(n,t,function(i,r){return gc(i,r,0)})}function UA(n,t,e){if(e==null&&(e=fc()),!gc(n,t,e))throw new Error("Numbers differ: actual === "+n+", expected === "+t)}function gc(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function BA(n,t,e){for(var i=0;i<n.length;i++)if(n[i]<t||n[i]>e)throw new Error("Value out of range:"+n[i]+" low: "+t+", high: "+e)}function zA(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var PA={__proto__:null,TEST_EPSILON_FLOAT16:Dm,expectArraysClose:kA,testEpsilon:fc,expectPromiseToFail:FA,expectArraysEqual:WA,expectNumbersClose:UA,expectValuesInRange:BA,expectArrayBuffersEqual:zA};var _A="2.6.0";function MA(){Me().set("PROD",!0)}function HA(){Me().set("DEBUG",!0)}function VA(){Me().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Lt(n){Me().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function qA(){z.disposeVariables()}function GA(){return z}function YA(){return z.memory()}function KA(n){return z.profile(n)}function pt(n,t){return z.tidy(n,t)}function Bt(n){var t=Qu(n);t.forEach(function(e){return e.dispose()})}function km(n){return z.keep(n)}function jA(n){return z.time(n)}function $A(n){return z.setBackend(n)}function XA(){return z.ready()}function JA(){return z.backendName}function ZA(n){z.removeBackend(n)}function QA(n){return z.findBackend(n)}function eT(n){return z.findBackendFactory(n)}function tT(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function nT(){return z.backend}function iT(n,t){Me().setPlatform(n,t)}function rT(n,t){var e,i=O(n,"a","add"),r=O(t,"b","add");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.add(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,hs)}var fe=U({add_:rT});function aT(n,t){var e,i=O(n,"a","floorDiv"),r=O(t,"b","floorDiv");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.floorDiv(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Dl)}var vc=U({floorDiv_:aT});function sT(n,t){var e,i=O(n,"a","div"),r=O(t,"b","div");if(e=rt(i,r),i=e[0],r=e[1],i.dtype==="int32"&&r.dtype==="int32")return vc(i,r);var a=function(l,u){var c=l.realDivide(i,r);return u([i,r]),c},s={a:i,b:r},o={};return z.runKernelFunc(a,s,null,Nl,o)}var Ie=U({div_:sT});function oT(n,t){var e,i=O(n,"a","mul"),r=O(t,"b","mul");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.multiply(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Jl)}var J=U({mul_:oT});function lT(n){var t=O(n,"x","abs"),e={x:t};return z.runKernelFunc(function(i,r){return r([t]),t.dtype==="complex64"?i.complexAbs(t):i.abs(t)},e,null,Qo)}var Vt=U({abs_:lT});function uT(n){var t=O(n,"x","acos"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acos(t);return r([t]),a},e,null,el)}var Fm=U({acos_:uT});function cT(n){var t=O(n,"x","acosh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acosh(t);return r([t]),a},e,null,tl)}var Wm=U({acosh_:cT});function hT(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 O(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(!sn(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var i=function(a,s){var o=a.addN(t);return s(t),o},r=t;return z.runKernelFunc(i,r,null,nl)}var dT=U({addN_:hT});function yc(n,t){for(var e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function Um(n,t,e){for(var i=n
with dtype `+s.dtype+". ")});var i=function(s,o){var l=Ze(t,e[0].shape)[0],u=jm(e.map(function(d){return d.shape}),l);if(st(u)===0)return ri([],u);if(e=e.filter(function(d){return d.size>0}),e.length===1)return e[0];var c=e.map(function(d){return d.shape});Km(c,l);var h=s.concat(e,l);return o(e),h},r=e,a={axis:t};return z.runKernelFunc(i,r,null,vl,a)}var Nt=U({concat_:ET});function DT(n){var t=O(n,"x","sigmoid"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.sigmoid(t);return r([a]),a},e,null,bu)}var Bi=U({sigmoid_:DT});function kT(n,t,e){var i=O(n,"x","slice");if(i.rank===0)throw new Error("Slicing scalar is not possible");var r=function(o,l){var u=pc(i,t,e),c=u[0],h=u[1];return ym(i,c,h),l([i]),o.slice(i,c,h)},a={x:i},s={begin:t,size:e};return z.runKernelFunc(r,a,null,mu,s)}var ze=U({slice_:kT});function FT(n){var t=O(n,"x","tanh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.tanh(t);return r([a]),a},e,null,Ru)}var xs=U({tanh_:FT});function WT(n,t,e,i,r,a){var s=O(n,"forgetBias","basicLSTMCell"),o=O(t,"lstmKernel","basicLSTMCell"),l=O(e,"lstmBias","basicLSTMCell"),u=O(i,"data","basicLSTMCell"),c=O(r,"c","basicLSTMCell"),h=O(a,"h","basicLSTMCell"),d=Nt([u,h],1),p=Fe(d,o),f=fe(p,l),m=f.shape[0],g=f.shape[1]/4,v=[m,g],b=ze(f,[0,0],v),w=ze(f,[0,g],v),S=ze(f,[0,g*2],v),L=ze(f,[0,g*3],v),x=fe(J(Bi(b),xs(w)),J(c,Bi(fe(s,S)))),C=J(xs(x),Bi(L));return[x,C]}var UT=U({basicLSTMCell_:WT});function BT(n,t,e){var i=O(n,"x","batchToSpaceND"),r=t.reduce(function(l,u){return l*u});E(i.rank>=1+t.length,function(){return"input rank is "+i.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(i.shape[0]%r===0,function(){return"input tensor batch is "+i.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+t.join(" * ")+" === "+r)});var a=function(l){return l.batchToSpaceND(i,t,e)},s={x:i},o={blockShape:t,crops:e};return z.runKernelFunc(a,s,null,pl,o)}var Cs=U({batchToSpaceND_:BT});function zT(n){var t;return n.rank===0||n.rank===1?t=V(n,[1,1,1,n.size]):n.rank===2?t=V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}function PT(n,t,e,i,r,a){a==null&&(a=.001);var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;i!=null&&(c=O(i,"offset","batchNorm")),E(o.rank===l.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),E(c==null||o.rank===c.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),E(u==null||o.rank===u.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var h=zT(s),d=function(g,v){return v([h,o,l,u]),g.batchNorm(h,Rs(o),Rs(l),Rs(c),Rs(u),a)},p={x:h,scale:u,offset:c,mean:o,variance:l},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,kl,f);return V(m,s.shape)}function Rs(n){return n==null?null:n.rank===0?V(n,[n.size]):n.rank===1?n:n.rank===2?V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n}var La=U({batchNorm_:PT});function _T(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"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(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&E(u.rank===2||u.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&E(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+c.rank+".")}),La(s,o,l,c,u,a)}var
2020-10-12 01:22:43 +02:00
`+r+" and "+t+` for depthToSpace with input shape
`+i.shape}),E(a*t>=0,function(){return`Negative dimension size caused by overflow when multiplying
`+a+" and "+t+` for depthToSpace with input shape
2020-10-15 15:43:16 +02:00
`+i.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 "+i.shape});var o=function(c){return c.depthToSpace(i,t,e)},l={x:i},u={blockSize:t,dataFormat:e};return z.runKernelFunc(o,l,null,Mp,u)}var eg=U({depthToSpace_:m1});function g1(n,t,e,i,r,a,s){r===void 0&&(r="NHWC"),a===void 0&&(a=[1,1]);var o=O(n,"x","depthwiseConv2d"),l=O(t,"filter","depthwiseConv2d"),u=o,c=!1;o.rank===3&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E(u.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+u.rank+".")}),E(l.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(l.rank+".")}),E(u.shape[3]===l.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+u.shape[3]+") must match the inChannels dimension in ")+("filter "+l.shape[2]+".")}),s!=null&&E(it(i),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")});var h=function(m,g){a==null&&(a=[1,1]),E(zt(e,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+e+" and dilations '"+a+"'")});var v=On(u.shape,l.shape,e,a,i,s,!0),b=m.depthwiseConv2D(u,l,v);return g([u,l]),b},d={x:u,filter:l},p={strides:e,pad:i,dataFormat:r,dilations:a,dimRoundingMode:s},f=z.runKernelFunc(h,d,null,Al,p);return c?V(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Ia=U({depthwiseConv2d_:g1});function v1(n){var t=O(n,"x","diag"),e=function(r){var a=V(t,[t.size]),s=r.diag(a),o=n.shape.concat(n.shape);return V(s,o)},i={x:t};return z.runKernelFunc(e,i,null,qp)}var y1=U({diag_:v1});function b1(n,t,e,i,r,a){r===void 0&&(r=[1,1]),a===void 0&&(a="NHWC");var s=O(n,"x","dilation2d"),o=O(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 l=s,u=!1;s.rank===3&&(l=V(s,[1,s.shape[0],s.shape[1],s.shape[2]]),u=!0);var c={x:l,filter:o},h={strides:e,pad:i,dilations:r},d=z.runKernel(Tl,c,h);return u?V(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var tg=U({dilation2d_:b1});function w1(n,t){for(var e=n.length,i=[],r=0;r<e;r++){var a=e-1-r,s=n[a]||1,o=t[t.length-1-r]||1;o>1&&s===1&&i.unshift(a)}return i}function ft(n,t){for(var e=[],i=0;i<t.length;i++){var r=n[n.length-i-1],a=t.length-i-1,s=t[a];(r==null||r===1&&s>1)&&e.unshift(a)}return e}function Qe(n,t){for(var e=[],i=Math.max(n.length,t.length),r=0;r<i;r++){var a=n[n.length-r-1];a==null&&(a=1);var s=t[t.length-r-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 S1(n,t){var e,i=O(n,"a","equal"),r=O(t,"b","equal");e=rt(i,r),i=e[0],r=e[1],Qe(i.shape,r.shape);var a=function(o){return o.equal(i,r)},s={a:i,b:r};return z.runKernelFunc(a,s,null,jp)}var Aa=U({equal_:S1});function L1(n,t,e){var i=O(t,"a","where"),r=O(e,"b","where"),a=O(n,"condition","where","bool"),s=Qe(i.shape,r.shape),o=Os(i,s),l=Os(r,s);a.rank===1&&E(a.shape[0]===i.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}),a.rank!==1&&Ue(a.shape,l.shape,"Error in where: ");var u=function(h,d){var p=h.select(a,o,l);return d([a]),p},c={condition:a,t:o,e:l};return z.runKernelFunc(u,c,null,pu)}var hn=U({where_:L1});function I1(n){var t=O(n,"x","zerosLike"),e={x:t};return z.runKernelFunc(function(i){return i.zerosLike(t)},e,null,Fu)}var Ee=U({zerosLike_:I1});function A1(n,t){var e,i=O(n,"a","div"),r=O(t,"b","div");e=rt(i,r),i=e[0],r=e[1];var a=Ie(i,r),s=Ee(a),o=Aa(r,s);return hn(o,s,a)}var ng=U({divNoNan_:A1});function T1(n,t){var e=O(n,"t1","dot"),i=O(t,"t2","dot");E((e.rank===1||e.rank===2)&&(i.rank===1||i
rank `+a.rank+"."}),E(it(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=V(a,[1,a.shape[0],a.shape[1],a.shape[2]]));var l=function(d,p){var f=d.localResponseNormalization4D(s,t,e,i,r);return p([s,f]),f},u={x:s},c={depthRadius:t,bias:e,alpha:i,beta:r},h=z.runKernelFunc(l,u,null,Vl,c);return o?V(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var dg=U({localResponseNormalization_:X1});function J1(n){var t=O(n,"x","log"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.log(t);return r([t]),a},e,null,_l)}var _i=U({log_:J1});function Z1(n){var t=O(n,"x","log1p"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.log1p(t);return r([t]),a},e,null,Ml)}var Cc=U({log1p_:Z1});function Q1(n){return E(ti(n),function(){return"The f passed in grad(f) must be a function"}),function(t,e){var i=O(t,"x","tf.grad",null),r=e!=null?O(e,"dy","tf.grad"):null;return z.tidy(function(){var a=z.gradients(function(){return n(i)},[i],r),s=a.value,o=a.grads;return r!=null&&Ue(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Us(o),o[0]})}}function eN(n){return E(ti(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 i=va(t,"args","tf.grads",null),r=e!=null?O(e,"dy","tf.grads"):null;return z.tidy(function(){var a=z.gradients(function(){return n.apply(void 0,i)},i,r),s=a.value,o=a.grads;return r!=null&&Ue(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Us(o),o})}}function tN(n){return E(ti(n),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(t,e){E(t instanceof Y,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),E(e==null||e instanceof Y,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var i=z.gradients(function(){return n(t)},[t],e),r=i.grads,a=i.value;return Us(r),{grad:r[0],value:a}}}function nN(n){return E(ti(n),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(t,e){E(Array.isArray(t)&&t.every(function(r){return r instanceof Y}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),E(e==null||e instanceof Y,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var i=z.gradients(function(){return n.apply(void 0,t)},t,e);return e!=null&&Ue(i.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Us(i.grads),i}}function pg(n,t){E(ti(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 ga}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var e=t!=null;if(!e){t=[];for(var i in z.registeredVariables)t.push(z.registeredVariables[i])}var r=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),l=o.value,u=o.grads;E(u.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(l.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+l.rank+" tensor")});var c={};return t.forEach(function(h,d){u[d]!=null&&(c[h.name]=u[d])}),r!=null&&r.forEach(function(h){return c[h.name]=null}),{value:l,grads:c}}function En(n){return z.customGrad(n)}function Us(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 iN(n){var t=O(n,"x","neg"),e={x:t};return z.runKernelFunc(function(i){return i.neg(t)},e,null,Zl)}var mt=U({neg_:iN});function rN(n){var t=O(n,"x","softplus"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.softplus(t);return r([t]),a},e,null,wu)}var Rc=U({softplus_:rN});function aN(n){var t=O(n,"x","logSigmoid"),e=En(function(i){var r=mt(Rc(mt(i))),a=function(s){var o=J(s,Bi(mt(i)));return o};return{value:r,gradFunc:a}});return e(t)}var fg=U({logSigmoid_:aN});function sN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","max"),r=function(o,l){var u=Ze(t,i.shape),c=u,h=Qt(c,i.rank),d=i;h!=null&&(d=lt(i,h),c=Rn(c.length,d.rank));var p=o.max(d,c);h!=null&&d.dispose();var f=p;if(e){var m=Zt(f.shape,Ze(t,i.shape));f=V(f,m),p.dispose()}return l([i,f]),f},a={x:i},s={reductionIndices:t,keepDims:e};return z.runKernelFunc(r,a,null,ql,s)}var Mi=U({max_:sN});function oN(n,t){var e,i=O(n,"a","sub"),r=O(t,"b","sub");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.subtract(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,xu)}var ge=U({sub_:oN});function lN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","sum");i.dtype==="bool"&&(i=ue(i,"int32"));var r=function(o,l){l([i]);var u=Ze(t,i.shape),c=Qt(u,i.rank),h=u,d=i;c!=null&&(d=lt(i,c),h=Rn(h.length,i.rank));var p=o.sum(d,h);if(e){var f=Zt(p.shape,u);p=V(p,f)}return p},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,Lu,s)}var Ae=U({sum_:lN});function uN(n,t){t===void 0&&(t=-1);var e=O(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 i=function(s,o){var l=!0,u=Mi(n,t,!0),c=ge(n,u),h=ge(ue(c,"float32"),_i(Ae(dn(c),t,l)));return o([h]),h},r={logits:e},a={axis:t};return z.runKernelFunc(i,r,null,Hl,a)}var mg=U({logSoftmax_:uN});function cN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","logSumExp"),r=Ze(t,i.shape),a=Mi(i,r,!0),s=ge(i,a),o=dn(s),l=Ae(o,r),u=_i(l),c=fe(V(a,u.shape),u);if(e){var h=Zt(c.shape,r);return V(c,h)}return c}var Oc=U({logSumExp_:cN});function hN(n,t){var e=O(n,"a","logicalAnd","bool"),i=O(t,"b","logicalAnd","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalAnd(e,i)},r,null,sf)}var Hi=U({logicalAnd_:hN});function dN(n){var t=O(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(i){return i.logicalNot(t)},e,null,of)}var Bs=U({logicalNot_:dN});function pN(n,t){var e=O(n,"a","logicalOr","bool"),i=O(t,"b","logicalOr","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalOr(e,i)},r,null,lf)}var Ec=U({logicalOr_:pN});function fN(n,t){var e=O(n,"a","logicalXor","bool"),i=O(t,"b","logicalXor","bool");return Qe(e.shape,i.shape),Hi(Ec(n,t),Bs(Hi(n,t)))}var gg=U({logicalXor_:fN});function mN(n,t,e,i,r){var a=O(n,"x","maxPool"),s=1,o=a,l=!1;a.rank===3&&(l=!0,o=V(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(zt(e,s),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),r!=null&&E(it(i),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+r+" but got pad "+i+".")});var u=function(p,f){var m=xr(o.shape,t,e,1,i,r),g;return m.filterWidth===1&&m.filterHeight===1&&sn(m.inShape,m.outShape)?g=o.clone():g=p.maxPool(o,m),f([o,g]),g},c={x:o},h={filterSize:t,strides:e,pad:i,dimRoundingMode:r},d=z.runKernelFunc(u,c,null,Yl,h);return l?V(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Dc=U({maxPool_:mN});function gN(n,t,e,i,r,a,s){t===void 0&&(t=[1,1,1]),a===void 0&&(a="NDHWC"),s==null?s=[1,1,1]:Lt("dilations is deprecated, this field will be gone in v3.0.0.");var o=O(n,"x","maxPool3d"),l=o,u=!1;o.rank===4&&(u=!0,l=V(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),E(l.rank===5,function(){return"Error i
2020-10-12 01:22:43 +02:00
`+("1. The "+i+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
`+("2. The custom "+i+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");return u}else{var c=n;if(c.className==null||c.config==null)throw new M(i+": Improper config format: "+(JSON.stringify(c)+`.
2020-10-15 15:43:16 +02:00
`)+"'className' and 'config' must set.");var h=c.className,d=void 0,p=void 0;if(h in e?(a=e[h],d=a[0],p=a[1]):h in on?(s=on.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 "+i+": "+h+`. This may be due to one of the following reasons:
2020-10-12 01:22:43 +02:00
`+("1. The "+i+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-10-15 15:43:16 +02:00
`+("2. The custom "+i+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(p!=null){for(var f={},m=0,g=Object.keys(on);m<g.length;m++){var v=g[m];f[v]=on[v]}for(var b=0,w=Object.keys(e);b<w.length;b++){var v=w[b];f[v]=e[v]}var S=c.config;S.customObjects=f;for(var L=qt({},on),x=0,C=Object.keys(e);x<C.length;x++){var v=C[x];on[v]=e[v]}rh(c.config);var R=p(d,c.config,e,r);return on=qt({},L),R}else{for(var L=qt({},on),D=0,k=Object.keys(e);D<k.length;D++){var v=k[D];on[v]=e[v]}var R=new d(c.config);return on=qt({},L),R}}}function MD(n,t){return n<t?-1:n>t?1:0}function Qs(n,t){return-1*MD(n,t)}function di(n){if(n==null)return n;for(var t=[],e=0,i=n;e<i.length;e++){var r=i[e];t.indexOf(r)===-1&&t.push(r)}return t}function HD(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 zr(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 ah(n,t,e,i){return e===void 0&&(e=0),i===void 0&&(i=Infinity),kn(e>=0),kn(i>=e),Array.isArray(n)&&n.length>=e&&n.length<=i&&n.every(function(r){return typeof r===t})}function It(n,t){Array.isArray(n)?(y.util.assert(n.length>0,function(){return t+" is unexpectedly an empty array."}),n.forEach(function(e,i){return It(e,"element "+(i+1)+" of "+t)})):y.util.assert(Number.isInteger(n)&&n>0,function(){return"Expected "+t+" to be a positive integer, but got "+(yv(n)+".")})}function yv(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return yv(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function VD(n,t){var e=y.util.now(),i,r=function(){for(var a=[],s=0;s<arguments.length;s++)a[s]=arguments[s];var o=y.util.now();return o-e<t||(e=o,i=n.apply(void 0,a)),i};return r}function bv(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}function sh(n,t){return y.tidy(function(){return y.sqrt(y.sum(y.mul(n,n),t,!0))})}var Ea=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.getConfig=function(){return{}},t}(y.serialization.Serializable),wv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.defaultMaxValue=2,i.defaultAxis=0,i.maxValue=e.maxValue!=null?e.maxValue:i.defaultMaxValue,i.axis=e.axis!=null?e.axis:i.defaultAxis,i}return t.prototype.apply=function(e){var i=this;return y.tidy(function(){var r=sh(e,i.axis),a=y.clipByValue(r,0,i.maxValue);return y.mul(e,y.div(a,y.add(gt(),r)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(Ea);y.serialization.registerClass(wv);var Sv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.defaultAxis=0,i.axis=e.axis!=null?e.axis:i.defaultAxis,i}return t.prototype.apply=function(e){var i=this;return y.tidy(function(){return y.div(e,y.add(gt(),sh(e,i.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(Ea);y.serialization.registerClass(Sv);var Lv=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e){return y.relu(e)},t.className="NonNeg",t}(Ea);y.serialization.registerClass(Lv);var Iv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.defaultMinValue=0,i.defaultMaxValue=1,i.defaultRate=1,i.defaultAxis=0,i.minValue=e.minValue!=null?e.minValue:i.defaultMinValue,i.maxValue=e.maxValue!=null?e.maxValue:i.defaultMaxValue,i.rate=e.rate!=null?e.rate:i.defaultRate,i.axis=e.axis!=null?e.axis:i.defaultAxis,i}return t.prototype.apply=function(e){var i=this;return y.tidy(function(){var r=sh(e,i.axis),a=y.add(y.mul(i.rate,y.clipByValue(r,i.minValue,i.maxValue)),y.mul(1-i.rate,r));return y.mul(e,y.div(a,y.add(gt(),r)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(Ea);y.serialization.registerClass(Iv);var Av={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),un(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),i.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(i.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");i.tensor=e,B.keep(e),i.written=!0,this.tensors[t]=i},n.prototype.writeMany=function(t,e){var i=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(r,a){return i.write(r,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 i=0;i<this.size();i++)t.push(i)}if(t.length===0)return B.tensor([],[0].concat(this.elementShape));var r=this.readMany(t);return un(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),B.stack(r,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 B.tensor([],[0].concat(this.elementShape));for(var e=[],i=0;i<this.size();i++)e.push(i);var r=this.readMany(e);return un(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),B.concat(r,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 i=Math.max.apply(Math,t);if(!this.dynamicSize&&i>=this.maxSize)throw new Error("Max index must be < array size ("+i+" vs. "+this.maxSize+")");this.writeMany(t,B.unstack(e,0))},n.prototype.split=function(t,e){var i=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,a=t.map(function(c){return r+=c,r});if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
2020-10-12 01:22:43 +02:00
tensor.shape[0], but sum of lengths is
2020-10-15 15:43:16 +02:00
`+r+", 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=r===0?0:e.size/r,o=[];B.tidy(function(){e=B.reshape(e,[1,r,s]);for(var c=0;c<t.length;++c){var h=c===0?0:a[c-1],d=[0,h,0],p=[1,t[c],s];o[c]=B.reshape(B.slice(e,d,p),i.elementShape)}return o});for(var l=[],u=0;u<t.length;u++)l[u]=u;this.writeMany(l,o)},n}();var Ao=function(){function n(t,e,i,r){r===void 0&&(r=-1),this.tensors=t,this.elementShape=e,this.elementDtype=i,t!=null&&t.forEach(function(a){if(i!==a.dtype)throw new Error("Invalid data types; op elements "+i+", but list elements "+a.dtype);un(e,a.shape,"TensorList shape mismatch: "),B.keep(a)}),this.idTensor=B.scalar(0),this.maxNumElements=r,B.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(this.tensors.slice(),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,i){var r=this;if(i===void 0&&(i=-1),e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);if(i!==-1&&this.tensors.length!==i)throw new Error("Operation expected a list with "+i+" elements but got a list with "+this.tensors.length+" elements.");return un(t,this.elementShape,"TensorList shape mismatch: "),B.tidy(function(){var a=r.tensors.map(function(s){return B.reshape(s,t)});return B.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 i=this.tensors.pop();return un(i.shape,t,"TensorList shape mismatch: "),B.reshape(i,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(un(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");B.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,i){if(i!==this.elementDtype)throw new Error("Invalid data types; op elements "+i+", 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 un(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.");un(this.elementShape,e.shape,"TensorList shape mismatch: "),B.keep(e),this.tensors[t]=e},n.prototype.gather=function(t,e,i){var r=this;if(e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);return un(this.elementShape,i,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?B.tensor([],[0].concat(this.elementShape)):B.tidy(function(){var a=t.map(function(s){return B.reshape(r.tensors[s],i)});return B.stack(a,0)})},n.prototype.concat=function(t,e){var i=thi
2020-10-12 01:22:43 +02:00
tensor.shape[0], but sum of lengths is
2020-10-15 15:43:16 +02:00
`+i+", and tensor's shape is: "+n.shape);for(var a=i===0?0:n.size/i,s=B.tidy(function(){var u=[];n=B.reshape(n,[1,i,a]);for(var c=0;c<t.length;++c){var h=c===0?0:r[c-1],d=[0,h,0],p=[1,t[c],a];u[c]=B.reshape(B.slice(n,d,p),e)}return n.dispose(),u}),o=new Ao([],e,n.dtype,t.length),l=0;l<s.length;l++)o.setItem(l,s[l]);return o}var kW=void 0,FW=function(n,t,e){return Un(kW,void 0,void 0,function(){var i,r,a,s,o,l,u,c,o,h,d,l,p,f,m,m,g,v,g,b,g,g,g,w,S,L,x,C,R,D,k,W,F,P,H,_,K,j,q,G,Z,X,ee,ne,ie,te,re,le,he,ye,Oe,ke,Pe,_e,ct,wt,qe,We,F,P,me,We,K,L,Ot,me,ne,ie,L,ot,me,L,ht,ot,me,q,G,L,ht,me,We,L,ht,ot,me,Tn,L,ht,me,re,me,he,L,We,P,me,We,L,Ot,me,Oe,L,ke,me;return bn(this,function(Ct){switch(Ct.label){case 0:i=n.op;switch(i){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 r=A("thenBranch",n,t,e),a=A("elseBranch",n,t,e),s=A("cond",n,t,e),o=A("args",n,t,e),[4,s.data()];case 2:return l=Ct.sent(),l[0]?[2,e.functionMap[r].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)]:[2,e.functionMap[a].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 3:return u=A("body",n,t,e),c=A("cond",n,t,e),o=A("args",n,t,e),[4,e.functionMap[c].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 4:return h=Ct.sent(),d=o.map(function(St){return St.id}),[4,h[0].data()];case 5:l=Ct.sent(),h.forEach(function(St){!St.kept&&d.indexOf(St.id)===-1&&St.dispose()}),p=o,f=function(){var St,Ce,Et;return bn(this,function(dt){switch(dt.label){case 0:return St=p,[4,e.functionMap[u].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 1:return p=dt.sent(),Ce=p.map(function(nt){return nt.id}),St.forEach(function(nt){!nt.kept&&d.indexOf(nt.id)===-1&&Ce.indexOf(nt.id)===-1&&nt.dispose()}),[4,e.functionMap[c].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 2:return Et=dt.sent(),[4,Et[0].data()];case 3:return l=dt.sent(),Et.forEach(function(nt){!nt.kept&&d.indexOf(nt.id)===-1&&Ce.indexOf(nt.id)===-1&&nt.dispose()}),[2]}})},Ct.label=6;case 6:return l[0]?[5,f()]:[3,8];case 7:return Ct.sent(),[3,6];case 8:return[2,p];case 9:return m=A("pred",n,t,e),[2,[Xn(m)]];case 10:return m=A("pred",n,t,e),g=A("data",n,t,e),g.kept||(g=Xn(g)),[4,m.data()];case 11:return[2,Ct.sent()[0]?[void 0,g]:[g,void 0]];case 12:return v=n.inputNames.find(function(St){return Mt(St,t,e)!==void 0}),v?(g=Mt(v,t,e),[2,[Xn(g)]]):[2,void 0];case 13:return b=A("frameName",n,t,e),g=A("tensor",n,t,e),e.enterFrame(b),[2,[Xn(g)]];case 14:return g=A("tensor",n,t,e),e.exitFrame(),[2,[Xn(g)]];case 15:return g=A("tensor",n,t,e),e.nextIteration(),[2,[Xn(g)]];case 16:return w=A("size",n,t,e),S=A("dtype",n,t,e),L=A("elementShape",n,t,e),x=A("dynamicSize",n,t,e),C=A("clearAfterRead",n,t,e),R=A("identicalElementShapes",n,t,e),D=A("name",n,t,e),k=new CW(D,S,w,L,R,x,C),e.addTensorArray(k),[2,[k.idTensor,B.scalar(1)]];case 17:return W=A("tensorArrayId",n,t,e),F=A("index",n,t,e),P=A("tensor",n,t,e),H=e.getTensorArray(W.id),H.write(F,P),[2,[H.idTensor]];case 18:return _=A("tensorArrayId",n,t,e),K=A("index",n,t,e),j=e.getTensorArray(_.id),[2,[j.read(K)]];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),jt(function(){return se(i,void 0,void 0,function(){return oe(this,function(s){switch(s.label){case 0:return[4,r.iterator()];case 1:return[2,s.sent().columnMajorBatch(t,e,EU)]}})})},a)},n.prototype.concatenate=function(t){var e=this,i=this,r;return this.size===Infinity||t.size===Infinity?r=Infinity:this.size!=null&&t.size!=null?r=this.size+t.size:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s;return oe(this,function(o){switch(o.label){case 0:return[4,i.iterator()];case 1:return s=(a=o.sent()).concatenate,[4,t.iterator()];case 2:return[2,s.apply(a,[o.sent()])]}})})},r)},n.prototype.filter=function(t){var e=this,i=this,r;return this.size===Infinity?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().filter(function(s){return Ne.tidy(function(){return t(s)})})]}})})},r)},n.prototype.forEachAsync=function(t){return se(this,void 0,void 0,function(){return oe(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,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().map(function(a){return Ne.tidy(function(){return t(a)})})]}})})},this.size)},n.prototype.mapAsync=function(t){var e=this,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.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 i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().prefetch(t)]}})})},this.size)},n.prototype.repeat=function(t){var e=this,i=this,r;return this.size!=null&&t>0?r=this.size*t:t===0?r=0:this.size!=null&&(t===void 0||t<0)?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s=this;return oe(this,function(o){return a=od(function(){return se(s,void 0,void 0,function(){var l;return oe(this,function(u){switch(u.label){case 0:return l={},[4,i.iterator()];case 1:return[2,(l.value=u.sent(),l.done=!1,l)]}})})}),[2,bU(a.take(t))]})})},r)},n.prototype.skip=function(t){var e=this,i=this,r;return this.size!=null&&t>=0&&this.size>=t?r=this.size-t:this.size!=null&&(this.size<t||t===void 0||t<0)?r=0:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().skip(t)]}})})},r)},n.prototype.shuffle=function(t,e,i){var r=this;if(i===void 0&&(i=!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=sw(e||Ne.util.now().toString());return jt(function(){return se(r,void 0,void 0,function(){var o;return oe(this,function(l){switch(l.label){case 0:return o=s.int32(),i&&(o+=s.int32()),[4,a.iterator()];case 1:return[2,l.sent().shuffle(t,o.toString())]}})})},this.size)},n.prototype.take=function(t){var e=this,i=this,r;return this.size!=null&&this.size>t?r=t:this.size!=null&&this.size<=t?r=this.size:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().take(t)]}})})},r)},n.prototype.toArray=function(){return se(this,void 0,void 0,function(){return oe(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,r]}})})},t}(qa);var No='"',Ga=Symbol("out"),gw=Symbol("field"),xo=Symbol("quote"),ud=Symbol("quoteafterquote"),vw=Symbol("quoteinquote"),yw=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.input=e,r.hasHeader=!0,r.fullColumnNames=null,r.columnNamesValidated=!1,r.columnConfigs=null,r.configuredColumnsOnly=!1,r.delimiter=",",r.delimWhitespace=!1,r.base=new mw(e),i||(i={}),r.hasHeader=!(i.hasHeader===!1),r.fullColumnNames=i.columnNames,r.columnConfigs=i.columnConfigs,r.configuredColumnsOnly=i.configuredColumnsOnly,i.delimWhitespace?(Ne.util.assert(i.delimiter==null,function(){return"Delimiter should not be provided when delimWhitespace is true."}),r.delimWhitespace=!0,r.delimiter=" "):r.delimiter=i.delimiter?i.delimiter:",",r}return t.prototype.columnNames=function(){return se(this,void 0,void 0,function(){return oe(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 se(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u=this;return oe(this,function(c){switch(c.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(e=c.sent(),!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&e&&Ne.util.assert(e.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+u.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=e),i=this.fullColumnNames.reduce(function(h,d){return h[d]=h[d]+1||1,h},{}),r=Object.keys(i).filter(function(h){return i[h]>1}),Ne.util.assert(r.length===0,function(){return"Duplicate column names found: "+r.toString()}),this.columnConfigs){for(a=0,s=Object.keys(this.columnConfigs);a<s.length;a++)if(o=s[a],l=this.fullColumnNames.indexOf(o),l===-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 se(this,void 0,void 0,function(){var e,i,r,a;return oe(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(i=s.sent(),i.done)throw new Error("No data was found for CSV parsing.");return r=i.value,a=this.parseRow(r,!1),[2,a];case 3:return[2,null]}})})},t.prototype.iterator=function(){return se(this,void 0,void 0,function(){var e,i=this;return oe(this,function(r){switch(r.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:r.sent(),r.label=2;case 2:return[4,this.base.iterator()];case 3:return e=r.sent(),this.hasHeader&&(e=e.skip(1)),[2,e.map(function(a){return i.makeDataElement(a)})]}})})},t.prototype.makeDataElement=function(e){for(var i=this.parseRow(e),r={},a={},s=0;s<this.fullColumnNames.length;s++){var o=this.fullColumnNames[s],l=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!l)continue;var u=i[s],c=null;if(u==="")if(l&&l.default!==void 0)c=l.default;else{if(l&&(l.required||l.isLabel))throw new Error("Required column "+o+" is empty in this line: "+e);c=void 0}else{var h=Number(u);if(isNaN(h))l&&l.dtype==="bool"?c=this.getBoolean(u):c=u;else if(!l||!l.dtype)c=h;else switch(l.dtype){case"float32":c=h;break;case"int32":c=Math.floor(h);break;case"bool":c=this.getBoolean(u);break;default:c=h}}l&&l.isLabel?a[o]=c:r[o]=c}return Object.keys(a).length===0?r:{xs:r,ys:a}},t.prototype.getBoolean=function(e){return e==="1"||e.toLowerCase()==="true"?1:0},t.prototype.parseRow=function(e,i){i===void 0&&(i=!0);for(var r=[],a=0,s=e.length,o=Ga,l=0;l<s;l++)switch(o){case Ga:switch(e.charAt(l)){case No:a=l+1,o=xo;break;case this.delimiter:if(a=l+1,this.delimiter===" "&&this
2020-10-12 01:22:43 +02:00
============================
Hi there 👋. 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-10-15 15:43:16 +02:00
============================`));var a={};return this.data.set(a,{values:e,dtype:r,refCount:1}),a},t.prototype.makeTensorInfo=function(e,i,r){var a=this.write(r,e,i);return{dataId:a,shape:e,dtype:i}},t.prototype.incRef=function(e){var i=this.data.get(e);i.refCount++},t.prototype.decRef=function(e){if(this.data.has(e)){var i=this.data.get(e);i.refCount--}},t.prototype.move=function(e,i,r,a){this.data.set(e,{values:i,dtype:a,refCount:1})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return Mw(this,void 0,void 0,function(){return Hw(this,function(i){return[2,this.readSync(e)]})})},t.prototype.readSync=function(e){var i=this.data.get(e),r=i.dtype,a=i.complexTensorInfos;if(r==="complex64"){var s=this.readSync(a.real.dataId),o=this.readSync(a.imag.dataId);return T.backend_util.mergeRealAndImagArrays(s,o)}return this.data.get(e).values},t.prototype.bufferSync=function(e){var i=this.readSync(e.dataId),r=i;if(e.dtype==="string")try{r=i.map(function(a){return T.util.decodeString(a)})}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return T.buffer(e.shape,e.dtype,r)},t.prototype.makeOutput=function(e,i,r){var a=this.write(e,i,r);return T.engine().makeTensorFromDataId(a,i,r,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var i=this.data.get(e).complexTensorInfos;i!=null&&(this.disposeData(i.real.dataId),this.disposeData(i.imag.dataId)),this.data.delete(e)}},t.prototype.disposeIntermediateTensorInfo=function(e){var i=e.dataId;if(this.data.has(i)){var r=this.data.get(i);r.refCount--,r.refCount<1&&this.disposeData(i)}},t.prototype.time=function(e){return Mw(this,void 0,void 0,function(){var i,r;return Hw(this,function(a){return i=T.util.now(),e(),r=T.util.now()-i,[2,{kernelMs:r}]})})},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,i,r,a){ae(e,"stridedSlice");var s=T.slice_util.computeOutShape(i,r,a);if(s.some(function(p){return p===0}))return T.tensor([],s);for(var o=T.buffer(s,e.dtype),l=this.bufferSync(e),u=0;u<o.size;u++){for(var c=o.indexToLoc(u),h=new Array(c.length),d=0;d<h.length;d++)h[d]=c[d]*a[d]+i[d];o.set.apply(o,[l.get.apply(l,h)].concat(c))}return o.toTensor()},t.prototype.diag=function(e){for(var i=this.readSync(e.dataId),r=T.buffer([e.size,e.size],e.dtype),a=r.values,s=0;s<i.length;s++)a[s*e.size+s]=i[s];return r.toTensor()},t.prototype.unstack=function(e,i){for(var r=e.shape[i],a=new Array(e.rank-1),s=0,o=0;o<e.rank;o++)o!==i&&(a[s++]=e.shape[o]);var l=new Array(e.rank).fill(0),u=e.shape.slice();u[i]=1;for(var c=new Array(r),o=0;o<c.length;o++)l[i]=o,c[o]=T.slice(e,l,u).reshape(a);return c},t.prototype.reverse=function(e,i){ae(e,"reverse");for(var r=T.buffer(e.shape,e.dtype),a=this.bufferSync(e),s=function(l){var u=r.indexToLoc(l),c=u.slice();i.forEach(function(h){return c[h]=e.shape[h]-1-c[h]}),r.set.apply(r,[a.get.apply(a,c)].concat(u))},o=0;o<r.size;o++)s(o);return r.toTensor()},t.prototype.neg=function(e){return ae(e,"neg"),T.mul(T.scalar(-1),e)},t.prototype.addN=function(e){var i=this;ae(e,"addN");for(var r=e.map(function(c){return i.readSync(c.dataId)}),a=T.buffer(e[0].shape,e[0].dtype),s=a.values,o=0;o<e.length;o++)for(var l=r[o],u=0;u<s.length;u++)s[u]+=l[u];return a.toTensor()},t.prototype.softmax=function(e,i){var r=T.util.parseAxisParam([i],e.shape),a=T.max(e,r),s=T.backend_util.expandShapeToKeepDim(a.shape,r),o=T.sub(e,a.reshape(s)),l=T.exp(o),u=this.sum(l,r).reshape(s);return T.div(l,u)},t.prototype.pow=function(e,i){return ae([e,i],"pow"),this.broadcastedBinaryOp(e,i,e.dtype,function(r,a){return Math.pow(r,a)})},t.prototype.batchMatMul=function(e,i,r,a){ae([e,i],"matMul");for(var s=r?e.shape[1]:e.shape[2],o=r?e.shape[2]:e.shape[1],l=a?i.shape[1]:i.shape[2],u=e.shape[0],c=this.readSync(e.dataId),h=this.readSync(i.dataId),d=r?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],p=d[0],f=d[1],m=d[2],g=a?[1,i.strides[1],i.strides[0]]:[i.strides[
2020-10-12 01:22:43 +02:00
`),a=r.length.toString().length+2,s=r.map(function(d,p){return N.util.rightPad((p+1).toString(),a)+d}),o=0,l=0;l<s.length;l++)o=Math.max(s[l].length,o);var u=s.slice(0,i-1),c=s.slice(i-1,i),h=s.slice(i);console.log(u.join(`
`)),console.log(t.split(`
`)[0]),console.log("%c "+N.util.rightPad(c[0],o),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join(`
2020-10-15 15:43:16 +02:00
`))}function y0(n){return Jn(n,function(){return n.createProgram()},"Unable to create WebGLProgram.")}function b0(n,t){if(ce(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 Do(n,t){if(ce(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 w0(n,t){var e=Jn(n,function(){return n.createBuffer()},"Unable to create WebGLBuffer");return ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)}),ce(n,function(){return n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)}),e}function S0(n,t){var e=Jn(n,function(){return n.createBuffer()},"Unable to create WebGLBuffer");return ce(n,function(){return n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)}),ce(n,function(){return n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)}),e}function ZP(){return N.env().getNumber("WEBGL_VERSION")===2?1:4}function L0(n){return Jn(n,function(){return n.createTexture()},"Unable to create WebGLTexture.")}function I0(n,t){var e=N.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){var i="["+n+"x"+t+"]";throw new Error("Requested texture size "+i+" is invalid.")}if(n>e||t>e){var i="["+n+"x"+t+"]",r="["+e+"x"+e+"]";throw new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU "+r+".")}}function A0(n){return Jn(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Cd(n,t,e,i,r,a,s){var o=n.getAttribLocation(t,e);return o===-1?!1:(ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,i)}),ce(n,function(){return n.vertexAttribPointer(o,r,n.FLOAT,!1,a,s)}),ce(n,function(){return n.enableVertexAttribArray(o)}),!0)}function N0(n,t,e){T0(n,e),ce(n,function(){return n.activeTexture(n.TEXTURE0+e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function QP(n,t){T0(n,t),ce(n,function(){return n.activeTexture(n.TEXTURE0+t)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function x0(n,t,e){return Jn(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function C0(n,t,e){return n.getUniformLocation(t,e)}function R0(n,t,e,i){ce(n,function(){return N0(n,t,i)}),ce(n,function(){return n.uniform1i(e,i)})}function e_(n){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,null)}),ce(n,function(){return n.viewport(0,0,n.canvas.width,n.canvas.height)}),ce(n,function(){return n.scissor(0,0,n.canvas.width,n.canvas.height)})}function ko(n,t,e){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,e)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0)})}function Rd(n,t){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,t)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0)})}function es(n){var t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+O0(n,t))}function O0(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 Jn(n,t,e){var i=ce(n,function(){return t()});if(i==null)throw new Error(e);return i}function T0(n,t){var e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,i=t+n.TEXTURE0;if(i<n.TEXTURE0||i>e){var r="[gl.TEXTURE0, gl.TEXTURE"+e+"]";throw new Error("textureUnit must be in "+r+".")}}function lr(n,t){return t===void 0&&(t=2),N.util.sizeFromShape(n.slice(0,n.length-t))}function ur(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 Fo(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[lr(n)]
2020-10-12 01:22:43 +02:00
void main() {
`+i.join(`
`)+`
float result = `+r+`;
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var k_=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 i=[];this.variableNames.forEach(function(a){i.push("vec4 v"+a+" = get"+a+"AtOutCoords();")});var r=this.variableNames.map(function(a){return"v"+a}).join(" + ");this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+i.join(`
`)+`
vec4 result = `+r+`;
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var F_=function(){function n(t,e,i){this.variableNames=["A"];var r=t.windowSize,a=t.batchSize,s=t.outSize;i||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];var o=e==="max"?">":"<",l=i?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * `+r+`;
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < `+r+`; i++) {
int inIdx = `+l+`;
float candidate = getA(batch, inIdx);
if (candidate `+o+` bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-10-15 15:43:16 +02:00
`}return n}();function P0(n,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return n+"."+e})}function $t(n,t){return t===1?[n]:P0(n,t)}function W_(n,t){if(n===1)return"rc";for(var e="",i=0;i<n;i++)e+=t[i],i<n-1&&(e+=",");return e}function Dt(){var n,t,e,i,r,a,s,o,l,u;return N.env().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",i="in",r="texture",a="outputColor",s="out vec4 outputColor;",o=`
2020-10-12 01:22:43 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`,l="",u=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(n="",t="attribute",e="varying",i="varying",r="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;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,l=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,u=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-10-15 15:43:16 +02:00
`),{version:n,attribute:t,varyingVs:e,varyingFs:i,texture2D:r,output:a,defineOutput:s,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function cr(n,t,e){e===void 0&&(e="index");var i=N.util.computeStrides(t);return i.map(function(r,a){var s="int "+n[a]+" = "+e+" / "+r,o=a===i.length-1?"int "+n[a+1]+" = "+e+" - "+n[a]+" * "+r:"index -= "+n[a]+" * "+r;return s+"; "+o+";"}).join("")}function kd(n){var t=N.util.computeStrides(n).map(function(e){return e.toString()});return`
2020-10-12 01:22:43 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * `+t[0]+" + coords.y * "+t[1]+` + coords.z;
}
2020-10-15 00:22:38 +02:00
`}var _0=`
2020-10-12 01:22:43 +02: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);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
2020-10-15 00:22:38 +02:00
`;var M0=N.backend_util.getBroadcastDims;function q_(n,t,e,i){var r=[];n.forEach(function(f){var m=N.util.sizeFromShape(f.shapeInfo.logicalShape);f.shapeInfo.isUniform?r.push("uniform float "+f.name+(m>1?"["+m+"]":"")+";"):(r.push("uniform sampler2D "+f.name+";"),r.push("uniform int offset"+f.name+";"))});var a=r.join(`
`),s=n.map(function(f){return U_(f,t,i)}).join(`
`),o=t.texShape,l=Dt(),u=P_(l),c,h,d=H_(l);t.isPacked?(c=B_(t.logicalShape,o),h=M_(l)):(c=z_(t.logicalShape,o),h=__(l)),i&&(d+=V_);var p=[d,u,h,a,c,s,e].join(`
2020-10-15 15:43:16 +02:00
`);return p}function ta(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return G_(n);case 1:return Y_(n);case 2:return K_(n);case 3:return j_(n);case 4:return $_(n);case 5:return X_(n);case 6:return J_(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function H0(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return Z_(n);case 1:return Q_(n);case 2:return eM(n);case 3:return tM(n);default:return nM(n)}}function U_(n,t,e){e===void 0&&(e=!1);var i="";e?i+=H0(n):i+=ta(n);var r=n.shapeInfo.logicalShape,a=t.logicalShape;return r.length<=a.length&&(e?i+=iM(n,t):i+=rM(n,t)),i}function B_(n,t){switch(n.length){case 0:return V0();case 1:return aM(n,t);case 2:return lM(n,t);case 3:return sM(n,t);default:return oM(n,t)}}function z_(n,t){switch(n.length){case 0:return V0();case 1:return uM(n,t);case 2:return fM(n,t);case 3:return cM(n,t);case 4:return hM(n,t);case 5:return dM(n,t);case 6:return pM(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function P_(n){return`
2020-10-12 01:22:43 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return `+n.texture2D+`(textureSampler, uv).r;
}
2020-10-15 00:22:38 +02:00
`}function __(n){return`
2020-10-12 01:22:43 +02:00
void setOutput(float val) {
`+n.output+` = vec4(val, 0, 0, 0);
}
2020-10-15 00:22:38 +02:00
`}function M_(n){return`
2020-10-12 01:22:43 +02:00
void setOutput(vec4 val) {
`+n.output+` = val;
}
2020-10-15 00:22:38 +02:00
`}function H_(n){var t=n.version+`
2020-10-12 01:22:43 +02: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);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
2020-10-15 00:22:38 +02:00
`+mM+`
`+gM+`
`+vM+`
`;return t}var mM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,gM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,vM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,V_=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`;function V0(){return`
2020-10-12 01:22:43 +02:00
int getOutputCoords() {
return 0;
}
2020-10-15 00:22:38 +02:00
`}function aM(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`}function uM(n,t){return t[0]===1?`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`}function sM(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],i=Math.ceil(n[2]/2),r=i*Math.ceil(n[1]/2);return`
2020-10-12 01:22:43 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = resTexRC.x * `+e[1]+` + resTexRC.y;
int b = index / `+r+`;
index -= b * `+r+`;
int r = 2 * (index / `+i+`);
int c = imod(index, `+i+`) * 2;
return ivec3(b, r, c);
}
2020-10-15 15:43:16 +02:00
`}function cM(n,t){var e=cr(["r","c","d"],n);return`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`}function oM(n,t){for(var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],i=Math.ceil(n[n.length-1]/2),r=i*Math.ceil(n[n.length-2]/2),a=r,s="",o="b, r, c",l=2;l<n.length-1;l++)a*=n[n.length-l-1],s=`
2020-10-12 01:22:43 +02:00
int b`+l+" = index / "+a+`;
index -= b`+l+" * "+a+`;
`+s,o="b"+l+", "+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 / `+r+`;
index -= b * `+r+`;
int r = 2 * (index / `+i+`);
int c = imod(index, `+i+`) * 2;
return ivec`+n.length+"("+o+`);
}
2020-10-15 15:43:16 +02:00
`}function hM(n,t){var e=cr(["r","c","d","d2"],n);return`
2020-10-12 01:22:43 +02: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-10-15 15:43:16 +02:00
`}function dM(n,t){var e=cr(["r","c","d","d2","d3"],n);return`
2020-10-12 01:22:43 +02: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-15 15:43:16 +02:00
`}function pM(n,t){var e=cr(["r","c","d","d2","d3","d4"],n);return`
2020-10-12 01:22:43 +02: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-15 00:22:38 +02:00
`}function lM(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(N.util.arraysEqual(n,t))return`
2020-10-12 01:22:43 +02:00
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(`+e[0]+", "+e[1]+`));
}
`;var i=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 / `+i+`);
int c = imod(index, `+i+`) * 2;
return ivec2(r, c);
}
2020-10-15 00:22:38 +02:00
`}function fM(n,t){return N.util.arraysEqual(n,t)?`
2020-10-12 01:22:43 +02: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-10-15 15:43:16 +02:00
`}function hr(n){return"offset"+n}function Z_(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),i=Dt();return`
2020-10-12 01:22:43 +02:00
vec4 `+e+`() {
return `+i.texture2D+"("+t+`, halfCR);
}
2020-10-15 00:22:38 +02:00
`}function G_(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return"float "+e+"() {return "+t+";}";var i=n.shapeInfo.texShape,r=i[0],a=i[1];if(r===1&&a===1)return`
2020-10-12 01:22:43 +02:00
float `+e+`() {
return sampleTexture(`+t+`, halfCR);
}
2020-10-15 15:43:16 +02:00
`;var s=n.shapeInfo.texShape,o=s[0],l=s[1],u=hr(t);return`
2020-10-12 01:22:43 +02:00
float `+e+`() {
vec2 uv = uvFromFlat(`+o+", "+l+", "+u+`);
return sampleTexture(`+t+`, uv);
}
2020-10-15 00:22:38 +02:00
`}function Q_(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),i=n.shapeInfo.texShape,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],a=Dt();return`
2020-10-12 01:22:43 +02:00
vec4 `+e+`(int index) {
vec2 uv = packedUVfrom1D(
`+r[0]+", "+r[1]+`, index);
return `+a.texture2D+"("+t+`, uv);
}
2020-10-15 00:22:38 +02:00
`}function Y_(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return`
2020-10-12 01:22:43 +02:00
float `+e+`(int index) {
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
`;var i=n.shapeInfo.texShape,r=i[0],a=i[1];if(a===1&&r===1)return`
float `+e+`(int index) {
return sampleTexture(`+t+`, halfCR);
}
2020-10-15 15:43:16 +02:00
`;var s=hr(t);return a===1?`
2020-10-12 01:22:43 +02:00
float `+e+`(int index) {
vec2 uv = vec2(0.5, (float(index + `+s+") + 0.5) / "+r+`.0);
return sampleTexture(`+t+`, uv);
}
`:r===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(`+r+", "+a+", index + "+s+`);
return sampleTexture(`+t+`, uv);
}
2020-10-15 00:22:38 +02:00
`}function eM(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=n.shapeInfo.texShape,a=r[0],s=r[1],o=Dt();if(r!=null&&N.util.arraysEqual(t,r))return`
2020-10-12 01:22:43 +02:00
vec4 `+i+`(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+s+".0, "+a+`.0);
return `+o.texture2D+"("+e+`, uv);
}
`;var l=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],u=Math.ceil(t[1]/2);return`
vec4 `+i+`(int row, int col) {
vec2 uv = packedUVfrom2D(`+u+", "+l[0]+", "+l[1]+`, row, col);
return `+o.texture2D+"("+e+`, uv);
}
2020-10-15 00:22:38 +02:00
`}function K_(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=n.shapeInfo.texShape;if(r!=null&&N.util.arraysEqual(t,r)){var a=r[0],s=r[1];return`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+s+".0, "+a+`.0);
return sampleTexture(`+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`}var o=N.util.squeezeShape(t),l=o.newShape,u=o.keptDims,c=l;if(c.length<t.length){var h=ia(n,c),d=["row","col"];return`
`+ta(h)+`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(d,u)+`);
2020-10-12 01:22:43 +02:00
}
`}if(n.shapeInfo.isUniform)return`
float `+i+`(int row, int col) {
int index = round(dot(vec2(row, col), vec2(`+t[1]+`, 1)));
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
2020-10-15 15:43:16 +02:00
`;var p=r[0],f=r[1],m=hr(e);return f===1?`
2020-10-12 01:22:43 +02:00
float `+i+`(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 `+i+`(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 `+i+`(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-10-15 15:43:16 +02:00
`}function tM(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=n.shapeInfo.texShape,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];if(t[0]===1){var s=t.slice(1),o=[1,2],l=ia(n,s),u=["b","row","col"];return`
2020-10-15 00:22:38 +02:00
`+H0(l)+`
2020-10-12 01:22:43 +02:00
vec4 `+i+`(int b, int row, int col) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(u,o)+`);
2020-10-12 01:22:43 +02:00
}
2020-10-13 04:01:35 +02:00
`}var c=a[0],h=a[1],d=Math.ceil(t[2]/2),p=d*Math.ceil(t[1]/2),f=Dt();return`
2020-10-12 01:22:43 +02:00
vec4 `+i+`(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
`+c+", "+h+", "+p+", "+d+`, b, row, col);
return `+f.texture2D+"("+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`}function j_(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[1]*t[2],a=t[2],s=N.util.squeezeShape(t),o=s.newShape,l=s.keptDims,u=o;if(u.length<t.length){var c=ia(n,u),h=["row","col","depth"];return`
`+ta(c)+`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col, int depth) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(h,l)+`);
2020-10-12 01:22:43 +02:00
}
`}if(n.shapeInfo.isUniform)return`
float `+i+`(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(`+r+", "+a+`, 1)));
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
`;var d=n.shapeInfo.texShape,p=d[0],f=d[1],m=n.shapeInfo.flatOffset;if(f===r&&m==null)return`
float `+i+`(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 `+i+`(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-10-15 15:43:16 +02:00
`;var g=hr(e);return`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * `+r+" + col * "+a+" + depth + "+g+`;
vec2 uv = uvFromFlat(`+p+", "+f+`, index);
return sampleTexture(`+e+`, uv);
}
2020-10-15 00:22:38 +02:00
`}function nM(n){for(var t=n.shapeInfo.logicalShape,e=t.length,i=n.name,r="get"+i.charAt(0).toUpperCase()+i.slice(1),a=n.shapeInfo.texShape,s=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],o=s[0],l=s[1],u=Math.ceil(t[e-1]/2),c=u*Math.ceil(t[e-2]/2),h="int b, int row, int col",d="b * "+c+" + (row / 2) * "+u+" + (col / 2)",p=2;p<e-1;p++)h="int b"+p+", "+h,c*=t[e-p-1],d="b"+p+" * "+c+" + "+d;var f=Dt();return`
2020-10-12 01:22:43 +02:00
vec4 `+r+"("+h+`) {
int index = `+d+`;
int texR = index / `+l+`;
int texC = index - texR * `+l+`;
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+l+", "+o+`);
return `+f.texture2D+"("+i+`, uv);
}
2020-10-15 15:43:16 +02:00
`}function $_(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[3],a=t[2]*r,s=t[1]*a,o=N.util.squeezeShape(t),l=o.newShape,u=o.keptDims;if(l.length<t.length){var c=ia(n,l),h=["row","col","depth","depth2"];return`
`+ta(c)+`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col, int depth, int depth2) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(h,u)+`);
2020-10-12 01:22:43 +02:00
}
`}if(n.shapeInfo.isUniform)return`
float `+i+`(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(`+s+", "+a+", "+r+`, 1)));
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
`;var d=n.shapeInfo.flatOffset,p=n.shapeInfo.texShape,f=p[0],m=p[1];if(m===s&&d==null)return`
float `+i+`(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(`+a+", "+r+`, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+m+".0, "+f+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(m===r&&d==null)return`
float `+i+`(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-10-15 15:43:16 +02:00
`;var g=hr(e);return`
2020-10-12 01:22:43 +02:00
float `+i+`(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 * `+r+` + depth2;
vec2 uv = uvFromFlat(`+f+", "+m+", index + "+g+`);
return sampleTexture(`+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`}function X_(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[4],a=t[3]*r,s=t[2]*a,o=t[1]*s,l=N.util.squeezeShape(t),u=l.newShape,c=l.keptDims;if(u.length<t.length){var h=ia(n,u),d=["row","col","depth","depth2","depth3"];return`
`+ta(h)+`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col, int depth, int depth2, int depth3) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(d,c)+`);
2020-10-12 01:22:43 +02:00
}
`}if(n.shapeInfo.isUniform)return`
float `+i+`(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(`+o+", "+s+", "+a+", "+r+`)) +
depth3;
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
`;var p=n.shapeInfo.flatOffset,f=n.shapeInfo.texShape,m=f[0],g=f[1];if(g===o&&p==null)return`
float `+i+`(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(`+s+", "+a+", "+r+`, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+g+".0, "+m+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(g===r&&p==null)return`
float `+i+`(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-10-15 15:43:16 +02:00
`;var v=hr(e);return`
2020-10-12 01:22:43 +02:00
float `+i+`(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 * `+r+" + depth3 + "+v+`;
vec2 uv = uvFromFlat(`+m+", "+g+`, index);
return sampleTexture(`+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`}function J_(n){var t=n.shapeInfo.logicalShape,e=n.name,i="get"+e.charAt(0).toUpperCase()+e.slice(1),r=N.util.squeezeShape(t),a=r.newShape,s=r.keptDims;if(a.length<t.length){var o=ia(n,a),l=["row","col","depth","depth2","depth3","depth4"];return`
`+ta(o)+`
2020-10-12 01:22:43 +02:00
float `+i+`(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2020-10-15 15:43:16 +02:00
return `+i+"("+ra(l,s)+`);
2020-10-12 01:22:43 +02:00
}
`}var u=t[5],c=t[4]*u,h=t[3]*c,d=t[2]*h,p=t[1]*d;if(n.shapeInfo.isUniform)return`
float `+i+`(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+", "+c+`)) +
dot(
vec2(depth3, depth4),
vec2(`+u+`, 1)));
2020-10-15 15:43:16 +02:00
`+na(n)+`
2020-10-12 01:22:43 +02:00
}
`;var f=n.shapeInfo.flatOffset,m=n.shapeInfo.texShape,g=m[0],v=m[1];if(v===p&&f==null)return`
float `+i+`(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+", "+c+", "+u+`)) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(`+v+".0, "+g+`.0);
return sampleTexture(`+e+`, uv);
}
`;if(v===u&&f==null)return`
float `+i+`(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(`+v+".0, "+g+`.0);
return sampleTexture(`+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`;var b=hr(e);return`
2020-10-12 01:22:43 +02:00
float `+i+`(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 * `+c+" + depth3 * "+u+" + depth4 + "+b+`;
vec2 uv = uvFromFlat(`+g+", "+v+`, index);
return sampleTexture(`+e+`, uv);
}
2020-10-15 15:43:16 +02:00
`}function na(n){var t=n.name,e=N.util.sizeFromShape(n.shapeInfo.logicalShape);return e<2?"return "+t+";":`
2020-10-12 01:22:43 +02:00
for (int i = 0; i < `+e+`; i++) {
if (i == index) {
return `+t+`[i];
}
}
2020-10-15 00:22:38 +02:00
`}function iM(n,t){var e=n.name,i=e.charAt(0).toUpperCase()+e.slice(1),r="get"+i+"AtOutCoords",a=n.shapeInfo.logicalShape.length,s=t.logicalShape.length,o=M0(n.shapeInfo.logicalShape,t.logicalShape),l=Je(s),u=s-a,c,h=["x","y","z","w","u","v"];a===0?c="":s<2&&o.length>=1?c="coords = 0;":c=o.map(function(S){return"coords."+h[S+u]+" = 0;"}).join(`
2020-10-12 01:22:43 +02:00
`);var d="";s<2&&a>0?d="coords":d=n.shapeInfo.logicalShape.map(function(S,L){return"coords."+h[L+u]}).join(", ");var p="return outputValue;",f=N.util.sizeFromShape(n.shapeInfo.logicalShape),m=f===1,g=N.util.sizeFromShape(t.logicalShape),v=g===1;if(a===1&&!m&&!v)p=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(m&&!v)s===1?p=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:p=`
return vec4(outputValue.x);
`;else if(o.length){var b=a-2,w=a-1;o.indexOf(b)>-1&&o.indexOf(w)>-1?p="return vec4(outputValue.x);":o.indexOf(b)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(w)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 `+r+`() {
`+l+` coords = getOutputCoords();
`+c+`
vec4 outputValue = get`+i+"("+d+`);
`+p+`
}
2020-10-15 00:22:38 +02:00
`}function rM(n,t){var e=n.name,i=e.charAt(0).toUpperCase()+e.slice(1),r="get"+i+"AtOutCoords",a=t.texShape,s=n.shapeInfo.texShape,o=n.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===l&&n.shapeInfo.flatOffset==null&&N.util.arraysEqual(s,a))return`
2020-10-12 01:22:43 +02:00
float `+r+`() {
return sampleTexture(`+e+`, resultUV);
}
2020-10-15 00:22:38 +02:00
`;var u=Je(l),c=M0(n.shapeInfo.logicalShape,t.logicalShape),h=l-o,d,p=["x","y","z","w","u","v"];o===0?d="":l<2&&c.length>=1?d="coords = 0;":d=c.map(function(m){return"coords."+p[m+h]+" = 0;"}).join(`
2020-10-12 01:22:43 +02:00
`);var f="";return l<2&&o>0?f="coords":f=n.shapeInfo.logicalShape.map(function(m,g){return"coords."+p[g+h]}).join(", "),`
float `+r+`() {
`+u+` coords = getOutputCoords();
`+d+`
return get`+i+"("+f+`);
}
2020-10-15 15:43:16 +02:00
`}function Je(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 ia(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function ra(n,t){return t.map(function(e){return n[e]}).join(", ")}var yM=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,N.util.assert(t.length>2,function(){return"Packed arg"+(i.charAt(0).toUpperCase()+i.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),r||this.variableNames.push("bestIndicesA");var o=this.outputShape,l=o.length,u=Je(l),c=$t("coords",l),h,d;if(s===1){d=l+1;var p=Je(d);h=`
2020-10-12 01:22:43 +02:00
`+p+" sourceLocR = "+p+"("+c.join()+`, 0);
++`+c[l-1]+`;
`+p+" sourceLocG = "+p+"("+c.join()+`, 0);
++`+c[l-2]+`;
`+p+" sourceLocA = "+p+"("+c.join()+`, 0);
--`+c[l-1]+`;
`+p+" sourceLocB = "+p+"("+c.join()+`, 0);
--`+c[l-2]+";"}else d=l,h=`
`+u+` sourceLocR = coords;
++`+c[l-1]+`;
`+u+` sourceLocG = coords;
++`+c[l-2]+`;
`+u+` sourceLocA = coords;
--`+c[l-1]+`;
`+u+` sourceLocB = coords;
2020-10-15 15:43:16 +02:00
--`+c[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,d),m="."+f[d-1],g=f.map(function(D){return"int "+D}),v=$t("sourceLocR",d-1).concat("inIdx.r"),b=$t("sourceLocG",d-1).concat("inIdx.g"),w=$t("sourceLocB",d-1).concat("inIdx.b"),S=$t("sourceLocA",d-1).concat("inIdx.a"),L=i==="max"?"greaterThan":"lessThan",x=r?"":`
2020-10-12 01:22:43 +02:00
inIdx = round(vec4(getBestIndicesAChannel(`+v.join()+`),
getBestIndicesAChannel(`+b.join()+`),
getBestIndicesAChannel(`+w.join()+`),
getBestIndicesAChannel(`+S.join()+")));",C=`vec4(
getAChannel(`+v.join()+`),
hasNextCol ? getAChannel(`+b.join()+`) : 0.,
hasNextRow ? getAChannel(`+w.join()+`) : 0.,
hasNextRow && hasNextCol ? getAChannel(`+S.join()+") : 0.)",R=r?"":`
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()+`));
}
`+R+`
void main() {
`+u+` coords = getOutputCoords();
bool hasNextCol = `+c[l-1]+" < "+(o[l-1]-1)+`;
bool hasNextRow = `+c[l-2]+" < "+(o[l-2]-1)+`;
`+h+`
ivec4 srcIdx = ivec4(sourceLocR`+m+", sourceLocG"+m+`,
sourceLocB`+m+", sourceLocA"+m+") * "+e+`;
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = `+C+`;
for (int i = 0; i < `+e+`; i++) {
inIdx = srcIdx;
`+x+`
vec4 candidate = `+C+`;
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-10-15 00:22:38 +02:00
`}return n}();var bM=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,i=t.filterWidth,r=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=l-1-t.padInfo.top,h=u-1-t.padInfo.left,d=1/(e*i);this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec2 pads = ivec2(`+c+", "+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 < `+l+`;
wR += `+s+`) {
float dyR = float(dyRCorner + wR) / `+r+`.0;
if (dyR < 0.0 || dyR >= `+t.outHeight+`.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < `+u+`;
wC+= `+o+`) {
float dyC = float(dyCCorner + wC) / `+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;
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),wM=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,i=t.filterHeight,r=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,l=t.dilationDepth,u=t.dilationHeight,c=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,v=1/(e*i*r);this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec3 pads = ivec3(`+f+", "+m+", "+g+`);
const float avgMultiplier = float(`+v+`);
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 += `+l+`) {
float dyD = float(dyDCorner + wD) / `+a+`.0;
if (dyD < 0.0 || dyD >= `+t.outDepth+`.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < `+d+`;
wR += `+u+`) {
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 += `+c+`) {
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-10-15 00:22:38 +02:00
`}return n}();var q0={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},G0=function(){function n(t,e,i){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.backend_util.assertAndGetBroadcastShape(e,i),this.userCode=`
2020-10-12 01:22:43 +02:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
`+t+`
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2020-10-15 00:22:38 +02:00
`}return n}();var Y0=`
2020-10-12 01:22:43 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-15 15:43:16 +02:00
`,Fd="return a + b;",Wd="return a - b;",K0="return a * b;",SM=`
2020-10-12 01:22:43 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
2020-10-15 00:22:38 +02:00
`,LM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,IM="return float(a == b);",AM="return float(a != b);",TM="return float(a < b);",NM="return float(a <= b);",xM="return float(a > b);",CM="return float(a >= b);",RM="return float(a >= 1.0 && b >= 1.0);",OM="return float(a >= 1.0 || b >= 1.0);",EM=Y0+`
2020-10-12 01:22:43 +02:00
return max(a, b);
2020-10-15 00:22:38 +02:00
`,DM=Y0+`
2020-10-12 01:22:43 +02:00
return min(a, b);
2020-10-15 00:22:38 +02:00
`,kM=`if (b == 0.0) return NAN;
return mod(a, b);`,FM="return (b >= 1.0) ? a : a * (b + 1.0);",j0="return (a < 0.) ? b * a : a;",bt=function(){function n(t,e,i){this.variableNames=["A","B"],this.outputShape=N.backend_util.assertAndGetBroadcastShape(e,i),this.userCode=`
2020-10-12 01:22:43 +02:00
float binaryOperation(float a, float b) {
`+t+`
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2020-10-15 00:22:38 +02:00
`}return n}();var zo=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,WM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,UM=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`+zo+`
2020-10-12 01:22:43 +02:00
return result;
2020-10-15 00:22:38 +02:00
`,$0=`
2020-10-12 01:22:43 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2020-10-15 00:22:38 +02:00
`,BM=`
2020-10-12 01:22:43 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2020-10-15 00:22:38 +02:00
`,zM=`
2020-10-12 01:22:43 +02:00
return vec4(equal(a, b));
2020-10-15 00:22:38 +02:00
`,PM=`
2020-10-12 01:22:43 +02:00
return vec4(notEqual(a, b));
2020-10-15 00:22:38 +02:00
`,_M=`
2020-10-12 01:22:43 +02:00
return vec4(lessThan(a, b));
2020-10-15 00:22:38 +02:00
`,MM=`
2020-10-12 01:22:43 +02:00
return vec4(lessThanEqual(a, b));
2020-10-15 00:22:38 +02:00
`,HM=`
2020-10-12 01:22:43 +02:00
return vec4(greaterThan(a, b));
2020-10-15 00:22:38 +02:00
`,VM=`
2020-10-12 01:22:43 +02:00
return vec4(greaterThanEqual(a, b));
2020-10-15 00:22:38 +02:00
`,qM=`
2020-10-12 01:22:43 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-10-15 00:22:38 +02:00
`,GM=`
2020-10-12 01:22:43 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2020-10-15 00:22:38 +02:00
`,YM=`
2020-10-12 01:22:43 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-15 00:22:38 +02:00
`+zo+`
2020-10-12 01:22:43 +02:00
return result;
2020-10-15 00:22:38 +02:00
`,KM=`
2020-10-12 01:22:43 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-15 00:22:38 +02:00
`+zo+`
2020-10-12 01:22:43 +02:00
return result;
2020-10-15 00:22:38 +02:00
`,jM=`
2020-10-12 01:22:43 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-10-15 00:22:38 +02:00
`+zo+`
2020-10-12 01:22:43 +02:00
return result;
2020-10-15 15:43:16 +02:00
`,Ii=function(){function n(t,e,i,r){r===void 0&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.backend_util.assertAndGetBroadcastShape(e,i);var a=this.outputShape.length,s="";if(r)if(a===0||N.util.sizeFromShape(this.outputShape)===1)s=`
2020-10-12 01:22:43 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{var o=Je(a);if(s=`
`+o+` coords = getOutputCoords();
`,a===1)s+=`
result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2020-10-15 15:43:16 +02:00
`;else{var l=$t("coords",a);s+=`
2020-10-12 01:22:43 +02:00
bool nextRowOutOfBounds =
(`+l[a-2]+" + 1) >= "+this.outputShape[a-2]+`;
bool nextColOutOfBounds =
(`+l[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+`
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
`+s+`
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var $M=function(){function n(t){this.variableNames=["A"],this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
2020-10-15 00:22:38 +02:00
`}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var XM=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2020-10-15 00:22:38 +02:00
`}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var JM=function(){function n(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`}return n}();var ZM=function(){function n(t){this.outputShape=[],this.outputShape=N.backend_util.computeOutShape(t,1),this.variableNames=t.map(function(l,u){return"T"+u});var e=new Array(t.length-1);e[0]=t[0][1];for(var i=1;i<e.length;i++)e[i]=e[i-1]+t[i][1];for(var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"],i=1;i<e.length;i++){var a=e[i-1];r.push("else if (yC < "+e[i]+") "+("setOutput(getT"+i+"(yR, yC-"+a+"));"))}var s=e.length,o=e[e.length-1];r.push("else setOutput(getT"+s+"(yR, yC-"+o+"));"),this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
`+r.join(`
`)+`
}
2020-10-15 15:43:16 +02:00
`}return n}();var QM=function(){function n(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.backend_util.computeOutShape(t,e);var i=this.outputShape,r=i.length,a=Je(r),s=$t("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(v,b){return"T"+b});var l=new Array(t.length-1);l[0]=t[0][e];for(var u=1;u<l.length;u++)l[u]=l[u-1]+t[u][e];for(var c=o[e],h=o.slice(-2),d=o.join(),p="if ("+c+" < "+l[0]+`) {
2020-10-12 01:22:43 +02:00
return getChannel(
getT0(`+d+"), vec2("+h.join()+`));
}`,u=1;u<l.length;u++){var f=l[u-1];p+=`
if (`+c+" < "+l[u]+" && "+c+" >= "+l[u-1]+`) {
return getChannel(
2020-10-15 00:22:38 +02:00
getT`+u+"("+Po(o,c,f)+`),
vec2(`+Po(h,c,f)+`));
2020-10-12 01:22:43 +02:00
}`}var m=l.length,g=l[l.length-1];p+=`
return getChannel(
2020-10-15 00:22:38 +02:00
getT`+m+"("+Po(o,c,g)+`),
vec2(`+Po(h,c,g)+"));",this.userCode=`
2020-10-12 01:22:43 +02:00
float getValue(`+o.map(function(v){return"int "+v})+`) {
`+p+`
}
void main() {
`+a+` coords = getOutputCoords();
vec4 result = vec4(getValue(`+s+`), 0., 0., 0.);
`+s[r-1]+" = "+s[r-1]+` + 1;
if (`+s[r-1]+" < "+i[r-1]+`) {
result.g = getValue(`+s+`);
}
`+s[r-2]+" = "+s[r-2]+` + 1;
if (`+s[r-2]+" < "+i[r-2]+`) {
result.a = getValue(`+s+`);
}
`+s[r-1]+" = "+s[r-1]+` - 1;
if (`+s[r-2]+" < "+i[r-2]+` &&
`+s[r-1]+" < "+i[r-1]+`) {
result.b = getValue(`+s+`);
}
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();function Po(n,t,e){var i=n.indexOf(t),r=n.map(function(a,s){return s===i?a+" - "+e:a});return r.join()}var e5=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,i=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,s=t.dataFormat==="channelsLast";this.userCode=`
2020-10-12 01:22:43 +02: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+" - "+r+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int yC = 0; yC < `+t.outWidth+`; yC++) {
int xC = wC + yC * `+i+" - "+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);
}
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),t5=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,i=t.filterWidth,r=t.strideHeight,a=t.strideWidth,s=t.dataFormat==="channelsLast",o=e-1-t.padInfo.top,l=i-1-t.padInfo.left,u=s?1:2,c=s?2:3,h=s?3:1;this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec2 pads = ivec2(`+o+", "+l+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[`+h+`];
ivec2 dyCorner = ivec2(coords[`+u+"], coords["+c+`]) - 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) / `+r+`.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 < `+i+`; 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 = `+i+` - 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;
}
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),n5=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,i=t.strideHeight,r=t.strideWidth,a=t.padInfo.front,s=t.padInfo.top,o=t.padInfo.left;this.userCode=`
2020-10-12 01:22:43 +02: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 * `+i+" - "+s+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int yC = 0; yC < `+t.outWidth+`; yC++) {
int xC = wC + yC * `+r+" - "+o+`;
if (xC < 0 || xC >= `+t.inWidth+`) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),i5=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,i=t.filterHeight,r=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,l=e-1-t.padInfo.front,u=i-1-t.padInfo.top,c=r-1-t.padInfo.left;this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec3 pads = ivec3(`+l+", "+u+", "+c+`);
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < `+e+`; wF++) {
float dyF = float(dyFCorner + wF) / `+a+`.0;
if (dyF < 0.0 || dyF >= `+t.outDepth+`.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = `+e+` - 1 - wF;
for (int wR = 0; wR < `+i+`; 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 = `+i+` - 1 - wR;
for (int wC = 0; wC < `+r+`; 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 = `+r+` - 1 - wC;
for (int d2 = 0; d2 < `+t.outChannels+`; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}();var r5=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,i=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode=`
2020-10-12 01:22:43 +02: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+" - "+r+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int yC = 0; yC < `+t.outWidth+`; yC++) {
int xC = wC + yC * `+i+" - "+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);
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),a5=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,i=t.filterWidth,r=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.top,o=i-1-t.padInfo.left,l=t.outChannels/t.inChannels;this.userCode=`
2020-10-12 01:22:43 +02: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) / `+r+`.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 < `+i+`; 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 = `+i+` - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < `+l+`; dm++) {
int d2 = d1 * `+l+` + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}();var X0=function(){function n(t,e,i,r){e===void 0&&(e=!1),i===void 0&&(i=null),r===void 0&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,s=t.padInfo.left,o=t.strideHeight,l=t.strideWidth,u=t.dilationHeight,c=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,v=m?2:3,b=m?3:1,w="",S="";i&&(r?w=`float activation(float a) {
2020-10-12 01:22:43 +02:00
float b = getPreluActivationWeightsAtOutCoords();
`+i+`
}`:w=`
float activation(float x) {
`+i+`
}
`,S="result = activation(result);");var L=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+w+`
const ivec2 strides = ivec2(`+o+", "+l+`);
const ivec2 pads = ivec2(`+a+", "+s+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[`+b+`];
ivec2 xRCCorner =
ivec2(coords[`+g+"], coords["+v+`]) * 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 * `+u+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+d+`; wC++) {
int xC = xCCorner + wC * `+c+`;
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);
}
}
}
}
float result = dotProd;
`+L+`
`+S+`
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}(),s5=function(){function n(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,i=t.padInfo.top,r=t.padInfo.left,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,l=t.dilationDepth,u=t.dilationHeight,c=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-10-12 01:22:43 +02:00
const ivec3 strides = ivec3(`+a+", "+s+", "+o+`);
const ivec3 pads = ivec3(`+e+", "+i+", "+r+`);
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 * `+l+`;
if (xF < 0 || xF >= `+t.inDepth+`) {
continue;
}
for (int wR = 0; wR < `+d+`; wR++) {
int xR = xRCorner + wR * `+u+`;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+p+`; wC++) {
int xC = xCCorner + wC * `+c+`;
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-10-15 00:22:38 +02:00
`}return n}();var J0=function(){function n(t,e,i,r){e===void 0&&(e=!1),i===void 0&&(i=null),r===void 0&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.inHeight,s=t.inWidth,o=t.padInfo.top,l=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,h=t.dilationHeight,d=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,m=t.outChannels/t.inChannels,g="",v="";i&&(r?g=`float activation(float a) {
2020-10-12 01:22:43 +02:00
float b = getPreluActivationWeightsAtOutCoords();
`+i+`
}`:g=`
float activation(float x) {
`+i+`
}
`,v="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+g+`
const ivec2 strides = ivec2(`+u+", "+c+`);
const ivec2 pads = ivec2(`+o+", "+l+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / `+m+`;
int q = d2 - d1 * `+m+`;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < `+p+`; wR++) {
int xR = xRCorner + wR * `+h+`;
if (xR < 0 || xR >= `+a+`) {
continue;
}
for (int wC = 0; wC < `+f+`; wC++) {
int xC = xCCorner + wC * `+d+`;
if (xC < 0 || xC >= `+s+`) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
`+b+`
`+v+`
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var Z0=function(){function n(t,e,i,r){e===void 0&&(e=!1),i===void 0&&(i=null),r===void 0&&(r=!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,l=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,h=t.dilationHeight,d=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,m=f,g="int xR; int xC; int xCOffset;",v=0;v<p;v++)for(var b=0;b<f;b++)g+=`
2020-10-12 01:22:43 +02:00
vec4 xTexelR`+v+"C"+b*2+` = vec4(0.);
vec4 wR`+v+"C"+b+` = vec4(0.);
vec4 xR`+v+"C"+b+" = vec4(0.);";for(var v=0;v<p;v++)for(var w=0;w<m;w++){var b=w*2;if(g+=`
xR = xRCorner + `+v*h+`;
xC = xCCorner + `+b*d+`;
`,c===1){if(b<f&&(l%2===1?g+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < `+a+" && xCOffset >= 0 && xCOffset < "+s+`) {
xTexelR`+v+"C"+b+` = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= `+s+`) {
xTexelR`+v+"C"+b+`.zw = vec2(0.);
}
} else {
xTexelR`+v+"C"+b+` = 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`+v+"C"+b+" = vec4(previous.zw, xTexelR"+v+"C"+b+`.xy);
} else {
xR`+v+"C"+b+" = vec4(0, 0, xTexelR"+v+"C"+b+`.xy);
}
`:g+=`
if(xR >= 0 && xR < `+a+" && xC >= 0 && xC < "+s+`) {
xTexelR`+v+"C"+b+` = getX(batch, xR, xC, d1);
} else {
xTexelR`+v+"C"+b+` = vec4(0.);
}
xR`+v+"C"+b+" = xTexelR"+v+"C"+b+`;
`,b+1<f)){var S=l%2===0?N.util.nearestLargerEven(d):d;d%2===0&&l%2===1||d%2!==0&&l%2!==1?(g+=`
xCOffset = xC + `+l%2+" + "+S+`;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+v+"C"+(b+2)+` = getX(batch, xR, xCOffset, d1);
}
`,d>1&&(g+=`
xCOffset -= 2;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+v+"C"+b+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+v+"C"+b+` = vec4(0.);
}
`),g+=`
xR`+v+"C"+(b+1)+` = vec4(
xTexelR`+v+"C"+b+".zw, xTexelR"+v+"C"+(b+2)+`.xy);
`):g+=`
xCOffset = xC + `+S+`;
if(xR >= 0 && xR < `+a+` &&
xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+v+"C"+(b+2)+` = getX(batch, xR, xCOffset, d1);
}
xR`+v+"C"+(b+1)+" = xTexelR"+v+"C"+(b+2)+`;
`}}else b<f&&(g+=`
if(xR >= 0 && xR < `+a+`) {
`,l%2===1?(g+=`
xCOffset = xC + 1 - `+c+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+v+"C"+b+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+v+"C"+b+` = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < `+s+`) {
xTexelR`+v+"C"+(b+2)+` = getX(batch, xR, xC + 1, d1);
} else {
xTexelR`+v+"C"+(b+2)+` = vec4(0.);
}
xR`+v+"C"+b+` = vec4(
xTexelR`+v+"C"+b+".zw, xTexelR"+v+"C"+(b+2)+`.zw);
`,b+1<f&&(g+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + `+c+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
final = getX(batch, xR, xCOffset, d1);
}
xR`+v+"C"+(b+1)+" = vec4(xTexelR"+v+"C"+(b+2)+`.xy, final.xy);
`)):(g+=`
if(xC >= 0 && xC < `+s+`) {
xTexelR`+v+"C"+b+` = getX(batch, xR, xC, d1);
} else {
xTexelR`+v+"C"+b+` = vec4(0.);
}
xCOffset = xC + `+c+`;
if(xCOffset >= 0 && xCOffset < `+s+`) {
xTexelR`+v+"C"+(b+2)+` = getX(batch, xR, xCOffset, d1);
} else {
xTexelR`+v+"C"+(b+2)+` = vec4(0.);
}
xR`+v+"C"+b+` = vec4(
xTexelR`+v+"C"+b+".xy, xTexelR"+v+"C"+(b+2)+`.xy);
`,b+1<f&&(g+=`
xR`+v+"C"+(b+1)+` = vec4(
xTexelR`+v+"C"+b+".zw, xTexelR"+v+"C"+(b+2)+`.zw);
`)),g+="}");b<f&&(g+=`
vec4 wTexelR`+v+"C"+b+" = getW("+v+", "+b+`, d1, q);
wR`+v+"C"+b+" = vec4(wTexelR"+v+"C"+b+".xz, wTexelR"+v+"C"+b+`.xz);
`,b+1<f&&(g+=`
vec4 wTexelR`+v+"C"+(b+1)+" = getW("+v+", "+(b+1)+`, d1, q);
wR`+v+"C"+(b+1)+` =
vec4(wTexelR`+v+"C"+(b+1)+".xz, wTexelR"+v+"C"+(b+1)+".xz);"))}for(var v=0;v<p;v++)for(var b=0;b<f;b++)g+="dotProd += xR"+v+"C"+b+" * wR"+v+"C"+b+";";var L="",x="";i&&(r?L=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
`+i+`
}`:L=`vec4 activation(vec4 x) {
`+i+`
}`,x="result = activation(result);");var C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+L+`
const ivec2 strides = ivec2(`+u+", "+c+`);
const ivec2 pads = ivec2(`+o+", "+l+`);
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;
`+C+`
`+x+`
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var o5=function(){function n(t,e,i,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var s=t[0],o=t[1],l=t[2],u=t[3],c=e[0],h=i[0],d=i[1];this.outputShape=[c,h,d,u];var p=r==="bilinear"?1:0,f=[o-1+".0",l-1+".0"],m=f[0],g=f[1],v=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],b=v[0],w=v[1],S=v[2],L=d>1?[""+(l-1)/(d-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],x=L[0],C=L[1],R=L[2];this.userCode=`
2020-10-12 01:22:43 +02:00
const float height_ratio = float(`+b+`);
const float width_ratio = float(`+x+`);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= `+s+`) {
return;
}
float height_scale = `+w+`;
float width_scale = `+C+`;
float in_y = `+S+`;
if( in_y < 0.0 || in_y > `+m+` ) {
setOutput(float(`+a+`));
return;
}
float in_x = `+R+`;
if( in_x < 0.0 || in_x > `+g+` ) {
setOutput(float(`+a+`));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(`+p+` == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
2020-10-15 00:22:38 +02:00
`}return n}(),tS=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=t;var r=t.length,a=e?"0.0":"getX("+Q0(r,"coords")+")",s=t[t.length-1],o="",l="";e?(o=i?"end != "+(s-1):"end != 0",l=i?"end + 1":"end - 1"):(o=i?"end + pow2 < "+s:"end >= pow2",l=i?"end + pow2":"end - pow2"),this.userCode=`
2020-10-12 01:22:43 +02:00
uniform float index;
void main() {
`+Je(r)+` coords = getOutputCoords();
2020-10-15 00:22:38 +02:00
int end = `+eS(r,"coords")+`;
2020-10-12 01:22:43 +02:00
float val = `+a+`;
int pow2 = int(pow(2.0, index));
if (`+o+`) {
int idx = `+l+`;
2020-10-15 00:22:38 +02:00
`+eS(r,"coords")+` = idx;
val += getX(`+Q0(r,"coords")+`);
2020-10-12 01:22:43 +02:00
}
setOutput(val);
}
2020-10-15 00:22:38 +02:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.index==null&&(e.index=i.getUniformLocation(r,"index")),i.gl.uniform1f(e.index,t)}},n}();function Q0(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 eS(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 l5=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Xa.DENSE;var e=Za(t),i=Dt();this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-15 15:43:16 +02:00
`+cr(["r","c","d"],t)+`
2020-10-12 01:22:43 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = 4 * (resTexRC.x * `+e[1]+` + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
`+i.output+` = result;
}
2020-10-15 00:22:38 +02:00
`}return n}();var u5=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Xa.DENSE;var e=Za(t),i=Dt();this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-15 15:43:16 +02:00
`+cr(["r","c","d"],t)+`
2020-10-12 01:22:43 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(`+e[0]+", "+e[1]+`));
int index = 4 * (resTexRC.x * `+e[1]+` + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
`+i.output+` = result;
}
2020-10-15 00:22:38 +02:00
`}return n}();var c5=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=i,this.userCode=`
2020-10-12 01:22:43 +02: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-15 00:22:38 +02: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 h5=function(){function n(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2020-10-15 00:22:38 +02:00
`}return n}();var d5=function(){function n(t){this.variableNames=["A"],this.outTexUsage=tn.DOWNLOAD;var e=Dt();this.outputShape=t,this.userCode=`
`+_0+`
2020-10-12 01:22:43 +02:00
void main() {
float x = getAAtOutCoords();
`+e.output+` = encode_float(x);
}
2020-10-15 00:22:38 +02:00
`}return n}();var p5=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=tn.DOWNLOAD;var e=Dt();this.outputShape=t,this.userCode=`
`+_0+`
2020-10-12 01:22:43 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
`+e.output+` = encode_float(x);
}
2020-10-15 00:22:38 +02:00
`}return n}();var f5=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"];var r=Dt(),a=e[0],s=e[1];this.outputShape=t;var o="result";i&&(o="floor(result * 255. + 0.5)"),this.userCode=`
2020-10-15 15:43:16 +02:00
`+kd(t)+`
2020-10-12 01:22:43 +02: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 = `+r.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];
}
`+r.output+" = vec4("+o+`, 0., 0., 0.);
}
2020-10-15 00:22:38 +02:00
`}return n}();var m5=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=Dt(),a=e[0],s=e[1];this.outputShape=t;var o="",l="result";i&&(l="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var h=u*2+c;o+=`
2020-10-12 01:22:43 +02:00
localCoords = coords;
if(localCoords[2] + `+c+" < "+t[2]+`) {
localCoords[2] += `+c+`;
if(localCoords[1] + `+u+" < "+t[1]+`) {
localCoords[1] += `+u+`;
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 = `+r.texture2D+`(A, uv);
if(offset == 0) {
result[`+h+`] = values[0];
} else if(offset == 1) {
result[`+h+`] = values[1];
} else if(offset == 2) {
result[`+h+`] = values[2];
} else {
result[`+h+`] = values[3];
}
}
}
`}this.userCode=`
2020-10-15 15:43:16 +02:00
`+kd(t)+`
2020-10-12 01:22:43 +02:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
`+o+`
`+r.output+" = "+l+`;
}
2020-10-15 00:22:38 +02:00
`}return n}();var nS={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"},iS=function(){function n(t,e,i){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var a=i?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,s=i?r+".0":"1.0";this.userCode=`
2020-10-12 01:22:43 +02:00
const float exponentMultiplier = `+a+`;
float unaryOpComplex(float real, float expR, float imag, float expI) {
`+t+`
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(`+r+`);
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < `+r+`; 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+`;
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
2020-10-15 00:22:38 +02:00
`}return n}();var g5=function(){function n(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
2020-10-15 00:22:38 +02:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.valueLoc==null&&(e.valueLoc=i.getUniformLocationNoThrow(r,"value")),i.gl.uniform1f(e.valueLoc,t)}},n}();var y5=function(){function n(t,e,i){this.variableNames=["A","indices"];var r=t.slice();r[i]=e,this.outputShape=r,this.rank=r.length;var a=Je(this.rank),s=v5(t,i);this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
}
2020-10-15 00:22:38 +02:00
`}return n}();function v5(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 i=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=0;a<n.length;a++)a===t?r.push("int(getIndices("+i[a]+"))"):r.push(""+i[a]);return r.join()}var b5=function(){function n(t,e,i){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=i;var r=Je(e.length),a=Je(i.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2020-10-12 01:22:43 +02:00
`+r+" strides = "+r+"("+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-10-15 00:22:38 +02:00
`}return n}();function rS(n){var t=Dt(),e=t.version+`
2020-10-12 01:22:43 +02: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-10-15 15:43:16 +02:00
}`;return g0(n,e)}function aS(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 w0(n,t)}function sS(n){var t=new Uint16Array([0,1,2,2,1,3]);return S0(n,t)}function ns(n,t,e,i,r,a){I0(t,e);var s=L0(n),o=n.TEXTURE_2D;return ce(n,function(){return n.bindTexture(o,s)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)}),ce(n,function(){return n.texImage2D(o,0,i,t,e,0,r,a,null)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)}),s}function Ud(n){return n.internalFormatFloat}function oS(n,t,e,i){var r=Ja(t,e),a=r[0],s=r[1];return ns(n,a,s,Ud(i),i.textureFormatFloat,n.FLOAT)}function Bd(n){return n.internalFormatHalfFloat}function lS(n,t,e,i){var r=Ja(t,e),a=r[0],s=r[1];return ns(n,a,s,Bd(i),i.textureFormatFloat,i.textureTypeHalfFloat)}function zd(n){return n.downloadTextureFormat}function uS(n,t,e,i){var r=Ja(t,e),a=r[0],s=r[1];return ns(n,a,s,zd(i),n.RGBA,n.UNSIGNED_BYTE)}function Pd(n){return n.internalFormatPackedFloat}function cS(n,t,e,i){var r=Zr(t,e),a=r[0],s=r[1];return ns(n,a,s,Pd(i),n.RGBA,n.FLOAT)}function _d(n){return n.internalFormatPackedHalfFloat}function hS(n,t,e,i){var r=Zr(t,e),a=r[0],s=r[1];return ns(n,a,s,_d(i),n.RGBA,i.textureTypeHalfFloat)}function dS(n,t,e){var i=0,r=3*4,a=3*4+2*4;ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)});var s=Cd(n,t,"clipSpacePos",e,3,a,i);return s&&Cd(n,t,"uv",e,2,a,r)}function pS(n,t,e,i,r,a){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)});var s,o,l;r instanceof Uint8Array?(s=new Uint8Array(e*i*4),o=n.UNSIGNED_BYTE,l=n.RGBA):(s=new Float32Array(e*i*4),o=n.FLOAT,l=a.internalFormatPackedFloat),s.set(r),ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,l,e,i,0,n.RGBA,o,s)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function fS(n,t,e){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)}),e.data instanceof Uint8Array?ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)}):ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function mS(n,t,e,i){var r=n.createBuffer();ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,r)});var a=4,s=4,o=a*s*t*e;return ce(n,function(){return n.bufferData(n.PIXEL_PACK_BUFFER,o,n.STREAM_READ)}),ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)}),ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}),r}function gS(n,t,e){var i=n,r=new Float32Array(e);return i.bindBuffer(i.PIXEL_PACK_BUFFER,t),i.getBufferSubData(i.PIXEL_PACK_BUFFER,0,r),i.bindBuffer(i.PIXEL_PACK_BUFFER,null),r}function vS(n,t,e,i){var r=Ja(t,e),a=r[0],s=r[1],o=4,l=new Uint8Array(GP(t*e,o));return ce(n,function(){return n.readPixels(0,0,a,s,i.downloadTextureFormat,n.UNSIGNED_BYTE,l)}),new Float32Array(l.buffer)}function yS(n,t,e,i,r,a,s,o){var l=n,u=new Float32Array(YP(a,s));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function bS(n,t,e){var i=new Float32Array(t*e*4);return ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,i)}),i}var w5={__proto__:null,createVertexShader:rS,createVertexBuffer:aS,createIndexBuffer:sS,getInternalFormatForFloat32MatrixTexture:Ud,createFloat32MatrixTexture:oS,getInternalFormatForFloat16MatrixTexture:Bd,createFloat16MatrixTexture:lS,getInternalFormatForUnsignedBytesMatrixTexture:zd,createUnsignedBytesMatrixTexture:uS,getInternalFormatForPackedMatrixTexture:Pd,createPackedMatrixTexture:cS,getInternalFormatForFloat16PackedMatrixTexture:_d,createFloat16PackedMatrixTexture:hS,bindVertexProgramAttributeStreams:dS,uploadDenseMatrixToTexture:pS,uploadPixelDataToTexture:fS,createBufferFromOutputTexture:mS,downloadFloat32MatrixFromBuffer:gS,downloadByteEncodedFloatMatrixFromOutputTexture:vS,
2020-10-12 01:22:43 +02:00
blockIndex = rc.y + `+x+`;
pos = rc.x + `+L+`;
if(blockIndex < `+t[1]+" && pos < "+t[0]+`) {
offsetY = int(blockIndex / (`+u+")) * "+o+" - "+f+`;
d0 = offsetY + `+h+" * (pos / "+m+`);
if(d0 < `+e[b]+` && d0 >= 0) {
offsetX = int(mod(float(blockIndex), `+u+".) * "+s+". - "+p+`.);
d1 = offsetX + `+c+" * (int(mod(float(pos), "+m+".) / "+a+`.));
if(d1 < `+e[w]+` && d1 >= 0) {
ch = int(mod(float(pos), `+a+`.));
if (`+v+`) {
innerDims = vec2(d1, ch);
result[`+(L*2+x)+`] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[`+(L*2+x)+`] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
`+S+`
`+g.output+` = result;
}
2020-10-15 00:22:38 +02:00
`}return n}();var N5=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[];var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=`
2020-10-12 01:22:43 +02: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 * `+l+`;
setOutput(val);
}
2020-10-15 00:22:38 +02:00
`}return n}();var x5=function(){function n(t,e,i,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=i,this.alpha=r,this.beta=a,this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < `+this.depth+`; ++d) {
int depthBegin = int(max(0.0, float(d - `+e+`)));
int depthEnd = int(min(float(`+this.depth+`),
float(d + `+e+` + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = `+this.depth+`;
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(`+r+") * norm + float("+i+`);
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(`+r+`)
* float(`+a+`)
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * `+a+`);
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var C5=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=`
2020-10-12 01:22:43 +02: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));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - `+s+"; j <= "+s+`; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+o+`));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * `+l+`;
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var R5=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,i=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,s=t.effectiveFilterWidth,o=a-1-t.padInfo.top,l=s-1-t.padInfo.left,u=a*s-1;this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec2 pads = ivec2(`+o+", "+l+`);
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 += `+r+`) {
float dyR = float(dyRCorner + wR) / `+e+`.0;
if (dyR < 0.0 || dyR >= `+t.outHeight+`.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < `+s+`; wC++) {
float dyC = float(dyCCorner + wC) / `+i+`.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);
int maxPosValue = `+u+` - 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;
}
}
setOutput(dotProd);
}
2020-10-15 00:22:38 +02:00
`}return n}(),O5=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,i=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,h=l-1-t.padInfo.front,d=u-1-t.padInfo.top,p=c-1-t.padInfo.left,f=l*u*c-1;this.userCode=`
2020-10-12 01:22:43 +02: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 < `+l+`;
wD += `+a+`) {
float dyD = float(dyDCorner + wD) / `+e+`.0;
if (dyD < 0.0 || dyD >= `+t.outDepth+`.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < `+u+`;
wR += `+s+`) {
float dyR = float(dyRCorner + wR) / `+i+`.0;
if (dyR < 0.0 || dyR >= `+t.outHeight+`.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < `+c+`;
wC += `+o+`) {
float dyC = float(dyCCorner + wC) / `+r+`.0;
if (dyC < 0.0 || dyC >= `+t.outWidth+`.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = `+f+` -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * `+u+" * "+c+` +
wR * `+c+` + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
2020-10-15 15:43:16 +02:00
`}return n}();var Md=function(){function n(t,e,i,r,a,s,o){i===void 0&&(i=!1),r===void 0&&(r=!1),a===void 0&&(a=!1),s===void 0&&(s=null),o===void 0&&(o=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var l=i?t[1]:t[2],u=Math.ceil(l/2),c=i?"i * 2, rc.y":"rc.y, i * 2",h=r?"rc.z, i * 2":"i * 2, rc.z",d=i?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",m="";s&&(o?f=`vec4 activation(vec4 a) {
2020-10-12 01:22:43 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
`+s+`
}`:f=`vec4 activation(vec4 x) {
`+s+`
}`,m="result = activation(result);");var g=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode=`
`+f+`
const float sharedDimension = `+u+`.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < `+u+`; i++) {
vec4 a = getMatrixA(rc.x, `+c+`);
vec4 b = getMatrixB(rc.x, `+h+`);
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (`+d[0]+" * "+p[0]+`);
result += (`+d[1]+" * "+p[1]+`);
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
`+g+`
`+m+`
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`}return n}();var E5=function(){function n(t,e,i){this.variableNames=["probs"],this.outputShape=[t,i],this.userCode=`
2020-10-12 01:22:43 +02: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;
}
}
// If no other event happened, last event happened.
setOutput(float(`+(e-1)+`));
}
2020-10-15 00:22:38 +02:00
`}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.seedLoc==null&&(e.seedLoc=i.getUniformLocation(r,"seed")),i.gl.uniform1f(e.seedLoc,t)}},n}();var D5=function(){function n(t,e,i,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(`+r+"), float("+i+`),
float(index == coords.y)));
}
2020-10-15 00:22:38 +02:00
`}return n}();var U5=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-10-12 01:22:43 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-10-15 15:43:16 +02:00
`;else{var i=$t("rc",e),r=Je(e),a=k5(e,t,i),s=F5(e,t[t.length-1],t[t.length-2],i),o=W5(t,i);this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+r+` rc = getOutputCoords();
if(`+a+`) {
setOutput(vec4(0));
} else {
`+s+`
setOutput(vec4(`+o+`));
}
}
2020-10-15 00:22:38 +02:00
`}}return n}();function B5(n,t){for(var e=[],i=0;i<=1;i++)for(var r=0;r<=1;r++){for(var a=(i===0?"r":"rp1")+", "+(r===0?"c":"cp1"),s=2;s<n;s++)a=t[t.length-1-s]+","+a;e.push(a)}return e}function k5(n,t,e){if(n===1)return"rc > "+t[0];for(var i="",r=n-2;r<n;r++)i+=e[r]+" >= "+t[r],r<n-1&&(i+="||");return i}function F5(n,t,e,i){if(n===1)return"";var r=i.slice(-2);return`
2020-10-12 01:22:43 +02:00
int r = `+r[0]+`;
int c = `+r[1]+`;
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= `+t+`;
bool rEdge = rp1 >= `+e+`;
2020-10-15 00:22:38 +02:00
`}function W5(n,t){var e=n.length,i=B5(e,t);return e===1?`getA(rc),
2020-10-12 01:22:43 +02:00
rc + 1 >= `+n[0]+` ? 0. : getA(rc + 1),
0, 0`:"getA("+i[0]+`),
cEdge ? 0. : getA(`+i[1]+`),
rEdge ? 0. : getA(`+i[2]+`),
2020-10-15 00:22:38 +02:00
rEdge || cEdge ? 0. : getA(`+i[3]+")"}var z5=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=e.map(function(u,c){return u[0]+t[c]+u[1]});var r=t.length,a=Je(r),s=e.map(function(u){return u[0]}).join(","),o=e.map(function(u,c){return u[0]+t[c]}).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
2020-10-12 01:22:43 +02:00
int start = `+s+`;
int end = `+o+`;
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(`+i+`));
} else {
setOutput(getX(outC - start));
}
}
`;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(`+i+`));
} else {
`+a+` coords = outC - start;
setOutput(getX(`+l+`));
}
}
2020-10-15 15:43:16 +02:00
`}return n}();var P5=function(){function n(t,e,i){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(v,b){return v[0]+t[b]+v[1]});for(var r=t.length,a=Je(r),s=e.map(function(v){return v[0]}).join(","),o=e.map(function(v,b){return v[0]+t[b]}).join(","),l=$t("rc",r),u=$t("source",r),c=l[r-1]+" < "+this.outputShape[r-1],h=r===1?"source":"vec2("+u.slice(-2).join()+")",d=[a+" rc = outputLoc;",l[r-1]+` += 1;
2020-10-12 01:22:43 +02:00
if(`+c+`) {
`,r===1?"":`}
rc = outputLoc;
`+l[r-2]+` += 1;
if(`+l[r-2]+" < "+this.outputShape[r-2]+") {",r===1?"":" "+l[r-1]+` += 1;
if(`+c+") {"],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",m=0,g=r===1?2:4;m<g;m++)f+=`
`+d[m]+`
if (`+p+`) {
result[`+m+"] = float("+i+`);
} else {
`+a+` source = rc - start;
result[`+m+"] = getChannel(getX("+u.join()+"), "+h+`);
}
`;f+=r===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-10-15 00:22:38 +02:00
`}return n}();var is=function(){function n(t,e,i,r,a){if(r===void 0&&(r=!1),a===void 0&&(a=!1),this.variableNames=["x"],e==="avg"&&i)throw new Error("Cannot compute positions for average pool.");var s=t.filterWidth,o=t.strideHeight,l=t.strideWidth,u=t.dilationHeight,c=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",v="(xR * "+t.inWidth+" + xC) * "+t.inChannels+" + d",b="0.0";if(m||(b="-1.0 / 1e-20"),i){var w=">=";this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec2 strides = ivec2(`+o+", "+l+`);
const ivec2 pads = ivec2(`+p+", "+f+`);
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < `+h+`;
wR += `+u+`) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+d+`;
wC += `+c+`) {
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 `+w+` currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = `+(r?a?g:v:"wR * "+d+" + wC")+`;
}
}
}
setOutput(float(minMaxPosition));
}
`;return}var S="max",L=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(L="avgValue / count");var x=Math.floor(s/4)*4,C=s%4,R=`
if (`+m+`) {
avgValue += dot(values, ones);
} else {
minMaxValue = `+S+`(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(`+o+", "+l+`);
const ivec2 pads = ivec2(`+p+", "+f+`);
const float initializationValue = `+b+`;
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= `+t.inWidth+`) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
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(`+b+`);
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < `+h+`;
wR += `+u+`) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= `+t.inHeight+`) {
continue;
}
for (int wC = 0; wC < `+x+`; wC += 4) {
int xC = xCCorner + wC * `+c+`;
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+c+`, d),
getValue(batch, xR, xC + 2 * `+c+`, d),
getValue(batch, xR, xC + 3 * `+c+`, d)
);
`+R+`
}
int xC = xCCorner + `+x+`;
if (`+(C===1)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
`+R+`
} else if (`+(C===2)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+c+`, d),
initializationValue,
initializationValue
);
`+R+`
} else if (`+(C===3)+`) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + `+c+`, d),
getValue(batch, xR, xC + 2 * `+c+`, d),
initializationValue
);
`+R+`
}
}
setOutput(`+L+`);
}
2020-10-15 15:43:16 +02:00
`}return n}(),Hd=function(){function n(t,e,i,r,a){if(r===void 0&&(r=!1),a===void 0&&(a=!1),this.variableNames=["x"],e==="avg"&&i)throw new Error("Cannot compute positions for average pool.");var s=t.filterWidth,o=t.strideDepth,l=t.strideHeight,u=t.strideWidth,c=t.dilationDepth,h=t.dilationHeight,d=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,g=t.padInfo.front,v=t.padInfo.top,b=t.padInfo.left;this.outputShape=t.outShape;var w=e==="avg",S="0.0";if(w||(S="-1.0 / 1e-20"),i){var L=">=";this.userCode=`
2020-10-12 01:22:43 +02:00
const ivec3 strides =
ivec3(`+o+", "+l+", "+u+`);
const ivec3 pads = ivec3(`+g+", "+v+", "+b+`);
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < `+p+`;
wD += `+c+`) {
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 = `+(r?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 x="max",C=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(C="avgValue / count");var R=Math.floor(s/4)*4,D=s%4,k=`
if (`+w+`) {
avgValue += dot(values, ones);
} else {
minMaxValue = `+x+`(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(`+o+", "+l+", "+u+`);
const ivec3 pads = ivec3(`+g+", "+v+", "+b+`);
const float initializationValue = `+S+`;
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= `+t.inWidth+`) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
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(`+S+`);
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < `+p+`;
wD += `+c+`) {
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 < `+R+`; 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)
);
`+k+`
}
int xC = xCCorner + `+R+`;
if (`+(D===1)+`) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
`+k+`
} else if (`+(D===2)+`) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + `+d+`, ch),
initializationValue,
initializationValue
);
`+k+`
} else if (`+(D===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
);
`+k+`
}
}
setOutput(`+C+`);
}
}
2020-10-15 00:22:38 +02:00
`}return n}();var LS=function(){function n(t,e){this.variableNames=["x"];var i=t.windowSize,r=t.batchSize,a=t.inSize,s=t.outSize;this.outputShape=[r,s];var o="0.0",l="";e==="prod"?o="1.0":e==="min"?(o="1.0 / 1e-20",l="min"):e==="max"&&(o="-1.0 / 1e-20",l="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="sum"?u="sumValue":e==="prod"?u="prodValue":e==="all"?u="allValue":e==="any"&&(u="anyValue");var c=Math.floor(i/4)*4,h=i%4,d=`
2020-10-12 01:22:43 +02: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 = `+l+`(values, minMaxValue);
}
`,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%i>0&&(f=`
if (inIdx < 0 || inIdx >= `+a+`) {
return initializationValue;
}
`),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);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * `+i+`;
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 < `+c+`; 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+`
}
int inIdx = inOffset + `+c+`;
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+`
}
setOutput(`+u+`);
}
2020-10-15 00:22:38 +02:00
`}return n}();var IS=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var i="",r=0;r<4;r++){var a="thisRC = rc;";r%2===1&&(a+="thisRC.z += 1;"),r>1&&(a+="thisRC.y += 1;"),i+=`
2020-10-12 01:22:43 +02:00
`+a+`
`+(r>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[`+r+`] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
`+(r>0?"}":"")+`
`}this.userCode=`
2020-10-15 00:22:38 +02:00
`+_5(e)+`
2020-10-15 15:43:16 +02:00
`+kd(t)+`
2020-10-12 01:22:43 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = `+t[1]+`;
int cols = `+t[2]+`;
`+i+`
setOutput(result);
}
2020-10-15 15:43:16 +02:00
`}return n}();function _5(n){var t=cr(["r","c","d"],n);return`
2020-10-12 01:22:43 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
`+t+`
return ivec3(r, c, d);
}
2020-10-15 00:22:38 +02:00
`}var M5=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=`
2020-10-12 01:22:43 +02: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(`+v+`);
// 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 >= `+l+`) {
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 >= `+u+`) {
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;
}
}
}
// End loop over dy
setOutput(accumulator);
}
2020-10-15 00:22:38 +02:00
`}return n}();var H5=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=`
2020-10-12 01:22:43 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
`+u[0]/c[0]+`,
`+u[1]/c[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-10-15 00:22:38 +02:00
`}return n}();var V5=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=`
2020-10-12 01:22:43 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
`+u[0]/c[0]+`,
`+u[1]/c[1]+`,
`+u[1]/c[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));
}
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 < `+(l-1)+`;
bool hasNextRow = coords.z < `+(i-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-10-15 00:22:38 +02:00
`}return n}();var q5=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=`
2020-10-12 01:22:43 +02: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(`+v+`);
// 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 >= `+l+`) {
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 >= `+u+`) {
continue;
}
float sourceFracRow =
float(`+c[0]+`) *
(float(dyR) / float(`+h[0]+`));
float sourceFracCol =
float(`+c[1]+`) *
(float(dyC) / float(`+h[1]+`));
int sourceNearestRow = int(min(
float(int(`+a+`) - 1),
`+i+` ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(`+s+`) - 1),
`+i+` ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
2020-10-15 00:22:38 +02:00
`}return n}();var G5=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i],h=r?"0.5":"0.0";this.userCode=`
2020-10-12 01:22:43 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
`+u[0]/c[0]+`,
`+u[1]/c[1]+`);
const vec2 inputShapeRC = vec2(`+s+".0, "+o+`.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + `+h+`)));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
2020-10-15 00:22:38 +02:00
`}return n}();var Y5=function(){function n(t,e){this.variableNames=["x"];var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");if(this.outputShape=t,i===1){this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(`+t[0]+` - coord - 1));
}
`;return}var r=function(o){return e.indexOf(o)!==-1&&t[o]!==1?t[o]+" - coords["+o+"] - 1":"coords["+o+"]"},a=t.map(function(o,l){return r(l)}).join(","),s=Je(i);this.userCode=`
void main() {
`+s+` coords = getOutputCoords();
setOutput(getX(`+a+`));
}
2020-10-15 15:43:16 +02:00
`}return n}();var K5=function(){function n(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");this.outputShape=t;var r=$t("rc",i),a=r[i-1]+" + 1 < "+this.outputShape[i-1],s=r[i-2]+" + 1 < "+this.outputShape[i-2],o=Je(i);i===1?this.userCode=`
2020-10-12 01:22:43 +02: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 = `+l(r.slice())+`;
if(`+a+`){
result.g = `+u(r.slice())+`;
}
if(`+s+`) {
result.b = `+c(r.slice())+`;
if(`+a+`) {
result.a = `+h(r.slice())+`;
}
}
setOutput(result);
}
2020-10-15 00:22:38 +02:00
`;function l(f){return d(f)}function u(f){return f[i-1]="("+f[i-1]+" + 1)",d(f)}function c(f){return f[i-2]="("+f[i-2]+" + 1)",d(f)}function h(f){return f[i-1]="("+f[i-1]+" + 1)",f[i-2]="("+f[i-2]+" + 1)",d(f)}function d(f){var m=t.map(function(b,w){return p(w,f)}),g=m.join(","),v=m.slice(-2).join(",");return"getChannel(getX("+g+"), vec2("+v+"))"}function p(f,m){return e.indexOf(f)!==-1&&t[f]!==1?t[f]+" - "+m[f]+" - 1":""+m[f]}}return n}();var AS=function(){function n(t,e,i,r,a,s,o){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;var l=Je(a.length),u=Je(s.length),c="";i===1?c="i":i===2&&(c="i, j");var h="getIndices("+c+")",d="";r===1?d="i":r===2&&(d="i, coords[1]");var p="getUpdates("+d+")",f=e>1?"strides[j]":"strides";this.userCode=`
2020-10-12 01:22:43 +02:00
`+l+" strides = "+l+"("+a+`);
void main() {
`+u+` 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-10-15 00:22:38 +02:00
`}return n}();var j5=function(){function n(t,e){this.variableNames=["x","segmentIds"];var i=t.windowSize,r=t.batchSize,a=t.inSize,s=t.numSegments,o=s*Math.ceil(a/i);this.outputShape=[r,o];var l="0.0",u="sumValue",c=Math.floor(i/4)*4,h=i%4,d=`
2020-10-12 01:22:43 +02:00
sumValue += dot(values, segFilter);
`,p="";a%i>0&&(p=`
if (inIdx < 0 || inIdx >= `+a+`) {
return initializationValue;
}
`);var f="";a%i>0&&(f=`
if (inIdx < 0 || inIdx >= `+a+`) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = `+l+`;
float getValue(int batch, int inIdx) {
`+p+`
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
`+f+`
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
`+s+")) * float("+i+`));
int currentSeg = int(mod(float(outIdx), float(`+s+`)));
float sumValue = 0.0;
for (int i = 0; i < `+c+`; 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+`
}
int inIdx = inOffset + `+c+`;
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(`+u+`);
}
2020-10-15 00:22:38 +02:00
`}return n}();var $5=function(){function n(t,e,i){this.variableNames=["c","a","b"],this.outputShape=e;var r,a;if(i>4)throw Error("Where for rank "+i+" is not yet supported");if(i===1)a="resRC",r="resRC";else{for(var s=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[],u=0;u<e.length;u++)l.push(""+s[u]),u<t&&o.push(""+s[u]);r=o.join(),a=l.join()}var c=Je(i);this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+c+` resRC = getOutputCoords();
float cVal = getC(`+r+`);
if (cVal >= 1.0) {
setOutput(getA(`+a+`));
} else {
setOutput(getB(`+a+`));
}
}
2020-10-15 15:43:16 +02:00
`}return n}();var J5=function(){function n(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e=Je(this.rank),i="uniform int start["+this.rank+"];",r=X5(this.rank),a,s=t.map(function(o,l){return"sourceLoc."+Vd[l]+" = start["+l+"] + coords."+Vd[l]+";"});a=`
2020-10-12 01:22:43 +02:00
`+e+` sourceLoc;
`+e+` coords = getOutputCoords();
`+s.join(`
`)+`
`,this.userCode=`
`+i+`
void main() {
`+a+`
setOutput(getSource(`+r+`));
}
2020-10-15 15:43:16 +02: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(i,r){if(e.startLoc==null&&(e.startLoc=i.getUniformLocationNoThrow(r,"start"),e.startLoc==null))return;i.gl.uniform1iv(e.startLoc,t)}},n}(),Vd=["x","y","z","w","u","v"];function X5(n){if(n===1)return"sourceLoc";if(n<=6)return Vd.slice(0,n).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+n+" is not yet supported")}var Z5=function(){function n(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Je(this.rank),i=$t("coords",this.rank),r=$t("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+r.slice(-2).join()+")",s="getChannel(getSource("+r.join()+"), "+a+")",o=`
2020-10-12 01:22:43 +02:00
result.x = `+s+`;
if (++`+i[this.rank-1]+" < "+t[this.rank-1]+`) {
++`+r[this.rank-1]+`;
result.y = `+s+`;
--`+r[this.rank-1]+`;
}
`,l=this.rank===1?"":`
--`+i[this.rank-1]+`;
if (++`+i[this.rank-2]+" < "+t[this.rank-2]+`) {
++`+r[this.rank-2]+`;
result.z = `+s+`;
if (++`+i[this.rank-1]+" < "+t[this.rank-1]+`) {
++`+r[this.rank-1]+`;
result.w = `+s+`;
}
}
`,u=this.rank<=4?`sourceLoc = coords +
`+e+"("+t.map(function(c,h){return"start["+h+"]"}).join()+");":t.map(function(c,h){return r[h]+" = "+i[h]+" + start["+h+"];"}).join(`
`);this.userCode=`
uniform int start[`+this.rank+`];
void main() {
`+e+` coords = getOutputCoords();
`+e+` sourceLoc;
`+u+`
vec4 result = vec4(0.);
`+o+`
`+l+`
setOutput(result);
}
2020-10-15 00:22:38 +02: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(i,r){if(e.startLoc==null&&(e.startLoc=i.getUniformLocationNoThrow(r,"start"),e.startLoc==null))return;i.gl.uniform1iv(e.startLoc,t)}},n}();var Q5=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=i;var r=i.length,a=Je(i.length),s=Je(i.length),o="";if(r===1)o="coords * strides + begin";else{var l=0;o=i.map(function(u,c){return l++,i.length===1?"coords * strides["+c+"] + begin["+c+"]":"coords["+(l-1)+"] * strides["+c+"] + begin["+c+"]"}).join(",")}this.userCode=`
2020-10-12 01:22:43 +02:00
`+a+" begin = "+a+"("+t+`);
`+a+" strides = "+a+"("+e+`);
void main() {
`+s+` coords = getOutputCoords();
setOutput(getX(`+o+`));
}
2020-10-15 15:43:16 +02:00
`}return n}();var e9=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,i){var r=NS(e,i),a=xS(t,r,i);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);var s=TS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,i);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 l;return r===xt.PACKED_2X2_FLOAT32?l=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):r===xt.PACKED_2X2_FLOAT16?l=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):r===xt.UNPACKED_FLOAT32?l=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):r===xt.UNPACKED_FLOAT16?l=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):r===xt.PACKED_4X1_UNSIGNED_BYTE&&(l=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(l),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),l},n.prototype.releaseTexture=function(t,e,i,r){if(this.freeTextures==null)return;var a=NS(i,r),s=xS(e,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);var o=TS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=N.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=o):(this.freeTextures[s].push(t),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;var u=this.usedTextures[s],c=u.indexOf(t);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,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(i){t.gpgpu.deleteMatrixTexture(i)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(r){t.gpgpu.deleteMatrixTexture(r)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0},n}();function t9(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 TS(n,t,e,i,r){var a=n9(t,i),s;if(r){var o=Zr(n[0],n[1]),l=o[0],u=o[1];s=l*u}else{var c=Ja(n[0],n[1]),h=c[0],d=c[1];s=h*d}var p=t9(e,a);return s*p}function n9(n,t){switch(n){case xt.PACKED_2X2_FLOAT32:return Pd(t);case xt.PACKED_2X2_FLOAT16:return _d(t);case xt.UNPACKED_FLOAT32:return Ud(t);case xt.UNPACKED_FLOAT16:return Bd(t);case xt.PACKED_4X1_UNSIGNED_BYTE:return zd(t);default:throw new Error("Unknown physical texture type "+n)}}function i9(n){return N.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?xt.PACKED_2X2_FLOAT32:xt.UNPACKED_FLOAT32:n?xt.PACKED_2X2_FLOAT16:xt.UNPACKED_FLOAT16}function NS(n,t){if(n===tn.UPLOAD)return xt.PACKED_2X2_FLOAT32;if(n===tn.RENDER||n==null)return i9(t);if(n===tn.DOWNLOAD||n===tn.PIXELS)return xt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function xS(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var a9=function(){function n(t,e){this.variableNames=["A"];for
2020-10-12 01:22:43 +02:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
}
2020-10-15 00:22:38 +02:00
`}return n}();function r9(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"],i=[],r=0;r<n.length;r++)i.push("imod("+e[r]+", "+n[r]+")");return i.join()}var Re=function(){function n(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
float unaryOperation(float x) {
`+e+`
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
2020-10-15 15:43:16 +02:00
`}return n}(),Zn="if (isnan(x)) return x;",s9="return x;",CS="return abs(x);",RS=Zn+`
2020-10-12 01:22:43 +02:00
return (x < 0.0) ? 0.0 : x;
2020-10-15 15:43:16 +02:00
`,OS=Zn+`
2020-10-12 01:22:43 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-10-15 00:22:38 +02:00
`,ES="return (x >= 0.0) ? x : (exp(x) - 1.0);",o9=`
2020-10-12 01:22:43 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = `+N.backend_util.SELU_SCALEALPHA+`;
float scale = `+N.backend_util.SELU_SCALE+`;
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-10-15 15:43:16 +02:00
`;function l9(n){return n===void 0&&(n=0),Zn+(`
2020-10-12 01:22:43 +02:00
return x > 0.0 ? 1.0 : float(`+n+`);
2020-10-15 00:22:38 +02:00
`)}var DS="return -x;",kS="return ceil(x);",FS="return floor(x);",u9=`
2020-10-12 01:22:43 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-10-15 00:22:38 +02:00
`,c9="return float(isnan(x));",h9="return float(isinf(x));",d9="return float(!isnan(x) && !isinf(x));",p9=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,WS="return exp(x);",US="return exp(x) - 1.0;",f9=`if (x < 0.0) return NAN;
return log(x);`,m9="return log(1.0 + x);",g9="return sqrt(x);",v9="return inversesqrt(x);",y9="return 1.0 / (1.0 + exp(-1.0 * x));",b9=`
2020-10-12 01:22:43 +02:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-10-15 15:43:16 +02:00
`,w9=Zn+`
2020-10-12 01:22:43 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-10-15 15:43:16 +02:00
`,S9=Zn+`
2020-10-12 01:22:43 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-10-15 15:43:16 +02:00
`,L9=Zn+`
2020-10-12 01:22:43 +02:00
return atan(x);
2020-10-15 00:22:38 +02:00
`,I9=`
2020-10-12 01:22:43 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-10-15 00:22:38 +02:00
`,A9=`
2020-10-12 01:22:43 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-10-15 00:22:38 +02:00
`,T9=`
2020-10-12 01:22:43 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2020-10-15 15:43:16 +02:00
`,N9=Zn+"return log(x + sqrt(x * x + 1.0));",x9=Zn+`
2020-10-12 01:22:43 +02:00
if (x < 1.0) return NAN;
2020-10-15 15:43:16 +02:00
return log(x + sqrt(x * x - 1.0));`,C9=Zn+`
2020-10-12 01:22:43 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-10-15 00:22:38 +02:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,R9=`
2020-10-12 01:22:43 +02: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 = `+N.backend_util.ERF_P+`;
float a1 = `+N.backend_util.ERF_A1+`;
float a2 = `+N.backend_util.ERF_A2+`;
float a3 = `+N.backend_util.ERF_A3+`;
float a4 = `+N.backend_util.ERF_A4+`;
float a5 = `+N.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-10-15 00:22:38 +02:00
`,O9="return 1.0 / x;",E9="return float(!(x >= 1.0));",D9="return float(int(x));",_o="return x;";var k9="return x;",F9=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,BS=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,zS=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,PS=`
2020-10-12 01:22:43 +02: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-10-15 00:22:38 +02:00
`,rs=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
vec4 unaryOperation(vec4 x) {
`+e+`
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
2020-10-15 15:43:16 +02:00
`}return n}();var W9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,i=$t("rc",e),r=Je(e),a=W_(e,i),s=i.slice(-2),o=e<=1?"rc":"vec2("+s.join(",")+")";this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+r+` rc = getOutputCoords();
vec4 packedInput = getA(`+a+`);
setOutput(getChannel(packedInput, `+o+`));
}
2020-10-15 15:43:16 +02:00
`}return n}();var _S=N.backend_util.segment_util,U9=N.kernel_impls.split,B9=N.kernel_impls.tile,z9=N.kernel_impls.topkImpl,P9=N.kernel_impls.whereImpl,_9=1e-7,M9=1e-4,Mo={};function H9(n){return n in Mo||(Mo[n]={}),Mo[n]}function Ho(n,t){if(t===void 0&&(t=!1),n==="linear")return t?k9:s9;if(n==="relu")return t?BS:RS;if(n==="elu")return t?PS:ES;if(n==="relu6")return t?zS:OS;if(n==="prelu")return t?$0:j0;throw new Error("Activation "+n+" has not been implemented for the WebGL backend.")}var V9=128,q9=600;function G9(){return N.env().global.screen==null?1024:N.env().global.screen.height*N.env().global.screen.width*window.devicePixelRatio*q9/1024/1024}var MS=1e3,HS=function(n){HP(t,n);function t(e){var i=n.call(this)||this;if(i.pendingRead=new WeakMap,i.pendingDisposal=new WeakSet,i.dataRefCount=new WeakMap,i.numBytesInGPU=0,i.uploadWaitMs=0,i.downloadWaitMs=0,i.warnedAboutMemory=!1,i.warnedAboutCPUBackend=!1,i.pendingDeletes=0,i.disposed=!1,!N.env().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){var r=zn(N.env().getNumber("WEBGL_VERSION"));i.binaryCache=H9(N.env().getNumber("WEBGL_VERSION")),i.gpgpu=new wS(r),i.canvas=r.canvas,i.gpgpuCreatedLocally=!0}else i.gpgpu=e,i.binaryCache={},i.gpgpuCreatedLocally=!1,i.canvas=e.gl.canvas;return i.textureManager=new e9(i.gpgpu),i.numMBBeforeWarning=G9(),i.texData=new N.DataStorage(i,N.engine()),i}return t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,i,r){if((N.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||N.env().getBool("DEBUG"))&&this.checkNumericalProblems(e),r==="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:i,dtype:r,values:e,usage:tn.UPLOAD,refCount:1}),a},t.prototype.incRef=function(e){var i=this.texData.get(e);i.refCount++},t.prototype.decRef=function(e){if(this.texData.has(e)){var i=this.texData.get(e);i.refCount--}},t.prototype.move=function(e,i,r,a){if(N.env().getBool("DEBUG")&&this.checkNumericalProblems(i),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:a,values:i,usage:tn.UPLOAD,refCount:1})},t.prototype.disposeIntermediateTensorInfo=function(e){var i=e.dataId;if(this.texData.has(i)){var r=this.texData.get(i);r.refCount--,r.refCount<1&&this.disposeData(i)}},t.prototype.readSync=function(e){var i=this.texData.get(e),r=i.values,a=i.dtype,s=i.complexTensors,o=i.slice,l=i.shape,u=i.isPacked;if(o!=null){var c=void 0;u?c=new rs(l,_o):c=new Re(l,_o);var h=this.runWebGLProgram(c,[{dataId:e,shape:l,dtype:a}],a),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(r!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return r;var p=this.activeTimers!=null,f;p&&(f=N.util.now());var m;if(a==="complex64"){var g=s.real.dataSync(),v=s.imag.dataSync();m=N.backend_util.mergeRealAndImagArrays(g,v)}else m=this.getValuesFromTexture(e);return p&&(this.downloadWaitMs+=N.util.now()-f),this.convertAndCacheOnCPU(e,m)},t.prototype.read=function(e){return Oo(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h,d,p,f,m,g,v,b,w,S,L,x,C,R;return Eo(this,function(D){switch(D.label){case 0:if(this.pendingRead.has(e))return i=this.pendingRead.get(e),[2,new Promise(function(k){return i.push(k)})];if(r=this.texData.get(e),a=r.values,s=r.shape,o=r.slice,l=r.dtype,u=r.complexTensors,c=r.isPacked,o!=null)return h=void 0,c?h=new rs(s,_o):h=new Re(s,_o),d=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:l}],l),p=this.read(d.dataId),this.disposeIntermediateTensorInfo(d),[2,p];if(a!=null)return[2,this.convertAndCacheOnCPU(e)];if(!N.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&N.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,l!=="complex64"&&N.env().get("WEBGL_BUFFER_SUPPORTED")&&(m=this.decode(e),g=this.texData.
2020-10-12 01:22:43 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-15 00:22:38 +02:00
`,X9=`
2020-10-12 01:22:43 +02: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-10-15 15:43:16 +02:00
`;function Vo(n){return function(t){var e=t.inputs,i=t.backend,r=e.x,a=i,s=new Re(r.shape,n);return a.runWebGLProgram(s,[r],r.dtype)}}function qd(n,t,e,i){return function(r){var a=r.inputs,s=r.backend,o=a,l=o.a,u=o.b,c=s,h=N.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ii(t,l.shape,u.shape,!!e):new bt(n,l.shape,u.shape),d=i||l.dtype,p=c.runWebGLProgram(h,[l,u],d);return p}}var J9=$9+`
2020-10-12 01:22:43 +02:00
return atan(a, b);
2020-10-15 00:22:38 +02:00
`,Z9=`
2020-10-12 01:22:43 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-15 00:22:38 +02:00
`+X9+`
2020-10-12 01:22:43 +02:00
return result;
2020-10-15 15:43:16 +02:00
`,Q9=qd(J9,Z9),e6={kernelName:N.Atan2,backendName:"webgl",kernelFunc:Q9};function Gd(n){var t=n.inputs,e=n.backend,i=t.x;return e.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}var t6={kernelName:N.Identity,backendName:"webgl",kernelFunc:Gd};function n6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;Qr(r,"avgPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;N.util.assert(N.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=N.backend_util.computePool2DInfo(r.shape,a,s,u,o,l);if(c.filterWidth===1&&c.filterHeight===1&&N.util.arraysEqual(c.inShape,c.outShape))return Gd({inputs:{x:r},backend:e});var h=new is(c,"avg",!1);return e.runWebGLProgram(h,[r],"float32")}var i6={kernelName:N.AvgPool,backendName:"webgl",kernelFunc:n6};function r6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=a;Qr([r,a],"avgPoolBackprop");var o=i.filterSize,l=i.strides,u=i.pad,c=N.backend_util.computePool2DInfo(s.shape,o,l,1,u),h=new bM(c);return e.runWebGLProgram(h,[r],s.dtype)}var a6={kernelName:N.AvgPoolBackprop,backendName:"webgl",kernelFunc:r6};var s6=function(){function n(t,e,i,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],N.backend_util.assertAndGetBroadcastShape(t,e),N.backend_util.assertAndGetBroadcastShape(t,i);var o="0.0";r!=null&&(N.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="1.0";a!=null&&(N.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = `+o+`;
float scale = `+l+`;
float inv = scale * inversesqrt(variance + float(`+s+`));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
2020-10-15 00:22:38 +02:00
`}return n}();var o6=function(){function n(t,e,i,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.backend_util.assertAndGetBroadcastShape(t,e),N.backend_util.assertAndGetBroadcastShape(t,i);var o="vec4(0.0)";r!=null&&(N.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="vec4(1.0)";a!=null&&(N.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
vec4 offset = `+o+`;
vec4 scale = `+l+`;
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(`+s+`));
setOutput((x - mean) * inv + offset);
}
2020-10-15 00:22:38 +02:00
`}return n}();var l6=function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=t.mean,s=t.variance,o=t.offset,l=t.scale;N.util.assert(a.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),N.util.assert(o==null||a.shape.length===o.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),N.util.assert(l==null||a.shape.length===l.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var u=i.varianceEpsilon;u==null&&(u=.001);var c=[r,a,s],h=null;o!=null&&(h=o.shape,c.push(o));var d=null;l!=null&&(d=l.shape,c.push(l));var p=N.env().getBool("WEBGL_PACK_NORMALIZATION")?new o6(r.shape,a.shape,s.shape,h,d,u):new s6(r.shape,a.shape,s.shape,h,d,u),f=e.runWebGLProgram(p,c,c[0].dtype);return f},u6={kernelName:N.FusedBatchNorm,backendName:"webgl",kernelFunc:l6};var c6=qS+`
2020-10-12 01:22:43 +02:00
return cos(x);
2020-10-15 00:22:38 +02:00
`,h6=Vo(c6),d6={kernelName:N.Cos,backendName:"webgl",kernelFunc:h6};var p6=`
2020-10-12 01:22:43 +02:00
if (a == b) {
return 1.0;
};
2020-10-15 00:22:38 +02:00
return a / b;`,f6=`
2020-10-12 01:22:43 +02: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-10-15 15:43:16 +02:00
`,m6=qd(p6,f6,!0),g6={kernelName:N.Div,backendName:"webgl",kernelFunc:m6};var v6=function(){function n(t){this.variableNames=["Image"],this.outputShape=[];var e=t[2];this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = `+e+` - x;
float outputValue;
if(coordX >= 0 && coordX < `+e+`) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2020-10-15 00:22:38 +02:00
`}return n}();var y6={kernelName:N.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=t.image,r=e,a=new v6(i.shape),s=r.runWebGLProgram(a,[i],i.dtype);return s}};var b6=function(){function n(t){this.variableNames=["A"];var e=Dt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02: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(`+r+".0, "+i+`.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;
}
setOutput(floor(value * 255.0 + 0.5));
}
2020-10-15 00:22:38 +02:00
`}return n}();var w6=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Dt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=`
2020-10-12 01:22:43 +02: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(`+r+".0, "+i+`.0);
vec4 values = `+e.texture2D+`(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
`+e.output+` = result;
}
2020-10-15 15:43:16 +02:00
`}return n}();var L6={kernelName:N.FromPixels,backendName:"webgl",kernelFunc:S6},aa;function S6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.pixels,a=i.numChannels,s=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,l=s?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=l[0],c=l[1],h=[c,u],d=[c,u,a];(o||s)&&(aa==null&&(aa=document.createElement("canvas").getContext("2d")),aa.canvas.width=u,aa.canvas.height=c,aa.drawImage(r,0,0,u,c),r=aa.canvas);var p=e.makeTensorInfo(h,"int32");e.texData.get(p.dataId).usage=tn.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),r);var f=N.env().getBool("WEBGL_PACK")?new w6(d):new b6(d),m=e.runWebGLProgram(f,[p],"int32");return e.disposeData(p.dataId),m}function I6(n){for(var t=[];t.length===0||t[t.length-1].outSize!==1;){var e=t.length?t[t.length-1].outSize:n[1],i=N.backend_util.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:i,outSize:Math.ceil(e/i)})}return t}function A6(n,t,e,i){for(var r=I6(n.shape),a=n,s=0;s<r.length;s++){var o=r[s],l=o.inSize,u=o.windowSize,c=o.outSize,h=new LS({windowSize:u,inSize:l,batchSize:n.shape[0],outSize:c},e),d=a;a=i.runWebGLProgram(h,[a],t),d.dataId!==n.dataId&&i.disposeData(d.dataId)}return a}function T6(n,t,e){var i=[lr(n.shape)].concat(ur(n.shape)),r={dtype:n.dtype,shape:i,dataId:n.dataId},a=[lr(t)].concat(ur(t)),s=new IS(a,i),o=!0,l=e.runWebGLProgram(s,[r],n.dtype,null,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function Yd(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=i.shape,s=e,o=N.util.sizeFromShape(r.shape),l=N.util.inferFromImplicitShape(a,o),u=N.util.sizeFromShape(l);N.util.assert(o===u,function(){return"The new shape ("+l+") has "+u+" elements and the old "+("shape ("+r.shape+") has "+o+" elements. The new shape and old ")+"shape must have the same number of elements."});var c=s.texData.get(r.dataId);return c.isPacked&&!ts(r.shape,l)&&!(c.texture!==null&&ts(c.shape,l))?T6(r,l,s):(s.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var N6={kernelName:N.Reshape,backendName:"webgl",kernelFunc:Yd};function x6(n,t,e,i){var r=N.util.sizeFromShape(t),a=N.util.sizeFromShape(n.shape),s=a/r,o=Yd({inputs:{x:n},attrs:{shape:[s,r]},backend:i}),l=A6(o,n.dtype,"max",i),u=Yd({inputs:{x:l},attrs:{shape:e},backend:i});return i.disposeIntermediateTensorInfo(o),i.disposeIntermediateTensorInfo(l),u}var R6=function(){function n(t,e){this.variableNames=["A"];for(var i=new Array(t.length),r=0;r<i.length;r++)i[r]=t[e[r]];this.outputShape=i,this.rank=i.length;var a=Je(this.rank),s=C6(e);this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+a+` resRC = getOutputCoords();
setOutput(getA(`+s+`));
}
2020-10-15 00:22:38 +02:00
`}return n}();function C6(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"],i=new Array(t),r=0;r<n.length;r++)i[n[r]]=e[r];return i.join()}var O6=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var i=new Array(t.length),r=0;r<i.length;r++)i[r]=t[e[r]];if(this.outputShape=i,this.rank=i.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var a=Je(this.rank),s=P0("rc",this.rank),o=new Array(this.rank),r=0;r<e.length;r++)o[e[r]]=s[r];var l="vec2("+o.slice(-2).join()+")",u="++"+s[this.rank-1]+" < "+i[this.rank-1],c="getChannel(getA("+o.join()+"), "+l+")";this.userCode=`
2020-10-12 01:22:43 +02:00
void main() {
`+a+` rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = `+c+`;
if(`+u+`) {
result[1] = `+c+`;
}
--`+s[this.rank-1]+`;
if(++`+s[this.rank-2]+" < "+i[this.rank-2]+`) {
result[2] = `+c+`;
if(`+u+`) {
result[3] = `+c+`;
}
}
setOutput(result);
}
2020-10-15 15:43:16 +02:00
`}return n}();function GS(n,t,e){var i=N.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new O6(n.shape,t):new R6(n.shape,t);return e.runWebGLProgram(i,[n],n.dtype)}var E6={kernelName:N.Max,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e,s=a.reductionIndices,o=a.keepDims,l=i,u=r.shape.length,c=N.util.parseAxisParam(s,r.shape),h=c,d=N.backend_util.getAxesPermutation(h,u),p=d!=null,f=l.shouldExecuteOnCPU([r]),m=r;if(p){if(f){for(var g=l.texData.get(m.dataId),v=g.values,b=new Array(u),w=0;w<b.length;w++)b[w]=r.shape[d[w]];var S=z0(v,r.shape,r.dtype,d,b);m=l.makeTensorInfo(b,r.dtype);var L=l.texData.get(m.dataId);L.values=S}else m=GS(r,d,l);h=N.backend_util.getInnerMostAxes(h.length,u)}N.backend_util.assertAxesAreInnerMostDims("max",h,u);var x=N.backend_util.computeOutAndReduceShapes(m.shape,h),C=x[0],R=x[1],D=C;o&&(D=N.backend_util.expandShapeToKeepDim(C,c));var k;if(f){var g=l.texData.get(m.dataId),v=g.values,W=N_(v,N.util.sizeFromShape(R),D,r.dtype);k=l.makeTensorInfo(D,r.dtype);var F=l.texData.get(k.dataId);F.values=W}else k=x6(m,R,D,l);return p&&l.disposeIntermediateTensorInfo(m),k}};function D6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;Qr(r,"maxPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;N.util.assert(N.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=N.backend_util.computePool2DInfo(r.shape,a,s,u,o,l);if(c.filterWidth===1&&c.filterHeight===1&&N.util.arraysEqual(c.inShape,c.outShape))return Gd({inputs:{x:r},backend:e});var h=new is(c,"max",!1);return e.runWebGLProgram(h,[r],r.dtype)}var k6={kernelName:N.MaxPool,backendName:"webgl",kernelFunc:D6};function F6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=t.output,o=a;Qr([a,s],"maxPoolBackprop");var l=i.filterSize,u=i.strides,c=i.pad,h=i.dimRoundingMode,d=N.backend_util.computePool2DInfo(o.shape,l,u,1,c,h),p=!0,f=new is(d,"max",p),m=e.runWebGLProgram(f,[o],o.dtype),g=new R5(d),v=e.runWebGLProgram(g,[r,m],o.dtype);return e.disposeIntermediateTensorInfo(m),v}var W6={kernelName:N.MaxPoolBackprop,backendName:"webgl",kernelFunc:F6};function U6(n,t,e,i){var r=new is(e,"max",!1),a=i.runWebGLProgram(r,[n],"float32");r=new is(e,"max",!0,!0,t);var s=i.runWebGLProgram(r,[n],"float32");return[a,s]}var B6={kernelName:N.MaxPoolWithArgmax,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e,s=a.filterSize,o=a.strides,l=a.pad,u=a.includeBatchInIndex,c=i;N.util.assert(r.shape.length===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+r.shape.length+"."});var h=[1,1];N.util.assert(N.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=N.backend_util.computePool2DInfo(r.shape,s,o,h,l),p=U6(r,u,d,c),f=p[0],m=p[1];return[f,m]}};var z6={kernelName:N.NonMaxSuppressionV3,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs;N.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=e,d=h.readSync(a.dataId),p=h.readSync(s.dataId),f=l,m=u,g=c;return N.kernel_impls.nonMaxSuppressionV3Impl(d,p,f,m,g)}};var P6=N.kernel_impls.nonMaxSuppressionV4Impl,_6={kernelName:N.NonMaxSuppressionV4,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs;N.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=o.padToMaxOutputSize,d=e,p=d.readSync(a.dataId),f=d.readSync(s.dataId),m=P6(p,f,l,u,c,h),g=m.selectedIndices,v=m.validOutputs;return[g,v]}};var M6=N.kernel_impls.nonMaxSuppressionV5Impl,H6={kernelName:N.NonMaxSuppressionV5,backendName:"webgl",kernelFunc:function(n){var t=n.in
2020-10-12 01:22:43 +02:00
vec3 fill = vec3(`+i.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+") * "+l+" - (float(y) - "+p+") * "+o+`;
float coordYFloat = (float(x) - `+d+") * "+o+" + (float(y) - "+p+") * "+l+`;
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-10-15 00:22:38 +02:00
`}return n}();var q6={kernelName:N.RotateWithOffset,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.image,a=e,s=a.radians,o=a.fillValue,l=a.center,u=i,c=new V6(r.shape,s,o,l),h=u.runWebGLProgram(c,[r],r.dtype);return h}};var G6=qS+`
2020-10-12 01:22:43 +02:00
return sin(x);
2020-10-15 15:43:16 +02:00
`,Y6=Vo(G6),K6={kernelName:N.Sin,backendName:"webgl",kernelFunc:Y6};var j6="return x * x;",$6=Vo(j6),X6={kernelName:N.Square,backendName:"webgl",kernelFunc:$6};var YS="return (a - b) * (a - b);",J6=qd(YS,YS),Z6={kernelName:N.SquaredDifference,backendName:"webgl",kernelFunc:J6};var Q6="return tan(x);",e8=Vo(Q6),t8={kernelName:N.Tan,backendName:"webgl",kernelFunc:e8};var n8={kernelName:N.Transpose,backendName:"webgl",kernelFunc:function(n){for(var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e.perm,s=i,o=r.shape.length,l=new Array(o),u=0;u<l.length;u++)l[u]=r.shape[a[u]];var c;if(s.shouldExecuteOnCPU([r])){var h=s.texData.get(r.dataId),d=h.values,p=z0(d,r.shape,r.dtype,a,l);c=s.makeTensorInfo(l,r.dtype);var f=s.texData.get(c.dataId);f.values=p}else c=GS(r,a,s);return c}};function i8(n){var t=n.inputs,e=n.attrs,i=n.backend,r=e.axis,a=t.x;Qr(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");var s=i.readSync(a.dataId),o=E_(s,r,a.shape,a.dtype),l=o.outputValues,u=o.outputShape,c=o.indices;return[i.makeTensorInfo(u,a.dtype,l),i.makeTensorInfo([c.length],"int32",c)]}var r8={kernelName:N.Unique,backendName:"webgl",kernelFunc:i8};var a8=[e6,i6,a6,u6,d6,g6,y6,L6,t6,E6,k6,W6,B6,z6,_6,H6,N6,q6,K6,X6,Z6,t8,n8,r8];for(var Kd=0,KS=a8;Kd<KS.length;Kd++){var s8=KS[Kd];N.registerKernel(s8)}Bn.GPGPUContext=wS;Bn.MathBackendWebGL=HS;Bn.forceHalfFloat=VS;Bn.gpgpu_util=w5;Bn.setWebGLContext=p0;Bn.version_webgl=K9;Bn.webgl=j9;Bn.webgl_util=r_});var kt=Se(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});var jd=ji(),$d=Vb(),Xd=rw(),$S=Tw(),o8=d0(),l8=jS();var u8="2.6.0";var c8={"tfjs-core":jd.version_core,"tfjs-backend-cpu":o8.version_cpu,"tfjs-backend-webgl":l8.version_webgl,"tfjs-data":$S.version_data,"tfjs-layers":$d.version_layers,"tfjs-converter":Xd.version_converter,tfjs:u8};Object.keys(jd).forEach(function(n){n!=="default"&&Object.defineProperty(dr,n,{enumerable:!0,get:function(){return jd[n]}})});Object.keys($d).forEach(function(n){n!=="default"&&Object.defineProperty(dr,n,{enumerable:!0,get:function(){return $d[n]}})});Object.keys(Xd).forEach(function(n){n!=="default"&&Object.defineProperty(dr,n,{enumerable:!0,get:function(){return Xd[n]}})});dr.data=$S;dr.version=c8});var tL=Se(qo=>{const Be=kt(),h8={strides:[8,16],anchors:[2,6]},XS=6;function d8(n,t,e){const i=[];for(let r=0;r<e.strides.length;r++){const a=e.strides[r],s=Math.floor((t+a-1)/a),o=Math.floor((n+a-1)/a),l=e.anchors[r];for(let u=0;u<s;u++){const c=a*(u+.5);for(let h=0;h<o;h++){const d=a*(h+.5);for(let p=0;p<l;p++)i.push([d,c])}}}return i}const JS=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},ZS=n=>({startEndTensor:n,startPoint:Be.slice(n,[0,0],[-1,2]),endPoint:Be.slice(n,[0,2],[-1,2])}),p8=(n,t)=>{const e=Be.mul(n.startPoint,t),i=Be.mul(n.endPoint,t),r=Be.concat2d([e,i],1);return ZS(r)};function f8(n,t,e){const i=Be.slice(n,[0,1],[-1,2]),r=Be.add(i,t),a=Be.slice(n,[0,3],[-1,2]),s=Be.div(a,e),o=Be.div(r,e),l=Be.div(s,2),u=Be.sub(o,l),c=Be.add(o,l),h=Be.mul(u,e),d=Be.mul(c,e),p=1;return Be.concat2d([h,d],p)}function QS(n,t){return Be.tidy(()=>{const e=n.box?n.box:n;return p8(e,t).startEndTensor.squeeze()})}class eL{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=d8(t.detector.inputSize,t.detector.inputSize,h8),this.anchors=Be.tensor2d(this.anchorsData),this.inputSizeData=[t.detector.inputSize,t.detector.inputSize],this.inputSize=Be.tensor1d([t.detector.inputSize,t.detector.inputSize]),this.iouThreshold=t.detector.iouThreshold,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n){const[t,e,i]=Be.tidy(()=>{const l=n.resizeBilinear([this.width,this.height]),u=Be.mul(Be.sub(l.div(255),.5),2),c=this.blazeFaceModel.predict(u),h=c.squeeze(),d=f8(h,this.anchors,this.inputSize),p=Be.slice(h,[0,0],[-1,1]),f=Be.sigmoid(p).squeeze();return[h,d,f]}),r=await Be.image.nonMaxSuppressionAsync(e,i,this.maxFaces,this.iouThreshold,this.scoreThreshold),a=await r.array();r.dispose(
2020-10-12 01:22:43 +02: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.
* =============================================================================
*/
/**
* @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. */
//# sourceMappingURL=human.js.map