mirror of https://github.com/vladmandic/human
4210 lines
1.3 MiB
JavaScript
4210 lines
1.3 MiB
JavaScript
![]() |
var pf=Object.defineProperty,ng=N=>pf(N,"__esModule",{value:!0}),Mr=(N,i)=>()=>(i||(i={exports:{}},N(i.exports,i)),i.exports),Kh=(N,i)=>{ng(N);for(var ke in i)pf(N,ke,{get:i[ke],enumerable:!0})},ag=Mr(()=>{}),ig=Mr(()=>{}),Pp=Mr(()=>{}),ml=Mr(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=function(t,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,a){n.__proto__=a}||function(n,a){for(var c in a)a.hasOwnProperty(c)&&(n[c]=a[c])},i(t,e)};function ke(t,e){i(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function O(t,e,n,a){return new(n||(n=Promise))(function(c,d){function y(C){try{_(a.next(C))}catch(D){d(D)}}function v(C){try{_(a.throw(C))}catch(D){d(D)}}function _(C){C.done?c(C.value):new n(function(D){D(C.value)}).then(y,v)}_((a=a.apply(t,e||[])).next())})}function H(t,e){var n={label:0,sent:function(){if(d[0]&1)throw d[1];return d[1]},trys:[],ops:[]},a,c,d,y;return y={next:v(0),throw:v(1),return:v(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function v(C){return function(D){return _([C,D])}}function _(C){if(a)throw new TypeError("Generator is already executing.");for(;n;)try{if(a=1,c&&(d=C[0]&2?c.return:C[0]?c.throw||((d=c.return)&&d.call(c),0):c.next)&&!(d=d.call(c,C[1])).done)return d;(c=0,d)&&(C=[C[0]&2,d.value]);switch(C[0]){case 0:case 1:d=C;break;case 4:return n.label++,{value:C[1],done:!1};case 5:n.label++,c=C[1],C=[0];continue;case 7:C=n.ops.pop(),n.trys.pop();continue;default:if(!(d=n.trys,d=d.length>0&&d[d.length-1])&&(C[0]===6||C[0]===2)){n=0;continue}if(C[0]===3&&(!d||C[1]>d[0]&&C[1]<d[3])){n.label=C[1];break}if(C[0]===6&&n.label<d[1]){n.label=d[1],d=C;break}if(d&&n.label<d[2]){n.label=d[2],n.ops.push(C);break}d[2]&&n.ops.pop(),n.trys.pop();continue}C=e.call(t,n)}catch(D){C=[6,D],c=0}finally{a=d=0}if(C[0]&5)throw C[1];return{value:C[0]?C[1]:void 0,done:!0}}}var se=1e-7,xe=1e-4,Q=function(){function t(e,n){this.backend=e,this.dataMover=n,this.data=new WeakMap,this.dataIdsCount=0}return t.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},t.prototype.set=function(e,n){this.dataIdsCount++,this.data.set(e,n)},t.prototype.has=function(e){return this.data.has(e)},t.prototype.delete=function(e){return this.dataIdsCount--,this.data.delete(e)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),Ae=function(){function t(){}return t.prototype.time=function(e){return P("time")},t.prototype.read=function(e){return P("read")},t.prototype.readSync=function(e){return P("readSync")},t.prototype.numDataIds=function(){return P("numDataIds")},t.prototype.disposeData=function(e){return P("disposeData")},t.prototype.write=function(e,n,a){return P("write")},t.prototype.move=function(e,n,a,c){return P("move")},t.prototype.memory=function(){return P("memory")},t.prototype.floatPrecision=function(){return P("floatPrecision")},t.prototype.epsilon=function(){return this.floatPrecision()===32?se:xe},t.prototype.batchMatMul=function(e,n,a,c){return P("batchMatMul")},t.prototype.fusedBatchMatMul=function(e){var n=e.a,a=e.b,c=e.transposeA,d=e.transposeB,y=e.bias,v=e.activation,_=e.preluActivationWeights;return P("fusedBatchMatMul")},t.prototype.slice=function(e,n,a){return P("slice")},t.prototype.stridedSlice=function(e,n,a,c){return P("stridedSlice")},t.prototype.unstack=function(e,n){return P("unstack")},t.prototype.reverse=function(e,n){return P("reverse")},t.prototype.concat=function(e,n){return P("concat")},t.prototype.neg=function(e){return P("neg")},t.prototype.add=function(e,n){return P("add")},t.prototype.addN=function(e){return P("addN")},t.prototype.subtract=function(e,n){return P("subtract")},t.prototype.multiply=function(e,n){return P("multiply")},t.prototype.realDivide=function(e,n){return P("realDivide")},t.prototype.floorDiv=function(e,n){return P("floorDiv")},t.prototype.sum=function(e,n){return P("sum")},t.prototype.prod=function(e,n){return P("prod")},t.prototype.unsortedSegmentSum=function(e,n,a){return P(
|
||
|
`)),_.join(`
|
||
|
`)}function de(t,e,n,a){var c=Tt(e),d=a[a.length-1],y=new Array(d).fill(0),v=e.length,_=n==="complex64"?Oe(t):t;if(v>1)for(var C=0;C<c/d;C++)for(var D=C*d,B=0;B<d;B++)y[B]=Math.max(y[B],ye(_[D+B],0,n).length);return y}function ye(t,e,n){var a;return Array.isArray(t)?a=parseFloat(t[0].toFixed(_e))+" + "+(parseFloat(t[1].toFixed(_e))+"j"):yn(t)?a="'"+t+"'":n==="bool"?a=ve(t):a=parseFloat(t.toFixed(_e)).toString(),yt(a,e)}function ve(t){return t===0?"false":"true"}function Re(t,e,n,a,c,d){d===void 0&&(d=!0);var y=n==="complex64"?2:1,v=e[0],_=e.length;if(_===0){if(n==="complex64"){var C=Oe(t);return[ye(C[0],0,n)]}return n==="bool"?[ve(t[0])]:[t[0].toString()]}if(_===1){if(v>oe){var D=ee*y,B=Array.from(t.slice(0,D)),U=Array.from(t.slice((v-ee)*y,v*y));return n==="complex64"&&(B=Oe(B),U=Oe(U)),["["+B.map(function(er,mr){return ye(er,c[mr],n)}).join(", ")+", ..., "+U.map(function(er,mr){return ye(er,c[v-ee+mr],n)}).join(", ")+"]"]}var J=n==="complex64"?Oe(t):Array.from(t);return["["+J.map(function(er,mr){return ye(er,c[mr],n)}).join(", ")+"]"]}var fe=e.slice(1),Pe=a.slice(1),Me=a[0]*y,He=[];if(v>oe){for(var ct=0;ct<ee;ct++){var It=ct*Me,Ct=It+Me;He.push.apply(He,Re(t.slice(It,Ct),fe,n,Pe,c,!1))}He.push("...");for(var ct=v-ee;ct<v;ct++){var It=ct*Me,Ct=It+Me;He.push.apply(He,Re(t.slice(It,Ct),fe,n,Pe,c,ct===v-1))}}else for(var ct=0;ct<v;ct++){var It=ct*Me,Ct=It+Me;He.push.apply(He,Re(t.slice(It,Ct),fe,n,Pe,c,ct===v-1))}var Bt=_===2?",":"";He[0]="["+He[0]+Bt;for(var ct=1;ct<He.length-1;ct++)He[ct]=" "+He[ct]+Bt;for(var sr=`,
|
||
|
`,ct=2;ct<_;ct++)sr+=`
|
||
|
`;return He[He.length-1]=" "+He[He.length-1]+"]"+(d?"":sr),He}function Oe(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var Fe=function(){function t(e,n,a){var c=this;if(this.dtype=n,this.shape=e.slice(),this.size=Tt(e),a!=null){var d=a.length;W(d===this.size,function(){return"Length of values '"+d+"' does not match the size "+("inferred by the shape '"+c.size+"'.")})}if(n==="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=a||_r(n,this.size),this.strides=Ca(e)}return t.prototype.set=function(e){for(var n=this,a=[],c=1;c<arguments.length;c++)a[c-1]=arguments[c];a.length===0&&(a=[0]),W(a.length===this.rank,function(){return"The number of provided coordinates ("+a.length+") must "+("match the rank ("+n.rank+")")});var d=this.locToIndex(a);this.values[d]=e},t.prototype.get=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];e.length===0&&(e=[0]);for(var a=0,c=0,d=e;c<d.length;c++){var y=d[c];if(y<0||y>=this.shape[a]){var v="Requested out of range element at "+e+". "+(" Buffer shape="+this.shape);throw new Error(v)}a++}for(var _=e[e.length-1],C=0;C<e.length-1;++C)_+=this.strides[C]*e[C];return this.values[_]},t.prototype.locToIndex=function(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];for(var n=e[e.length-1],a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];return n},t.prototype.indexToLoc=function(e){if(this.rank===0)return[];if(this.rank===1)return[e];for(var n=new Array(this.shape.length),a=0;a<n.length-1;++a)n[a]=Math.floor(e/this.strides[a]),e-=n[a]*this.strides[a];return n[n.length-1]=e,n},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return Ve().makeTensor(this.values,this.shape,this.dtype)},t}(),Ve=null,Xe=null;function rt(t){Ve=t}function at(t){Xe=t}var $=function(){function t(e,n,a,c){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=n||"float32",this.size=Tt(e),this.strides=Ca(e),this.dataId=a,this.id=c,this.rankType=this.rank<5?this.rank.toString():"higher"}return Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return O(this,void 0,void 0,function(){var e;return H(this,function(n){switch(n.label){case 0:return[4,this.data()];case 1:return e=n.sent(),[2,Xe.buffer(this.shape,this.dtype,e)]}})})},t.prototype.bufferSync=function(){return Xe.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return O(this,void 0,void 0,function(){var e;return H(this,function(n){switch(n.label){case 0:return[4,this.data()];case 1:return e=n.sent(),[2,Hn(this.shape,e)]}})})},t.prototype.arraySync=function(){return Hn(this.shape,this.dataSync())},t.prototype.data=function(){return O(this,void 0,void 0,function(){var e,n;return H(this,function(a){switch(a.label){case 0:return this.throwIfDisposed(),e=Ve().read(this.dataId),this.dtype==="string"?[4,e]:[3,2];case 1:n=a.sent();try{return[2,n.map(function(c){return ts(c)})]}catch(c){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}a.label=2;case 2:return[2,e]}})})},t.prototype.dataSync=function(){this.throwIfDisposed();var e=Ve().readSync(this.dataId);if(this.dtype==="string")try{return e.map(function(n){return ts(n)})}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e},t.prototype.bytes=function(){return O(this,void 0,void 0,function(){var e;return H(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),[4,Ve().read(this.dataId)];case 1:return e=n.sent(),this.dtype==="string"?[2,e]:[2,new Uint8Array(e.buffer)]}})})},t.prototype.dispose=function(){if(this.isDisposed)return;Ve().disposeTensor(this),this.isDisposedInternal=!0},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDi
|
||
|
`)+"Manifest JSON has weights with names: "+(_.join(", ")+"."));return D=d.reduce(function(Me,He,ct){return He&&Me.push(ct),Me},[]),B=[],D.forEach(function(Me){n[Me].paths.forEach(function(He){var ct=a+(a.endsWith("/")?"":"/")+He;B.push(ct)})}),[4,t(B)];case 1:return U=Pe.sent(),J={},fe=0,D.forEach(function(Me){for(var He=n[Me].paths.length,ct=0,It=0;It<He;It++)ct+=U[fe+It].byteLength;for(var Ct=new ArrayBuffer(ct),Bt=new Uint8Array(Ct),sr=0,er=0;er<He;er++){var mr=new Uint8Array(U[fe+er]);Bt.set(mr,sr),sr+=mr.byteLength}var Gr=y[Me];Gr.forEach(function(en){var Qr=Ct.slice(en.groupOffset,en.groupOffset+en.sizeBytes),Zr=ya(Qr,[en.manifestEntry]);for(var Kr in Zr)J[Kr]=Zr[Kr]}),fe+=He}),[2,J]}})})}}var Gs="application/octet-stream",po="application/json",Lu=function(){function t(e,n){if(this.DEFAULT_METHOD="POST",n==null&&(n={}),this.weightPathPrefix=n.weightPathPrefix,this.onProgress=n.onProgress,this.weightUrlConverter=n.weightUrlConverter,n.fetchFunc!=null?(W(typeof n.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=n.fetchFunc):this.fetch=Rr().platform.fetch,W(e!=null&&e.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(e)&&W(e.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+e.length+").")}),this.path=e,n.requestInit!=null&&n.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=n.requestInit||{}}return t.prototype.save=function(e){return O(this,void 0,void 0,function(){var n,a,c,d;return H(this,function(y){switch(y.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return n=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),n.body=new FormData,a=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],c={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:a},n.body.append("model.json",new Blob([JSON.stringify(c)],{type:po}),"model.json"),e.weightData!=null&&n.body.append("model.weights.bin",new Blob([e.weightData],{type:Gs}),"model.weights.bin"),[4,this.fetch(this.path,n)];case 1:if(d=y.sent(),d.ok)return[2,{modelArtifactsInfo:dn(e),responses:[d]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(d.status+"."))}})})},t.prototype.load=function(){return O(this,void 0,void 0,function(){var e,n,a,c,d,y,v,_,C,D,B,U,J,fe,Pe;return H(this,function(Me){switch(Me.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(e=Me.sent(),!e.ok)throw new Error("Request to "+this.path+" failed with status code "+(e.status+". Please verify this URL points to ")+"the model JSON of the model to load.");Me.label=2;case 2:return Me.trys.push([2,4,,5]),[4,e.json()];case 3:return n=Me.sent(),[3,5];case 4:throw a=Me.sent(),c="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?c+=" 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.":c+=" Please make sure the server is serving valid JSON for this request.",new Error(c);case 5:if(d=n.modelTopology,y=n.weightsManifest,v=n.generatedBy,_=n.convertedBy,C=n.format,D=n.userDefinedMetadata,d==null&&y==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return y!=null?[4,this.loadWeights(y)]:[3,7];case 6:J=Me.sent(),B=J[0],U=J[1],Me.label=7;case 7:return fe={modelTopology:d,weightSpecs:B,weightData:U,userDefinedMetadata:D,generatedBy:v,convertedBy:_,format:C},Pe=n.mo
|
||
|
`)+("Actual: "+_+`.
|
||
|
`)+("Expected: "+C+"."));for(var D=0;D<C.length;++D){var B=_[D],U=C[D];if(!n(B,U))throw new Error("Arrays differ: actual["+D+"] = "+B+", expected["+D+"] = "+U+`.
|
||
|
`+("Actual: "+_+`.
|
||
|
`)+("Expected: "+C+"."))}}function El(t,e){t().then(function(){return e.fail()},function(){return e()})}function Rl(t,e){var n=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return yn(t)||yn(t[0])||yn(e)||yn(e[0])?ju(t,n,function(a,c){return a==c}):ju(t,e,function(a,c){return qs(a,c,0)})}function Al(t,e,n){if(n==null&&(n=gu()),!qs(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)}function qs(t,e,n){return!isFinite(t)&&!isFinite(e)?!0:!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}function qu(t,e,n){for(var a=0;a<t.length;a++)if(t[a]<e||t[a]>n)throw new Error("Value out of range:"+t[a]+" low: "+e+", high: "+n)}function Dl(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}var Fl={__proto__:null,TEST_EPSILON_FLOAT16:Gu,expectArraysClose:Tl,testEpsilon:gu,expectPromiseToFail:El,expectArraysEqual:Rl,expectNumbersClose:Al,expectValuesInRange:qu,expectArrayBuffersEqual:Dl},Ku="2.7.0";function Ol(){Rr().set("PROD",!0)}function Ml(){Rr().set("DEBUG",!0)}function Xu(){Rr().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Sa(t){Rr().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ll(){Ie.disposeVariables()}function zl(){return Ie}function Pl(){return Ie.memory()}function Qc(t){return Ie.profile(t)}function sa(t,e){return Ie.tidy(t,e)}function Pa(t){var e=Ot(t);e.forEach(function(n){return n.dispose()})}function xu(t){return Ie.keep(t)}function Zc(t){return Ie.time(t)}function Bl(t){return Ie.setBackend(t)}function Wl(){return Ie.ready()}function Ul(){return Ie.backendName}function Vl(t){Ie.removeBackend(t)}function Hl(t){return Ie.findBackend(t)}function Gl(t){return Ie.findBackendFactory(t)}function jl(t,e,n){return n===void 0&&(n=1),Ie.registerBackend(t,e,n)}function ql(){return Ie.backend}function Kl(t,e){Rr().setPlatform(t,e)}function Xl(t,e){var n,a=ie(t,"a","add"),c=ie(e,"b","add");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.add(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,pa)}var Cr=Ee({add_:Xl});function Yl(t,e){var n,a=ie(t,"a","floorDiv"),c=ie(e,"b","floorDiv");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.floorDiv(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,k)}var Yu=Ee({floorDiv_:Yl});function Ql(t,e){var n,a=ie(t,"a","div"),c=ie(e,"b","div");if(n=Nt(a,c),a=n[0],c=n[1],a.dtype==="int32"&&c.dtype==="int32")return Yu(a,c);var d=function(_,C){var D=_.realDivide(a,c);return C([a,c]),D},y={a,b:c},v={};return Ie.runKernelFunc(d,y,null,Vr,v)}var Br=Ee({div_:Ql});function Jc(t,e){var n,a=ie(t,"a","mul"),c=ie(e,"b","mul");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.multiply(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,qr)}var bt=Ee({mul_:Jc});function Zl(t){var e=ie(t,"x","abs"),n={x:e};return Ie.runKernelFunc(function(a,c){return c([e]),e.dtype==="complex64"?a.complexAbs(e):a.abs(e)},n,null,qn)}var ui=Ee({abs_:Zl});function Jl(t){var e=ie(t,"x","acos"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.acos(e);return c([e]),d},n,null,ri)}var $c=Ee({acos_:Jl});function $l(t){var e=ie(t,"x","acosh"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.acosh(e);return c([e]),d},n,null,pi)}var el=Ee({acosh_:$l});function eh(t){W(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),W(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+t.length)});var e=t.map(function(d,y){return ie(d,"tensors"+y,"addN")}),n=e[0];e.forEach(function(d){if(d.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(d){if(!it(d.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var a=function(d,y){var v=d.addN(e);return y(e),v},c=e;return Ie.runKernelFunc(a,c,null,di)}var th=Ee({addN_:eh});function Qu(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0
|
||
|
with dtype `+y.dtype+". ")});var a=function(y,v){var _=qt(e,n[0].shape)[0],C=Ir(n.map(function(U){return U.shape}),_);if(Tt(C)===0)return Dn([],C);if(n=n.filter(function(U){return U.size>0}),n.length===1)return n[0];var D=n.map(function(U){return U.shape});lr(D,_);var B=y.concat(n,_);return v(n),B},c=n,d={axis:e};return Ie.runKernelFunc(a,c,null,Ue,d)}var kr=Ee({concat_:Lr});function Sr(t){var e=ie(t,"x","sigmoid"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.sigmoid(e);return c([d]),d},n,null,Ds)}var fn=Ee({sigmoid_:Sr});function Xr(t,e,n){var a=ie(t,"x","slice");if(a.rank===0)throw new Error("Slicing scalar is not possible");var c=function(v,_){var C=Hu(a,e,n),D=C[0],B=C[1];return Bc(a,D,B),_([a]),v.slice(a,D,B)},d={x:a},y={begin:e,size:n};return Ie.runKernelFunc(c,d,null,To,y)}var $t=Ee({slice_:Xr});function On(t){var e=ie(t,"x","tanh"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.tanh(e);return c([d]),d},n,null,Ms)}var En=Ee({tanh_:On});function kn(t,e,n,a,c,d){var y=ie(t,"forgetBias","basicLSTMCell"),v=ie(e,"lstmKernel","basicLSTMCell"),_=ie(n,"lstmBias","basicLSTMCell"),C=ie(a,"data","basicLSTMCell"),D=ie(c,"c","basicLSTMCell"),B=ie(d,"h","basicLSTMCell"),U=kr([C,B],1),J=un(U,v),fe=Cr(J,_),Pe=fe.shape[0],Me=fe.shape[1]/4,He=[Pe,Me],ct=$t(fe,[0,0],He),It=$t(fe,[0,Me],He),Ct=$t(fe,[0,Me*2],He),Bt=$t(fe,[0,Me*3],He),sr=Cr(bt(fn(ct),En(It)),bt(D,fn(Cr(y,Ct)))),er=bt(En(sr),fn(Bt));return[sr,er]}var cn=Ee({basicLSTMCell_:kn});function Mn(t,e,n){var a=ie(t,"x","batchToSpaceND"),c=e.reduce(function(_,C){return _*C});W(a.rank>=1+e.length,function(){return"input rank is "+a.rank+" but should be > than blockShape.length "+e.length}),W(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),W(a.shape[0]%c===0,function(){return"input tensor batch is "+a.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+e.join(" * ")+" === "+c)});var d=function(_){return _.batchToSpaceND(a,e,n)},y={x:a},v={blockShape:e,crops:n};return Ie.runKernelFunc(d,y,null,Mi,v)}var Hr=Ee({batchToSpaceND_:Mn});function ua(t){var e;return t.rank===0||t.rank===1?e=Ke(t,[1,1,1,t.size]):t.rank===2?e=Ke(t,[1,1,t.shape[0],t.shape[1]]):t.rank===3?e=Ke(t,[1,t.shape[0],t.shape[1],t.shape[2]]):e=t,e}function Ci(t,e,n,a,c,d){d==null&&(d=.001);var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;a!=null&&(D=ie(a,"offset","batchNorm")),W(v.rank===_.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),W(D==null||v.rank===D.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),W(C==null||v.rank===C.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var B=ua(y),U=function(Me,He){return He([B,v,_,C]),Me.batchNorm(B,Ui(v),Ui(_),Ui(D),Ui(C),d)},J={x:B,scale:C,offset:D,mean:v,variance:_},fe={varianceEpsilon:d},Pe=Ie.runKernelFunc(U,J,null,K,fe);return Ke(Pe,y.shape)}function Ui(t){return t==null?null:t.rank===0?Ke(t,[t.size]):t.rank===1?t:t.rank===2?Ke(t,[1,1,t.shape[0],t.shape[1]]):t.rank===3?Ke(t,[1,t.shape[0],t.shape[1],t.shape[2]]):t}var Xn=Ee({batchNorm_:Ci});function $i(t,e,n,a,c,d){var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;return a!=null&&(D=ie(a,"offset","batchNorm")),W(y.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(y.rank+".")}),W(v.rank===2||v.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+v.rank+".")}),W(_.rank===2||_.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+_.rank+".")}),C!=null&&W(C.rank===2||C.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+C.rank+".")}),D!=null&&W(D.rank===2||D.rank===1,function(){return"Error in batchNorm2D: off
|
||
|
`+c+" and "+e+` for depthToSpace with input shape
|
||
|
`+a.shape}),W(d*e>=0,function(){return`Negative dimension size caused by overflow when multiplying
|
||
|
`+d+" and "+e+` for depthToSpace with input shape
|
||
|
`+a.shape}),W(y%(e*e)===0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+y+" for depthToSpace with input shape "+a.shape});var v=function(D){return D.depthToSpace(a,e,n)},_={x:a},C={blockSize:e,dataFormat:n};return Ie.runKernelFunc(v,_,null,fa,C)}var Kp=Ee({depthToSpace_:Rf});function Af(t,e,n,a,c,d,y){c===void 0&&(c="NHWC"),d===void 0&&(d=[1,1]);var v=ie(t,"x","depthwiseConv2d"),_=ie(e,"filter","depthwiseConv2d"),C=v,D=!1;v.rank===3&&(D=!0,C=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2]])),W(C.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+C.rank+".")}),W(_.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(_.rank+".")}),W(C.shape[3]===_.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+C.shape[3]+") must match the inChannels dimension in ")+("filter "+_.shape[2]+".")}),y!=null&&W(xt(a),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+a+".")});var B=function(Pe,Me){d==null&&(d=[1,1]),W(dt(n,d),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+n+" and dilations '"+d+"'")});var He=T(C.shape,_.shape,n,d,a,y,!0),ct=Pe.depthwiseConv2D(C,_,He);return Me([C,_]),ct},U={x:C,filter:_},J={strides:n,pad:a,dataFormat:c,dilations:d,dimRoundingMode:y},fe=Ie.runKernelFunc(B,U,null,ra,J);return D?Ke(fe,[fe.shape[1],fe.shape[2],fe.shape[3]]):fe}var lh=Ee({depthwiseConv2d_:Af});function Df(t){var e=ie(t,"x","diag"),n=function(c){var d=Ke(e,[e.size]),y=c.diag(d),v=t.shape.concat(t.shape);return Ke(y,v)},a={x:e};return Ie.runKernelFunc(n,a,null,sn)}var Ff=Ee({diag_:Df});function Of(t,e,n,a,c,d){c===void 0&&(c=[1,1]),d===void 0&&(d="NHWC");var y=ie(t,"x","dilation2d"),v=ie(e,"filter","dilation2d");W(y.rank===3||y.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+(y.rank+".")}),W(v.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+(v.rank+".")}),W(d==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+d)});var _=y,C=!1;y.rank===3&&(_=Ke(y,[1,y.shape[0],y.shape[1],y.shape[2]]),C=!0);var D={x:_,filter:v},B={strides:n,pad:a,dilations:c},U=Ie.runKernel(hn,D,B);return C?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var Xp=Ee({dilation2d_:Of});function Mf(t,e){for(var n=t.length,a=[],c=0;c<n;c++){var d=n-1-c,y=t[d]||1,v=e[e.length-1-c]||1;v>1&&y===1&&a.unshift(d)}return a}function Ja(t,e){for(var n=[],a=0;a<e.length;a++){var c=t[t.length-a-1],d=e.length-a-1,y=e[d];(c==null||c===1&&y>1)&&n.unshift(d)}return n}function ca(t,e){for(var n=[],a=Math.max(t.length,e.length),c=0;c<a;c++){var d=t[t.length-c-1];d==null&&(d=1);var y=e[e.length-c-1];if(y==null&&(y=1),d===1)n.unshift(y);else if(y===1)n.unshift(d);else if(d!==y){var v="Operands could not be broadcast together with shapes "+(t+" and "+e+".");throw Error(v)}else n.unshift(d)}return n}function Lf(t,e){var n,a=ie(t,"a","equal"),c=ie(e,"b","equal");n=Nt(a,c),a=n[0],c=n[1],ca(a.shape,c.shape);var d=function(v){return v.equal(a,c)},y={a,b:c};return Ie.runKernelFunc(d,y,null,Kn)}var hh=Ee({equal_:Lf});function zf(t,e,n){var a=ie(e,"a","where"),c=ie(n,"b","where"),d=ie(t,"condition","where","bool"),y=ca(a.shape,c.shape),v=Ju(a,y),_=Ju(c,y);d.rank===1&&W(d.shape[0]===a.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}),d.rank!==1&&nt(d.shape,_.shape,"Error in where: ");var C=function(B,U){var J=B.select(d,v,_);return U([d]),J},D={condition:d,t:v,e:_};return Ie.runKernelFunc(C,D,null,Aa)}var us=Ee({where_:zf});function Pf(t){var e=ie(t,"x","zerosLike"),n={x:e};return Ie.runKernelFunc(function(a){return a.zerosLike(e)},n,null,zs)}var gn=Ee({zerosLike_:Pf});function Bf(t,e){var n,a=ie(t,"a","div"),c=ie(e,"b","div");n=Nt(a,c),a=n[0],c=n[1];var d=Br(a,c),y=gn(d),v=hh(c,y);return us(v,y,d)}var Yp=Ee({divNoNan_:Bf});function Wf(t,e){var n=ie(t,"t1","dot"),a=ie(e,"t2","d
|
||
|
rank `+d.rank+"."}),W(xt(e),function(){return"Error in localResponseNormalization: depthRadius must be an "+("integer but got depthRadius "+e+".")});var y=d,v=!1;d.rank===3&&(v=!0,y=Ke(d,[1,d.shape[0],d.shape[1],d.shape[2]]));var _=function(U,J){var fe=U.localResponseNormalization4D(y,e,n,a,c);return J([y,fe]),fe},C={x:y},D={depthRadius:e,bias:n,alpha:a,beta:c},B=Ie.runKernelFunc(_,C,null,In,D);return v?Ke(B,[B.shape[1],B.shape[2],B.shape[3]]):B}var id=Ee({localResponseNormalization_:h1});function p1(t){var e=ie(t,"x","log"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.log(e);return c([e]),d},n,null,xr)}var tc=Ee({log_:p1});function d1(t){var e=ie(t,"x","log1p"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.log1p(e);return c([e]),d},n,null,Sn)}var lp=Ee({log1p_:d1});function f1(t){return W(la(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){var a=ie(e,"x","tf.grad",null),c=n!=null?ie(n,"dy","tf.grad"):null;return Ie.tidy(function(){var d=Ie.gradients(function(){return t(a)},[a],c),y=d.value,v=d.grads;return c!=null&&nt(y.shape,c.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Rh(v),v[0]})}}function m1(t){return W(la(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){W(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var a=Nn(e,"args","tf.grads",null),c=n!=null?ie(n,"dy","tf.grads"):null;return Ie.tidy(function(){var d=Ie.gradients(function(){return t.apply(void 0,a)},a,c),y=d.value,v=d.grads;return c!=null&&nt(y.shape,c.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rh(v),v})}}function y1(t){return W(la(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){W(e instanceof $,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),W(n==null||n instanceof $,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var a=Ie.gradients(function(){return t(e)},[e],n),c=a.grads,d=a.value;return Rh(c),{grad:c[0],value:d}}}function v1(t){return W(la(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){W(Array.isArray(e)&&e.every(function(c){return c instanceof $}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),W(n==null||n instanceof $,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var a=Ie.gradients(function(){return t.apply(void 0,e)},e,n);return n!=null&&nt(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rh(a.grads),a}}function od(t,e){W(la(t),function(){return"The f passed in variableGrads(f) must be a function"}),W(e==null||Array.isArray(e)&&e.every(function(B){return B instanceof et}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var n=e!=null;if(!n){e=[];for(var a in Ie.registeredVariables)e.push(Ie.registeredVariables[a])}var c=n?e.filter(function(B){return!B.trainable}):null,d=e.length;e=e.filter(function(B){return B.trainable}),W(e.length>0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+d+" variables is ")+"trainable."});var y=!0,v=Ie.gradients(t,e,null,y),_=v.value,C=v.grads;W(C.some(function(B){return B!=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()."}),W(_.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+_.rank+" tensor")});var D={};return e.forEach(function(B,U){C[U]!=null&&(D[B.name]=C[U])}),c!=null&&c.forEach(function(B){return D[B.name]=null}),{value:_,grads:D}}function Cs(t){return Ie.customGrad(t)}function Rh(t){var e=t.filter(function(n){return n==nul
|
||
|
the f you passed encloses all operations that lead from x to y.`)}function g1(t){var e=ie(t,"x","neg"),n={x:e};return Ie.runKernelFunc(function(a){return a.neg(e)},n,null,Io)}var $a=Ee({neg_:g1});function x1(t){var e=ie(t,"x","softplus"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.softplus(e);return c([e]),d},n,null,Xo)}var hp=Ee({softplus_:x1});function _1(t){var e=ie(t,"x","logSigmoid"),n=Cs(function(a){var c=$a(hp($a(a))),d=function(y){var v=bt(y,fn($a(a)));return v};return{value:c,gradFunc:d}});return n(e)}var sd=Ee({logSigmoid_:_1});function w1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","max"),c=function(v,_){var C=qt(e,a.shape),D=C,B=Ji(D,a.rank),U=a;B!=null&&(U=$n(a,B),D=p(D.length,U.rank));var J=v.max(U,D);B!=null&&U.dispose();var fe=J;if(n){var Pe=ci(fe.shape,qt(e,a.shape));fe=Ke(fe,Pe),J.dispose()}return _([a,fe]),fe},d={x:a},y={reductionIndices:e,keepDims:n};return Ie.runKernelFunc(c,d,null,$r,y)}var rc=Ee({max_:w1});function b1(t,e){var n,a=ie(t,"a","sub"),c=ie(e,"b","sub");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.subtract(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,ps)}var zr=Ee({sub_:b1});function k1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","sum");a.dtype==="bool"&&(a=pr(a,"int32"));var c=function(v,_){_([a]);var C=qt(e,a.shape),D=Ji(C,a.rank),B=C,U=a;D!=null&&(U=$n(a,D),B=p(B.length,a.rank));var J=v.sum(U,B);if(n){var fe=ci(J.shape,C);J=Ke(J,fe)}return J},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Yo,y)}var Yr=Ee({sum_:k1});function S1(t,e){e===void 0&&(e=-1);var n=ie(t,"logits","logSoftmax");if(e===-1&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+n.rank+" and axis was "+e));var a=function(y,v){var _=!0,C=rc(t,e,!0),D=zr(t,C),B=zr(pr(D,"float32"),tc(Yr(cs(D),e,_)));return v([B]),B},c={logits:n},d={axis:e};return Ie.runKernelFunc(a,c,null,wa,d)}var ud=Ee({logSoftmax_:S1});function I1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","logSumExp"),c=qt(e,a.shape),d=rc(a,c,!0),y=zr(a,d),v=cs(y),_=Yr(v,c),C=tc(_),D=Cr(Ke(d,C.shape),C);if(n){var B=ci(D.shape,c);return Ke(D,B)}return D}var pp=Ee({logSumExp_:I1});function N1(t,e){var n=ie(t,"a","logicalAnd","bool"),a=ie(e,"b","logicalAnd","bool");ca(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalAnd(n,a)},c,null,pn)}var nc=Ee({logicalAnd_:N1});function C1(t){var e=ie(t,"x","logicalNot","bool"),n={x:e};return Ie.runKernelFunc(function(a){return a.logicalNot(e)},n,null,zn)}var Ah=Ee({logicalNot_:C1});function T1(t,e){var n=ie(t,"a","logicalOr","bool"),a=ie(e,"b","logicalOr","bool");ca(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalOr(n,a)},c,null,Fr)}var dp=Ee({logicalOr_:T1});function E1(t,e){var n=ie(t,"a","logicalXor","bool"),a=ie(e,"b","logicalXor","bool");return ca(n.shape,a.shape),nc(dp(t,e),Ah(nc(t,e)))}var cd=Ee({logicalXor_:E1});function R1(t,e,n,a,c){var d=ie(t,"x","maxPool"),y=1,v=d,_=!1;d.rank===3&&(_=!0,v=Ke(d,[1,d.shape[0],d.shape[1],d.shape[2]])),W(v.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+v.rank+"."}),W(dt(n,y),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+n+" and dilations '"+y+"'")}),c!=null&&W(xt(a),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+c+" but got pad "+a+".")});var C=function(J,fe){var Pe=h(v.shape,e,n,1,a,c),Me;return Pe.filterWidth===1&&Pe.filterHeight===1&&it(Pe.inShape,Pe.outShape)?Me=v.clone():Me=J.maxPool(v,Pe),fe([v,Me]),Me},D={x:v},B={filterSize:e,strides:n,pad:a,dimRoundingMode:c},U=Ie.runKernelFunc(C,D,null,mi,B);return _?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var fp=Ee({maxPool_:R1});function A1(t,e,n,a,c,d,y){e===void 0&&(e=[1,1,1]),d===void 0&&(d="NDHWC"),y==null?y=[1,1,1]:Sa("dilations is deprecated, this field will be gone in v3.0.0.");var v=ie(t,"x","maxPool3d"),_=v,C=!1;v.rank===4&&(C=!0,_=Ke(v,[1,v.shape[0],v.shape
|
||
|
`+("1. The "+o+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
|
||
|
`+("2. The custom "+o+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");return Y}else{var le=s;if(le.className==null||le.config==null)throw new w(o+": Improper config format: "+(JSON.stringify(le)+`.
|
||
|
`)+"'className' and 'config' must set.");var Ne=le.className,We=void 0,je=void 0;if(Ne in r?(b=r[Ne],We=b[0],je=b[1]):Ne in ot?(T=ot.className,We=T[0],je=T[1]):Ne in u&&(M=u[Ne],We=M[0],je=M[1]),We==null)throw new w("Unknown "+o+": "+Ne+`. This may be due to one of the following reasons:
|
||
|
`+("1. The "+o+" is defined in Python, in which ")+`case it needs to be ported to TensorFlow.js or your JavaScript code.
|
||
|
`+("2. The custom "+o+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(je!=null){for(var qe={},mt=0,pt=Object.keys(ot);mt<pt.length;mt++){var st=pt[mt];qe[st]=ot[st]}for(var dt=0,Dt=Object.keys(r);dt<Dt.length;dt++){var st=Dt[dt];qe[st]=r[st]}var or=le.config;or.customObjects=qe;for(var Xt=H({},ot),Jt=0,vr=Object.keys(r);Jt<vr.length;Jt++){var st=vr[Jt];ot[st]=r[st]}ut(le.config);var lr=je(We,le.config,r,h);return ot=H({},Xt),lr}else{for(var Xt=H({},ot),Ir=0,Lr=Object.keys(r);Ir<Lr.length;Ir++){var st=Lr[Ir];ot[st]=r[st]}var lr=new We(le.config);return ot=H({},Xt),lr}}}function Zt(s,u){return s<u?-1:s>u?1:0}function ar(s,u){return-1*Zt(s,u)}function qt(s){if(s==null)return s;for(var u=[],r=0,o=s;r<o.length;r++){var h=o[r];u.indexOf(h)===-1&&u.push(h)}return u}function Ur(s){if(s==null)throw new w("Invalid value in obj: "+JSON.stringify(s));for(var u in s)if(s.hasOwnProperty(u))return!1;return!0}function jr(s,u,r){if(r==null)return;if(s.indexOf(r)<0)throw new w(r+" is not a valid "+u+". Valid values are "+s+" or null/undefined.")}function _r(s,u,r,o){return r===void 0&&(r=0),o===void 0&&(o=Infinity),tt(r>=0),tt(o>=r),Array.isArray(s)&&s.length>=r&&s.length<=o&&s.every(function(h){return typeof h===u})}function tr(s,u){Array.isArray(s)?(i.util.assert(s.length>0,function(){return u+" is unexpectedly an empty array."}),s.forEach(function(r,o){return tr(r,"element "+(o+1)+" of "+u)})):i.util.assert(Number.isInteger(s)&&s>0,function(){return"Expected "+u+" to be a positive integer, but got "+(Fa(s)+".")})}function Fa(s){return s===null?"null":Array.isArray(s)?"["+s.map(function(u){return Fa(u)}).join(",")+"]":typeof s=="string"?'"'+s+'"':""+s}function Oa(s,u){var r=i.util.now(),o,h=function(){for(var b=[],T=0;T<arguments.length;T++)b[T]=arguments[T];var M=i.util.now();return M-r<u||(r=M,o=s.apply(void 0,b)),o};return h}function Tn(s){return s==="relu"?"relu":s==="linear"?"linear":s==="elu"?"elu":null}function Wa(s,u){return i.tidy(function(){return i.sqrt(i.sum(i.mul(s,s),u,!0))})}var Na=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.getConfig=function(){return{}},u}(i.serialization.Serializable),yn=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.defaultMaxValue=2,o.defaultAxis=0,o.maxValue=r.maxValue!=null?r.maxValue:o.defaultMaxValue,o.axis=r.axis!=null?r.axis:o.defaultAxis,o}return u.prototype.apply=function(r){var o=this;return i.tidy(function(){var h=Wa(r,o.axis),b=i.clipByValue(h,0,o.maxValue);return i.mul(r,i.div(b,i.add(P(),h)))})},u.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},u.className="MaxNorm",u}(Na);i.serialization.registerClass(yn);var Ma=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.defaultAxis=0,o.axis=r.axis!=null?r.axis:o.defaultAxis,o}return u.prototype.apply=function(r){var o=this;return i.tidy(function(){return i.div(r,i.add(P(),Wa(r,o.axis)))})},u.prototype.getConfig=function(){return{axis:this.axis}},u.className="UnitNorm",u}(Na);i.serialization.registerClass(Ma);var li=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.apply=function(r){return i.relu(r)},u.className="NonNeg",u}(Na);i.serialization.registerClass(li);var hi=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.defaultMinValue=0,o.defaultMaxValue=1,o.defaultRate=1,o.defaultAxis=0,o.minValue=r.minValue!=null?r.minValue:o.defaultMinValue,o.maxValue=r.maxValue!=null?r.maxValue:o.defaultMaxValue,o.rate=r.rate!=null?r.rate:o.defaultRate,o.axis=r.axis!=null?r.axis:o.defaultAxis,o}return u.prototype.apply=function(r){var o=this;return i.tidy(function(){var h=Wa(r,o.axis),b=i.add(i.mul(o.rate,i.clipByValue(h,o.minValue,o.maxValue)),i.mul(1-o.rate,h));return i.mul(r,i.div(b,i.add(P(),h)))})},u.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},u.className="MinMaxNorm",u}(Na);i.serialization.registerClass(hi);var la={maxNorm:"MaxNorm",minMaxNor
|
||
|
because the value dtype is `+k.dtype+", but TensorArray dtype is "+this.dtype+".");if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=k.shape),ln(this.elementShape,k.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+x+"."),K.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+x+", because it has already been read.");if(K.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+x+", because it has already been written.");K.tensor=k,i.keep(k),K.written=!0,this.tensors[x]=K},S.prototype.writeMany=function(x,k){var K=this;if(x.length!==k.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,"+("because the index size: "+x.length+" is not the same as tensors size: "+k.length+"."));x.forEach(function(Se,we){return K.write(Se,k[we])})},S.prototype.gather=function(x,k){if(!!k&&k!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+k);if(x)x=x.slice(0,this.size());else{x=[];for(var K=0;K<this.size();K++)x.push(K)}if(x.length===0)return i.tensor([],[0].concat(this.elementShape));var Se=this.readMany(x);return ln(this.elementShape,Se[0].shape,"TensorArray shape mismatch: "),i.stack(Se,0)},S.prototype.concat=function(x){if(!!x&&x!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+x);if(this.size()===0)return i.tensor([],[0].concat(this.elementShape));for(var k=[],K=0;K<this.size();K++)k.push(K);var Se=this.readMany(k);return ln(this.elementShape,Se[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+Se[0].shape+")"),i.concat(Se,0)},S.prototype.scatter=function(x,k){if(k.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+k.dtype);if(x.length!==k.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+x.length+" vs. "+k.shape[0]);var K=Math.max.apply(Math,xe(x));if(!this.dynamicSize&&K>=this.maxSize)throw new Error("Max index must be < array size ("+K+" vs. "+this.maxSize+")");this.writeMany(x,i.unstack(k,0))},S.prototype.split=function(x,k){var K=this;if(k.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+k.dtype);var Se=0,we=x.map(function(zt){return Se+=zt,Se});if(Se!==k.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
||
|
tensor.shape[0], but sum of lengths is
|
||
|
`+Se+", and tensor's shape is: "+k.shape);if(!this.dynamicSize&&x.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+x.length+"), and the TensorArray is not marked as dynamically resizeable");var Je=Se===0?0:k.size/Se,Be=[];i.tidy(function(){k=i.reshape(k,[1,Se,Je]);for(var zt=0;zt<x.length;++zt){var Wt=zt===0?0:we[zt-1],Gt=[0,Wt,0],Qt=[1,x[zt],Je];Be[zt]=i.reshape(i.slice(k,Gt,Qt),K.elementShape)}return Be});for(var vt=[],ft=0;ft<x.length;ft++)vt[ft]=ft;this.writeMany(vt,Be)},S}(),Di=function(){function S(x,k,K,Se){Se===void 0&&(Se=-1),this.tensors=x,this.elementShape=k,this.elementDtype=K,x!=null&&x.forEach(function(we){if(K!==we.dtype)throw new Error("Invalid data types; op elements "+K+", but list elements "+we.dtype);ln(k,we.shape,"TensorList shape mismatch: "),i.keep(we)}),this.idTensor=i.scalar(0),this.maxNumElements=Se,i.keep(this.idTensor)}return Object.defineProperty(S.prototype,"id",{get:function(){return this.idTensor.id},enumerable:!0,configurable:!0}),S.prototype.copy=function(){return new S(xe(this.tensors),this.elementShape,this.elementDtype)},S.prototype.clearAndClose=function(x){this.tensors.forEach(function(k){(x==null||!x.has(k.id))&&k.dispose()}),this.tensors.length=0,this.idTensor.dispose()},S.prototype.size=function(){return this.tensors.length},S.prototype.stack=function(x,k,K){var Se=this;if(K===void 0&&(K=-1),k!==this.elementDtype)throw new Error("Invalid data types; op elements "+k+", but list elements "+this.elementDtype);if(K!==-1&&this.tensors.length!==K)throw new Error("Operation expected a list with "+K+" elements but got a list with "+this.tensors.length+" elements.");return ln(x,this.elementShape,"TensorList shape mismatch: "),i.tidy(function(){var we=Se.tensors.map(function(Je){return i.reshape(Je,x)});return i.stack(we,0)})},S.prototype.popBack=function(x,k){if(k!==this.elementDtype)throw new Error("Invalid data types; op elements "+k+", but list elements "+this.elementDtype);if(this.size()===0)throw new Error("Trying to pop from an empty list.");var K=this.tensors.pop();return ln(K.shape,x,"TensorList shape mismatch: "),i.reshape(K,x)},S.prototype.pushBack=function(x){if(x.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+x.dtype+", but list elements "+this.elementDtype);if(ln(x.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");i.keep(x),this.tensors.push(x)},S.prototype.resize=function(x){if(x<0)throw new Error("TensorListResize expects size to be non-negative. Got: "+x);if(this.maxNumElements!==-1&&x>this.maxNumElements)throw new Error("TensorListResize input size "+x+" is greater maxNumElement "+this.maxNumElements+".");this.tensors.length=x},S.prototype.getItem=function(x,k,K){if(K!==this.elementDtype)throw new Error("Invalid data types; op elements "+K+", but list elements "+this.elementDtype);if(x<0||x>this.tensors.length)throw new Error("Trying to access element "+x+" in a list with "+this.tensors.length+" elements.");if(this.tensors[x]==null)throw new Error("element at index "+x+" is null.");return ln(this.tensors[x].shape,k,"TensorList shape mismatch: "),this.tensors[x]},S.prototype.setItem=function(x,k){if(k.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+k.dtype+", but list elements "+this.elementDtype);if(x<0||this.maxNumElements!==-1&&x>=this.maxNumElements)throw new Error("Trying to set element "+x+" in a list with max "+this.maxNumElements+" elements.");ln(this.elementShape,k.shape,"TensorList shape mismatch: "),i.keep(k),this.tensors[x]=k},S.prototype.gather=function(x,k,K){var Se=this;if(k!==this.elementDtype)throw new Error("Invalid data types; op elements "+k+", but list elements "+this.elementDtype);return ln(this.elementShape,K,"TensorList shape mismatch: "),x=x.slice(0,this.size()),x.length===0?i.tensor([],[0].concat(this.elementShape)):i.tidy(function(){var we=x.map(function(Je){return i.reshape(Se.tensors[Je],K)});return i.stack(we,0)
|
||
|
tensor.shape[0], but sum of lengths is
|
||
|
`+K+", and tensor's shape is: "+S.shape);for(var we=K===0?0:S.size/K,Je=i.tidy(function(){var ft=[];S=i.reshape(S,[1,K,we]);for(var zt=0;zt<x.length;++zt){var Wt=zt===0?0:Se[zt-1],Gt=[0,Wt,0],Qt=[1,x[zt],we];ft[zt]=i.reshape(i.slice(S,Gt,Qt),k)}return S.dispose(),ft}),Be=new Di([],k,S.dtype,x.length),vt=0;vt<Je.length;vt++)Be.setItem(vt,Je[vt]);return Be}var Fi=void 0,ji=function(S,x,k){return O(Fi,void 0,void 0,function(){var K,Se,we,Je,Be,vt,ft,zt,Be,Wt,Gt,vt,Qt,wr,Ar,Ar,Yt,xr,Yt,Sn,Yt,Yt,Yt,pn,zn,Fr,wa,In,ur,$r,Ra,mi,Ga,ja,ai,zi,An,ba,qi,yi,ii,qr,Io,nn,qa,La,Ki,oi,Pi,no,mo,Ka,ao,Ko,No,Co,io,ia,Ga,ja,Pr,ia,An,Fr,oa,Pr,nn,qa,Fr,Xa,Pr,Fr,Qn,Xa,Pr,qi,yi,Fr,Qn,Pr,ia,Fr,Qn,Xa,Pr,oo,Fr,Qn,Pr,Ki,Pr,Pi,Fr,ia,ja,Pr,ia,Fr,oa,Pr,mo,Fr,Ka,Pr;return H(this,function(ka){switch(ka.label){case 0:K=S.op;switch(K){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 Se=w("thenBranch",S,x,k),we=w("elseBranch",S,x,k),Je=w("cond",S,x,k),Be=w("args",S,x,k),[4,Je.data()];case 2:return vt=ka.sent(),vt[0]?[2,k.functionMap[Se].executeFunctionAsync(Be,k.tensorArrayMap,k.tensorListMap)]:[2,k.functionMap[we].executeFunctionAsync(Be,k.tensorArrayMap,k.tensorListMap)];case 3:return ft=w("body",S,x,k),zt=w("cond",S,x,k),Be=w("args",S,x,k),[4,k.functionMap[zt].executeFunctionAsync(Be,k.tensorArrayMap,k.tensorListMap)];case 4:return Wt=ka.sent(),Gt=Be.map(function(vn){return vn.id}),[4,Wt[0].data()];case 5:vt=ka.sent(),Wt.forEach(function(vn){!vn.kept&&Gt.indexOf(vn.id)===-1&&vn.dispose()}),Qt=Be,wr=function(){var vn,Bi,yo;return H(this,function(vo){switch(vo.label){case 0:return vn=Qt,[4,k.functionMap[ft].executeFunctionAsync(Qt,k.tensorArrayMap,k.tensorListMap)];case 1:return Qt=vo.sent(),Bi=Qt.map(function(Aa){return Aa.id}),vn.forEach(function(Aa){!Aa.kept&&Gt.indexOf(Aa.id)===-1&&Bi.indexOf(Aa.id)===-1&&Aa.dispose()}),[4,k.functionMap[zt].executeFunctionAsync(Qt,k.tensorArrayMap,k.tensorListMap)];case 2:return yo=vo.sent(),[4,yo[0].data()];case 3:return vt=vo.sent(),yo.forEach(function(Aa){!Aa.kept&&Gt.indexOf(Aa.id)===-1&&Bi.indexOf(Aa.id)===-1&&Aa.dispose()}),[2]}})},ka.label=6;case 6:return vt[0]?[5,wr()]:[3,8];case 7:return ka.sent(),[3,6];case 8:return[2,Qt];case 9:return Ar=w("pred",S,x,k),[2,[Tt(Ar)]];case 10:return Ar=w("pred",S,x,k),Yt=w("data",S,x,k),Yt.kept||(Yt=Tt(Yt)),[4,Ar.data()];case 11:return[2,ka.sent()[0]?[void 0,Yt]:[Yt,void 0]];case 12:return xr=S.inputNames.find(function(vn){return ge(vn,x,k)!==void 0}),xr?(Yt=ge(xr,x,k),[2,[Tt(Yt)]]):[2,void 0];case 13:return Sn=w("frameName",S,x,k),Yt=w("tensor",S,x,k),k.enterFrame(Sn),[2,[Tt(Yt)]];case 14:return Yt=w("tensor",S,x,k),k.exitFrame(),[2,[Tt(Yt)]];case 15:return Yt=w("tensor",S,x,k),k.nextIteration(),[2,[Tt(Yt)]];case 16:return pn=w("size",S,x,k),zn=w("dtype",S,x,k),Fr=w("elementShape",S,x,k),wa=w("dynamicSize",S,x,k),In=w("clearAfterRead",S,x,k),ur=w("identicalElementShapes",S,x,k),$r=w("name",S,x,k),Ra=new gr($r,zn,pn,Fr,ur,wa,In),k.addTensorArray(Ra),[2,[Ra.idTensor,i.scalar(1)]];case 17:return mi=w("tensorArrayId",S,x,k),Ga=w("index",S,x,k),ja=w("tensor",S,x,k
|
||
|
`+X});var Ue;return this.size===Infinity||this.size==null?Ue=this.size:j?Ue=Math.ceil(this.size/X):Ue=Math.floor(this.size/X),jn(function(){return H(re,void 0,void 0,function(){return se(this,function(kt){switch(kt.label){case 0:return[4,te.iterator()];case 1:return[2,kt.sent().columnMajorBatch(X,j,wi)]}})})},Ue)},pe.prototype.concatenate=function(X){var j=this,re=this,te;return this.size===Infinity||X.size===Infinity?te=Infinity:this.size!=null&&X.size!=null?te=this.size+X.size:te=null,jn(function(){return H(j,void 0,void 0,function(){var Ue,kt;return se(this,function($e){switch($e.label){case 0:return[4,re.iterator()];case 1:return kt=(Ue=$e.sent()).concatenate,[4,X.iterator()];case 2:return[2,kt.apply(Ue,[$e.sent()])]}})})},te)},pe.prototype.filter=function(X){var j=this,re=this,te;return this.size===Infinity?te=Infinity:te=null,jn(function(){return H(j,void 0,void 0,function(){return se(this,function(Ue){switch(Ue.label){case 0:return[4,re.iterator()];case 1:return[2,Ue.sent().filter(function(kt){return i.tidy(function(){return X(kt)})})]}})})},te)},pe.prototype.forEachAsync=function(X){return H(this,void 0,void 0,function(){return se(this,function(j){switch(j.label){case 0:return[4,this.iterator()];case 1:return[2,j.sent().forEachAsync(X)]}})})},pe.prototype.map=function(X){var j=this,re=this;return jn(function(){return H(j,void 0,void 0,function(){return se(this,function(te){switch(te.label){case 0:return[4,re.iterator()];case 1:return[2,te.sent().map(function(Ue){return i.tidy(function(){return X(Ue)})})]}})})},this.size)},pe.prototype.mapAsync=function(X){var j=this,re=this;return jn(function(){return H(j,void 0,void 0,function(){return se(this,function(te){switch(te.label){case 0:return[4,re.iterator()];case 1:return[2,te.sent().mapAsync(X)]}})})},this.size)},pe.prototype.prefetch=function(X){var j=this;if(X==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var re=this;return jn(function(){return H(j,void 0,void 0,function(){return se(this,function(te){switch(te.label){case 0:return[4,re.iterator()];case 1:return[2,te.sent().prefetch(X)]}})})},this.size)},pe.prototype.repeat=function(X){var j=this,re=this,te;return this.size!=null&&X>0?te=this.size*X:X===0?te=0:this.size!=null&&(X===void 0||X<0)?te=Infinity:te=null,jn(function(){return H(j,void 0,void 0,function(){var Ue,kt=this;return se(this,function($e){return Ue=Ur(function(){return H(kt,void 0,void 0,function(){var Le;return se(this,function(Ye){switch(Ye.label){case 0:return Le={},[4,re.iterator()];case 1:return[2,(Le.value=Ye.sent(),Le.done=!1,Le)]}})})}),[2,jr(Ue.take(X))]})})},te)},pe.prototype.skip=function(X){var j=this,re=this,te;return this.size!=null&&X>=0&&this.size>=X?te=this.size-X:this.size!=null&&(this.size<X||X===void 0||X<0)?te=0:te=null,jn(function(){return H(j,void 0,void 0,function(){return se(this,function(Ue){switch(Ue.label){case 0:return[4,re.iterator()];case 1:return[2,Ue.sent().skip(X)]}})})},te)},pe.prototype.shuffle=function(X,j,re){var te=this;if(re===void 0&&(re=!0),X==null||X<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 Ue=this,kt=W(j||i.util.now().toString());return jn(function(){return H(te,void 0,void 0,function(){var $e;return se(this,function(Le){switch(Le.label){case 0:return $e=kt.int32(),re&&($e+=kt.int32()),[4,Ue.iterator()];case 1:return[2,Le.sent().shuffle(X,$e.toString())]}})})},this.size)},pe.prototype.take=function(X){var j=this,re=this,te;return this.size!=null&&this.size>X?te=X:this.size!=null&&this.size<=X?te=this.size:te=null,jn(function(){return H(j,void 0,void 0,function(){return se(this,function(Ue){switch(Ue.label){case 0:return[4,re.iterator()];case 1:return[2,Ue.sent().take(X)]}})})},te)},pe.prototype.toArray=function(){return H(this,void 0,void 0,function(
|
||
|
`).map(function(kt){return kt.endsWith("\r")&&(kt=kt.slice(0,-1)),kt}),[2,te]}})})},X}(Gn),_n='"',xa=Symbol("out"),Rr=Symbol("field"),ti=Symbol("quote"),_a=Symbol("quoteafterquote"),Ri=Symbol("quoteinquote"),Hi=function(pe){O(X,pe);function X(j,re){var te=pe.call(this)||this;return te.input=j,te.hasHeader=!0,te.fullColumnNames=null,te.columnNamesValidated=!1,te.columnConfigs=null,te.configuredColumnsOnly=!1,te.delimiter=",",te.delimWhitespace=!1,te.base=new on(j),re||(re={}),te.hasHeader=!(re.hasHeader===!1),te.fullColumnNames=re.columnNames,te.columnConfigs=re.columnConfigs,te.configuredColumnsOnly=re.configuredColumnsOnly,re.delimWhitespace?(i.util.assert(re.delimiter==null,function(){return"Delimiter should not be provided when delimWhitespace is true."}),te.delimWhitespace=!0,te.delimiter=" "):te.delimiter=re.delimiter?re.delimiter:",",te}return X.prototype.columnNames=function(){return H(this,void 0,void 0,function(){return se(this,function(j){switch(j.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:j.sent(),j.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},X.prototype.setColumnNames=function(){return H(this,void 0,void 0,function(){var j,re,te,Ue,kt,$e,Le,Ye=this;return se(this,function(Ft){switch(Ft.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(j=Ft.sent(),!this.fullColumnNames&&!j)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&j&&i.util.assert(j.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+Ye.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+j.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=j),re=this.fullColumnNames.reduce(function(St,Mt){return St[Mt]=St[Mt]+1||1,St},{}),te=Object.keys(re).filter(function(St){return re[St]>1}),i.util.assert(te.length===0,function(){return"Duplicate column names found: "+te.toString()}),this.columnConfigs){for(Ue=0,kt=Object.keys(this.columnConfigs);Ue<kt.length;Ue++)if($e=kt[Ue],Le=this.fullColumnNames.indexOf($e),Le===-1)throw new Error('The key "'+$e+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}return this.columnNamesValidated=!0,[2]}})})},X.prototype.maybeReadHeaderLine=function(){return H(this,void 0,void 0,function(){var j,re,te,Ue;return se(this,function(kt){switch(kt.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return j=kt.sent(),[4,j.next()];case 2:if(re=kt.sent(),re.done)throw new Error("No data was found for CSV parsing.");return te=re.value,Ue=this.parseRow(te,!1),[2,Ue];case 3:return[2,null]}})})},X.prototype.iterator=function(){return H(this,void 0,void 0,function(){var j,re=this;return se(this,function(te){switch(te.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:te.sent(),te.label=2;case 2:return[4,this.base.iterator()];case 3:return j=te.sent(),this.hasHeader&&(j=j.skip(1)),[2,j.map(function(Ue){return re.makeDataElement(Ue)})]}})})},X.prototype.makeDataElement=function(j){for(var re=this.parseRow(j),te={},Ue={},kt=0;kt<this.fullColumnNames.length;kt++){var $e=this.fullColumnNames[kt],Le=this.columnConfigs?this.columnConfigs[$e]:null;if(this.configuredColumnsOnly&&!Le)continue;var Ye=re[kt],Ft=null;if(Ye==="")if(Le&&Le.default!==void 0)Ft=Le.default;else{if(Le&&(Le.required||Le.isLabel))throw new Error("Required column "+$e+" is empty in this line: "+j);Ft=void 0}else{var St=Number(Ye);if(isNaN(St))Le&&Le.dtype==="bool"?Ft=this.getBoolean(Ye):Ft=Ye;else if(!Le||!Le.dtype)Ft=St;else switch(Le.dtype){case"float32":Ft=St;break;case"int32":Ft=Math.floor(St);break;case"bool":Ft=this.getBoolean(Ye);break;default:Ft=St}}Le&&Le.isLabel?Ue[$e]=Ft:te[$e]=Ft}return Object.keys(Ue).length===0?te:{xs:te,ys:Ue}},X.prototype.getBoolean=function(j){return j==="1"||j.toLowerCase()==="true"?1:0},X.prototype.parseRow=function(j,re){re===void 0&&(re=!0);for(var te=[],
|
||
|
============================
|
||
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
||
|
============================`));var V={};return this.data.set(V,{values:E,dtype:A,refCount:1}),V},ue.prototype.makeTensorInfo=function(E,F,A){var V;if(F==="string"&&A!=null&&A.length>0&&i.util.isString(A[0])){var oe=A.map(function(ee){return i.util.encodeString(ee)});V=this.write(oe,E,F)}else V=this.write(A,E,F);return{dataId:V,shape:E,dtype:F}},ue.prototype.incRef=function(E){var F=this.data.get(E);F.refCount++},ue.prototype.decRef=function(E){if(this.data.has(E)){var F=this.data.get(E);F.refCount--}},ue.prototype.move=function(E,F,A,V){this.data.set(E,{values:F,dtype:V,refCount:1})},ue.prototype.numDataIds=function(){return this.data.numDataIds()},ue.prototype.read=function(E){return se(this,void 0,void 0,function(){return xe(this,function(F){return[2,this.readSync(E)]})})},ue.prototype.readSync=function(E){var F=this.data.get(E),A=F.dtype,V=F.complexTensorInfos;if(A==="complex64"){var oe=this.readSync(V.real.dataId),ee=this.readSync(V.imag.dataId);return i.backend_util.mergeRealAndImagArrays(oe,ee)}return this.data.get(E).values},ue.prototype.bufferSync=function(E){var F=this.readSync(E.dataId),A=F;if(E.dtype==="string")try{A=F.map(function(V){return i.util.decodeString(V)})}catch(V){throw new Error("Failed to decode encoded string bytes into utf-8")}return i.buffer(E.shape,E.dtype,A)},ue.prototype.makeOutput=function(E,F,A){var V=this.write(E,F,A);return i.engine().makeTensorFromDataId(V,F,A,this)},ue.prototype.disposeData=function(E){if(this.data.has(E)){var F=this.data.get(E).complexTensorInfos;F!=null&&(this.disposeData(F.real.dataId),this.disposeData(F.imag.dataId)),this.data.delete(E)}},ue.prototype.disposeIntermediateTensorInfo=function(E){var F=E.dataId;if(this.data.has(F)){var A=this.data.get(F);A.refCount--,A.refCount<1&&this.disposeData(F)}},ue.prototype.time=function(E){return se(this,void 0,void 0,function(){var F,A;return xe(this,function(V){return F=i.util.now(),E(),A=i.util.now()-F,[2,{kernelMs:A}]})})},ue.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."]}},ue.prototype.stridedSlice=function(E,F,A,V){Q(E,"stridedSlice");var oe=i.slice_util.computeOutShape(F,A,V);if(oe.some(function(Re){return Re===0}))return i.tensor([],oe);for(var ee=i.buffer(oe,E.dtype),_e=this.bufferSync(E),ce=0;ce<ee.size;ce++){for(var de=ee.indexToLoc(ce),ye=new Array(de.length),ve=0;ve<ye.length;ve++)ye[ve]=de[ve]*V[ve]+F[ve];ee.set.apply(ee,[_e.get.apply(_e,ye)].concat(de))}return ee.toTensor()},ue.prototype.diag=function(E){for(var F=this.readSync(E.dataId),A=i.buffer([E.size,E.size],E.dtype),V=A.values,oe=0;oe<F.length;oe++)V[oe*E.size+oe]=F[oe];return A.toTensor()},ue.prototype.unstack=function(E,F){for(var A=E.shape[F],V=new Array(E.rank-1),oe=0,ee=0;ee<E.rank;ee++)ee!==F&&(V[oe++]=E.shape[ee]);var _e=new Array(E.rank).fill(0),ce=E.shape.slice();ce[F]=1;for(var de=new Array(A),ee=0;ee<de.length;ee++)_e[F]=ee,de[ee]=i.slice(E,_e,ce).reshape(V);return de},ue.prototype.reverse=function(E,F){Q(E,"reverse");for(var A=i.buffer(E.shape,E.dtype),V=this.bufferSync(E),oe=function(_e){var ce=A.indexToLoc(_e),de=ce.slice();F.forEach(function(ye){return de[ye]=E.shape[ye]-1-de[ye]}),A.set.apply(A,[V.get.apply(V,de)].concat(ce))},ee=0;ee<A.size;ee++)oe(ee);return A.toTensor()},ue.prototype.neg=function(E){return Q(E,"neg"),i.mul(i.scalar(-1),E)},ue.prototype.addN=function(E){var F=this;Q(E,"addN");for(var A=E.map(function(de){return F.readSync(de.dataId)}),V=i.buffer(E[0].shape,E[0].dtype),oe=V.values,ee=0;ee<E.length;ee++)for(var _e=A[ee],ce=0;ce<oe.length;ce++)oe[ce]+=_e[ce];return V.toTensor()},ue.prototype.softmax=function(E,F){var A=i.util.parseAxisParam([F],E.shape),V=i.max(E,A),oe=i.backend_util.expandShapeToKeepDim(V.shape,A),ee=i.sub(E,V.reshape(oe)),_e=i.exp(ee),ce=this.sum(_e,A).reshape(oe);return i.div(_e,ce)},ue.prototype.pow=function(E,F){return Q([E,F],"pow"),this.broadcastedBinaryOp(E,F,E.dtype,function(A,V){return Math.pow(A,V)})},ue.prototype.floorDiv=function(E,F){Q([E,F],"floorDiv");var A=funct
|
||
|
`),I=g.length.toString().length+2,R=g.map(function(Ce,De){return i.util.rightPad((De+1).toString(),I)+Ce}),z=0,L=0;L<R.length;L++)z=Math.max(R[L].length,z);var G=R.slice(0,m-1),Z=R.slice(m-1,m),be=R.slice(m);console.log(G.join(`
|
||
|
`)),console.log(p.split(`
|
||
|
`)[0]),console.log("%c "+i.util.rightPad(Z[0],z),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(be.join(`
|
||
|
`))}function jr(f){return Gn(f,function(){return f.createProgram()},"Unable to create WebGLProgram.")}function _r(f,p){if(Qe(f,function(){return f.linkProgram(p)}),f.getProgramParameter(p,f.LINK_STATUS)===!1)throw console.log(f.getProgramInfoLog(p)),new Error("Failed to link vertex and fragment shaders.")}function tr(f,p){if(Qe(f,function(){return f.validateProgram(p)}),f.getProgramParameter(p,f.VALIDATE_STATUS)===!1)throw console.log(f.getProgramInfoLog(p)),new Error("Shader program validation failed.")}function Fa(f,p){var l=Gn(f,function(){return f.createBuffer()},"Unable to create WebGLBuffer");return Qe(f,function(){return f.bindBuffer(f.ARRAY_BUFFER,l)}),Qe(f,function(){return f.bufferData(f.ARRAY_BUFFER,p,f.STATIC_DRAW)}),l}function Oa(f,p){var l=Gn(f,function(){return f.createBuffer()},"Unable to create WebGLBuffer");return Qe(f,function(){return f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,l)}),Qe(f,function(){return f.bufferData(f.ELEMENT_ARRAY_BUFFER,p,f.STATIC_DRAW)}),l}function Tn(){return i.env().getNumber("WEBGL_VERSION")===2?1:4}function Wa(f){return Gn(f,function(){return f.createTexture()},"Unable to create WebGLTexture.")}function Na(f,p){var l=i.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(f<=0||p<=0){var m="["+f+"x"+p+"]";throw new Error("Requested texture size "+m+" is invalid.")}if(f>l||p>l){var m="["+f+"x"+p+"]",g="["+l+"x"+l+"]";throw new Error("Requested texture size "+m+" greater than WebGL maximum on this browser / GPU "+g+".")}}function yn(f){return Gn(f,function(){return f.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Ma(f,p,l,m,g,I,R){var z=f.getAttribLocation(p,l);return z===-1?!1:(Qe(f,function(){return f.bindBuffer(f.ARRAY_BUFFER,m)}),Qe(f,function(){return f.vertexAttribPointer(z,g,f.FLOAT,!1,I,R)}),Qe(f,function(){return f.enableVertexAttribArray(z)}),!0)}function li(f,p,l){jn(f,l),Qe(f,function(){return f.activeTexture(f.TEXTURE0+l)}),Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,p)})}function hi(f,p){jn(f,p),Qe(f,function(){return f.activeTexture(f.TEXTURE0+p)}),Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,null)})}function la(f,p,l){return Gn(f,function(){return f.getUniformLocation(p,l)},'uniform "'+l+'" not present in program.')}function rn(f,p,l){return f.getUniformLocation(p,l)}function Ca(f,p,l,m){Qe(f,function(){return li(f,p,m)}),Qe(f,function(){return f.uniform1i(l,m)})}function xn(f){Qe(f,function(){return f.bindFramebuffer(f.FRAMEBUFFER,null)}),Qe(f,function(){return f.viewport(0,0,f.canvas.width,f.canvas.height)}),Qe(f,function(){return f.scissor(0,0,f.canvas.width,f.canvas.height)})}function Hn(f,p,l){Qe(f,function(){return f.bindFramebuffer(f.FRAMEBUFFER,l)}),Qe(f,function(){return f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,p,0)})}function _i(f,p){Qe(f,function(){return f.bindFramebuffer(f.FRAMEBUFFER,p)}),Qe(f,function(){return f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,null,0)})}function ha(f){var p=f.checkFramebufferStatus(f.FRAMEBUFFER);if(p!==f.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ei(f,p))}function Ei(f,p){switch(p){case f.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case f.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case f.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case f.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+p}}function Gn(f,p,l){var m=Qe(f,function(){return p()});if(m==null)throw new Error(l);return m}function jn(f,p){var l=f.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,m=p+f.TEXTURE0;if(m<f.TEXTURE0||m>l){var g="[gl.TEXTURE0, gl.TEXTURE"+l+"]";throw new Error("textureUnit must be in "+g+".")}}function Ua(f,p){return p===void 0&&(p=2),i.util.sizeFromShape(f.slice(0,f.length-p))}function ga(f){if(f.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[f.length>1?f[f.length-2]:1,f[f.length-1]]}function wi(f){var p=[1,1,1],l=f.length===0||f.length===1&&f[0]===1;return l||(p=[Ua(f)]
|
||
|
void main() {
|
||
|
`+m.join(`
|
||
|
`)+`
|
||
|
|
||
|
float result = `+g+`;
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),hn=function(){function f(p,l){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p,this.variableNames=l.map(function(I,R){return"T"+R});var m=[];this.variableNames.forEach(function(I){m.push("vec4 v"+I+" = get"+I+"AtOutCoords();")});var g=this.variableNames.map(function(I){return"v"+I}).join(" + ");this.userCode=`
|
||
|
void main() {
|
||
|
`+m.join(`
|
||
|
`)+`
|
||
|
|
||
|
vec4 result = `+g+`;
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),na=function(){function f(p,l,m){this.variableNames=["A"];var g=p.windowSize,I=p.batchSize,R=p.outSize;m||this.variableNames.push("bestIndicesA"),this.outputShape=[I,R];var z=l==="max"?">":"<",L=m?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int outIdx = coords[1];
|
||
|
int inOffset = outIdx * `+g+`;
|
||
|
|
||
|
int bestIndex = inOffset;
|
||
|
float bestValue = getA(batch, bestIndex);
|
||
|
|
||
|
for (int i = 0; i < `+g+`; i++) {
|
||
|
int inIdx = `+L+`;
|
||
|
float candidate = getA(batch, inIdx);
|
||
|
if (candidate `+z+` bestValue) {
|
||
|
bestValue = candidate;
|
||
|
bestIndex = inIdx;
|
||
|
}
|
||
|
}
|
||
|
setOutput(float(bestIndex));
|
||
|
}
|
||
|
`}return f}();function Jr(f,p){return["x","y","z","w","u","v"].slice(0,p).map(function(l){return f+"."+l})}function Vr(f,p){return p===1?[f]:Jr(f,p)}function Jn(f,p){if(f===1)return"rc";for(var l="",m=0;m<f;m++)l+=p[m],m<f-1&&(l+=",");return l}function tn(){var f,p,l,m,g,I,R,z,L,G;return i.env().getNumber("WEBGL_VERSION")===2?(f="#version 300 es",p="in",l="out",m="in",g="texture",I="outputColor",R="out vec4 outputColor;",z=`
|
||
|
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="",G=`
|
||
|
#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)));
|
||
|
}
|
||
|
`):(f="",p="attribute",l="varying",m="varying",g="texture2D",I="gl_FragColor",R="",z=`
|
||
|
#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));
|
||
|
}
|
||
|
`,G=`
|
||
|
int round(float value) {
|
||
|
return int(floor(value + 0.5));
|
||
|
}
|
||
|
|
||
|
ivec4 round(vec4 value) {
|
||
|
return ivec4(floor(value + vec4(0.5)));
|
||
|
}
|
||
|
`),{version:f,attribute:p,varyingVs:l,varyingFs:m,texture2D:g,output:I,defineOutput:R,defineSpecialNaN:z,defineSpecialInf:L,defineRound:G}}function Rn(f,p,l){l===void 0&&(l="index");var m=i.util.computeStrides(p);return m.map(function(g,I){var R="int "+f[I]+" = "+l+" / "+g,z=I===m.length-1?"int "+f[I+1]+" = "+l+" - "+f[I]+" * "+g:"index -= "+f[I]+" * "+g;return R+"; "+z+";"}).join("")}function Kn(f){var p=i.util.computeStrides(f).map(function(l){return l.toString()});return`
|
||
|
int getFlatIndex(ivec3 coords) {
|
||
|
return coords.x * `+p[0]+" + coords.y * "+p[1]+` + coords.z;
|
||
|
}
|
||
|
`}var aa=`
|
||
|
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;
|
||
|
}
|
||
|
`,ma=i.backend_util.getBroadcastDims;function Li(f,p,l,m){var g=[];f.forEach(function(Te){var Ge=i.util.sizeFromShape(Te.shapeInfo.logicalShape);Te.shapeInfo.isUniform?g.push("uniform float "+Te.name+(Ge>1?"["+Ge+"]":"")+";"):(g.push("uniform sampler2D "+Te.name+";"),g.push("uniform int offset"+Te.name+";"))});var I=g.join(`
|
||
|
`),R=f.map(function(Te){return x(Te,p,m)}).join(`
|
||
|
`),z=p.texShape,L=tn(),G=Se(L),Z,be,Ce=Be(L);p.isPacked?(Z=k(p.logicalShape,z),be=Je(L)):(Z=K(p.logicalShape,z),be=we(L)),m&&(Ce+=Wt);var De=[Ce,G,be,I,Z,R,l].join(`
|
||
|
`);return De}function Ea(f){var p=f.shapeInfo.logicalShape;switch(p.length){case 0:return $r(f);case 1:return mi(f);case 2:return ja(f);case 3:return zi(f);case 4:return ba(f);case 5:return qi(f);case 6:return yi(f);default:throw new Error(p.length+"-D input sampling is not yet supported")}}function S(f){var p=f.shapeInfo.logicalShape;switch(p.length){case 0:return ur(f);case 1:return Ra(f);case 2:return Ga(f);case 3:return ai(f);default:return An(f)}}function x(f,p,l){l===void 0&&(l=!1);var m="";l?m+=S(f):m+=Ea(f);var g=f.shapeInfo.logicalShape,I=p.logicalShape;return g.length<=I.length&&(l?m+=qr(f,p):m+=Io(f,p)),m}function k(f,p){switch(f.length){case 0:return Gt();case 1:return Qt(f,p);case 2:return Fr(f,p);case 3:return Ar(f,p);default:return xr(f,p)}}function K(f,p){switch(f.length){case 0:return Gt();case 1:return wr(f,p);case 2:return wa(f,p);case 3:return Yt(f,p);case 4:return Sn(f,p);case 5:return pn(f,p);case 6:return zn(f,p);default:throw new Error(f.length+"-D output sampling is not yet supported")}}function Se(f){return`
|
||
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
||
|
return `+f.texture2D+`(textureSampler, uv).r;
|
||
|
}
|
||
|
`}function we(f){return`
|
||
|
void setOutput(float val) {
|
||
|
`+f.output+` = vec4(val, 0, 0, 0);
|
||
|
}
|
||
|
`}function Je(f){return`
|
||
|
void setOutput(vec4 val) {
|
||
|
`+f.output+` = val;
|
||
|
}
|
||
|
`}function Be(f){var p=f.version+`
|
||
|
precision highp float;
|
||
|
precision highp int;
|
||
|
precision highp sampler2D;
|
||
|
`+f.varyingFs+` vec2 resultUV;
|
||
|
`+f.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;
|
||
|
`+f.defineSpecialNaN+`
|
||
|
`+f.defineSpecialInf+`
|
||
|
`+f.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);
|
||
|
}
|
||
|
|
||
|
`+vt+`
|
||
|
`+ft+`
|
||
|
`+zt+`
|
||
|
`;return p}var vt=`
|
||
|
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);
|
||
|
}
|
||
|
`,ft=`
|
||
|
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);
|
||
|
}
|
||
|
`,zt=`
|
||
|
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);
|
||
|
}
|
||
|
`,Wt=`
|
||
|
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;
|
||
|
}
|
||
|
`;function Gt(){return`
|
||
|
int getOutputCoords() {
|
||
|
return 0;
|
||
|
}
|
||
|
`}function Qt(f,p){var l=[Math.ceil(p[0]/2),Math.ceil(p[1]/2)];return l[0]===1?`
|
||
|
int getOutputCoords() {
|
||
|
return 2 * int(resultUV.x * `+l[1]+`.0);
|
||
|
}
|
||
|
`:l[1]===1?`
|
||
|
int getOutputCoords() {
|
||
|
return 2 * int(resultUV.y * `+l[0]+`.0);
|
||
|
}
|
||
|
`:`
|
||
|
int getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
return 2 * (resTexRC.x * `+l[1]+` + resTexRC.y);
|
||
|
}
|
||
|
`}function wr(f,p){return p[0]===1?`
|
||
|
int getOutputCoords() {
|
||
|
return int(resultUV.x * `+p[1]+`.0);
|
||
|
}
|
||
|
`:p[1]===1?`
|
||
|
int getOutputCoords() {
|
||
|
return int(resultUV.y * `+p[0]+`.0);
|
||
|
}
|
||
|
`:`
|
||
|
int getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
return resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
}
|
||
|
`}function Ar(f,p){var l=[Math.ceil(p[0]/2),Math.ceil(p[1]/2)],m=Math.ceil(f[2]/2),g=m*Math.ceil(f[1]/2);return`
|
||
|
ivec3 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
int index = resTexRC.x * `+l[1]+` + resTexRC.y;
|
||
|
|
||
|
int b = index / `+g+`;
|
||
|
index -= b * `+g+`;
|
||
|
|
||
|
int r = 2 * (index / `+m+`);
|
||
|
int c = imod(index, `+m+`) * 2;
|
||
|
|
||
|
return ivec3(b, r, c);
|
||
|
}
|
||
|
`}function Yt(f,p){var l=Rn(["r","c","d"],f);return`
|
||
|
ivec3 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
`+l+`
|
||
|
return ivec3(r, c, d);
|
||
|
}
|
||
|
`}function xr(f,p){for(var l=[Math.ceil(p[0]/2),Math.ceil(p[1]/2)],m=Math.ceil(f[f.length-1]/2),g=m*Math.ceil(f[f.length-2]/2),I=g,R="",z="b, r, c",L=2;L<f.length-1;L++)I*=f[f.length-L-1],R=`
|
||
|
int b`+L+" = index / "+I+`;
|
||
|
index -= b`+L+" * "+I+`;
|
||
|
`+R,z="b"+L+", "+z;return`
|
||
|
ivec`+f.length+` getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
int index = resTexRC.x * `+l[1]+` + resTexRC.y;
|
||
|
|
||
|
`+R+`
|
||
|
|
||
|
int b = index / `+g+`;
|
||
|
index -= b * `+g+`;
|
||
|
|
||
|
int r = 2 * (index / `+m+`);
|
||
|
int c = imod(index, `+m+`) * 2;
|
||
|
|
||
|
return ivec`+f.length+"("+z+`);
|
||
|
}
|
||
|
`}function Sn(f,p){var l=Rn(["r","c","d","d2"],f);return`
|
||
|
ivec4 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
`+l+`
|
||
|
return ivec4(r, c, d, d2);
|
||
|
}
|
||
|
`}function pn(f,p){var l=Rn(["r","c","d","d2","d3"],f);return`
|
||
|
ivec5 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+p[0]+`,
|
||
|
`+p[1]+`));
|
||
|
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
|
||
|
`+l+`
|
||
|
|
||
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
||
|
return outShape;
|
||
|
}
|
||
|
`}function zn(f,p){var l=Rn(["r","c","d","d2","d3","d4"],f);return`
|
||
|
ivec6 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
|
||
|
`+l+`
|
||
|
|
||
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
||
|
return result;
|
||
|
}
|
||
|
`}function Fr(f,p){var l=[Math.ceil(p[0]/2),Math.ceil(p[1]/2)];if(i.util.arraysEqual(f,p))return`
|
||
|
ivec2 getOutputCoords() {
|
||
|
return 2 * ivec2(resultUV.yx * vec2(`+l[0]+", "+l[1]+`));
|
||
|
}
|
||
|
`;var m=Math.ceil(f[1]/2);return`
|
||
|
ivec2 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
|
||
|
int index = resTexRC.x * `+l[1]+` + resTexRC.y;
|
||
|
int r = 2 * (index / `+m+`);
|
||
|
int c = imod(index, `+m+`) * 2;
|
||
|
|
||
|
return ivec2(r, c);
|
||
|
}
|
||
|
`}function wa(f,p){return i.util.arraysEqual(f,p)?`
|
||
|
ivec2 getOutputCoords() {
|
||
|
return ivec2(resultUV.yx * vec2(`+p[0]+", "+p[1]+`));
|
||
|
}
|
||
|
`:f[1]===1?`
|
||
|
ivec2 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
return ivec2(index, 0);
|
||
|
}
|
||
|
`:f[0]===1?`
|
||
|
ivec2 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
return ivec2(0, index);
|
||
|
}
|
||
|
`:`
|
||
|
ivec2 getOutputCoords() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+p[0]+", "+p[1]+`));
|
||
|
int index = resTexRC.x * `+p[1]+` + resTexRC.y;
|
||
|
int r = index / `+f[1]+`;
|
||
|
int c = index - r * `+f[1]+`;
|
||
|
return ivec2(r, c);
|
||
|
}
|
||
|
`}function In(f){return"offset"+f}function ur(f){var p=f.name,l="get"+p.charAt(0).toUpperCase()+p.slice(1),m=tn();return`
|
||
|
vec4 `+l+`() {
|
||
|
return `+m.texture2D+"("+p+`, halfCR);
|
||
|
}
|
||
|
`}function $r(f){var p=f.name,l="get"+p.charAt(0).toUpperCase()+p.slice(1);if(f.shapeInfo.isUniform)return"float "+l+"() {return "+p+";}";var m=f.shapeInfo.texShape,g=m[0],I=m[1];if(g===1&&I===1)return`
|
||
|
float `+l+`() {
|
||
|
return sampleTexture(`+p+`, halfCR);
|
||
|
}
|
||
|
`;var R=f.shapeInfo.texShape,z=R[0],L=R[1],G=In(p);return`
|
||
|
float `+l+`() {
|
||
|
vec2 uv = uvFromFlat(`+z+", "+L+", "+G+`);
|
||
|
return sampleTexture(`+p+`, uv);
|
||
|
}
|
||
|
`}function Ra(f){var p=f.name,l="get"+p.charAt(0).toUpperCase()+p.slice(1),m=f.shapeInfo.texShape,g=[Math.ceil(m[0]/2),Math.ceil(m[1]/2)],I=tn();return`
|
||
|
vec4 `+l+`(int index) {
|
||
|
vec2 uv = packedUVfrom1D(
|
||
|
`+g[0]+", "+g[1]+`, index);
|
||
|
return `+I.texture2D+"("+p+`, uv);
|
||
|
}
|
||
|
`}function mi(f){var p=f.name,l="get"+p.charAt(0).toUpperCase()+p.slice(1);if(f.shapeInfo.isUniform)return`
|
||
|
float `+l+`(int index) {
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var m=f.shapeInfo.texShape,g=m[0],I=m[1];if(I===1&&g===1)return`
|
||
|
float `+l+`(int index) {
|
||
|
return sampleTexture(`+p+`, halfCR);
|
||
|
}
|
||
|
`;var R=In(p);return I===1?`
|
||
|
float `+l+`(int index) {
|
||
|
vec2 uv = vec2(0.5, (float(index + `+R+") + 0.5) / "+g+`.0);
|
||
|
return sampleTexture(`+p+`, uv);
|
||
|
}
|
||
|
`:g===1?`
|
||
|
float `+l+`(int index) {
|
||
|
vec2 uv = vec2((float(index + `+R+") + 0.5) / "+I+`.0, 0.5);
|
||
|
return sampleTexture(`+p+`, uv);
|
||
|
}
|
||
|
`:`
|
||
|
float `+l+`(int index) {
|
||
|
vec2 uv = uvFromFlat(`+g+", "+I+", index + "+R+`);
|
||
|
return sampleTexture(`+p+`, uv);
|
||
|
}
|
||
|
`}function Ga(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=f.shapeInfo.texShape,I=g[0],R=g[1],z=tn();if(g!=null&&i.util.arraysEqual(p,g))return`
|
||
|
vec4 `+m+`(int row, int col) {
|
||
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+R+".0, "+I+`.0);
|
||
|
|
||
|
return `+z.texture2D+"("+l+`, uv);
|
||
|
}
|
||
|
`;var L=[Math.ceil(g[0]/2),Math.ceil(g[1]/2)],G=Math.ceil(p[1]/2);return`
|
||
|
vec4 `+m+`(int row, int col) {
|
||
|
vec2 uv = packedUVfrom2D(`+G+", "+L[0]+", "+L[1]+`, row, col);
|
||
|
return `+z.texture2D+"("+l+`, uv);
|
||
|
}
|
||
|
`}function ja(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=f.shapeInfo.texShape;if(g!=null&&i.util.arraysEqual(p,g)){var I=g[0],R=g[1];return`
|
||
|
float `+m+`(int row, int col) {
|
||
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+R+".0, "+I+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}var z=i.util.squeezeShape(p),L=z.newShape,G=z.keptDims,Z=L;if(Z.length<p.length){var be=qa(f,Z),Ce=["row","col"];return`
|
||
|
`+Ea(be)+`
|
||
|
float `+m+`(int row, int col) {
|
||
|
return `+m+"("+La(Ce,G)+`);
|
||
|
}
|
||
|
`}if(f.shapeInfo.isUniform)return`
|
||
|
float `+m+`(int row, int col) {
|
||
|
int index = round(dot(vec2(row, col), vec2(`+p[1]+`, 1)));
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var De=g[0],Te=g[1],Ge=In(l);return Te===1?`
|
||
|
float `+m+`(int row, int col) {
|
||
|
float index = dot(vec3(row, col, `+Ge+"), vec3("+p[1]+`, 1, 1));
|
||
|
vec2 uv = vec2(0.5, (index + 0.5) / `+De+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`:De===1?`
|
||
|
float `+m+`(int row, int col) {
|
||
|
float index = dot(vec3(row, col, `+Ge+"), vec3("+p[1]+`, 1, 1));
|
||
|
vec2 uv = vec2((index + 0.5) / `+Te+`.0, 0.5);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`:`
|
||
|
float `+m+`(int row, int col) {
|
||
|
// Explicitly use integer operations as dot() only works on floats.
|
||
|
int index = row * `+p[1]+" + col + "+Ge+`;
|
||
|
vec2 uv = uvFromFlat(`+De+", "+Te+`, index);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}function ai(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=f.shapeInfo.texShape,I=[Math.ceil(g[0]/2),Math.ceil(g[1]/2)];if(p[0]===1){var R=p.slice(1),z=[1,2],L=qa(f,R),G=["b","row","col"];return`
|
||
|
`+S(L)+`
|
||
|
vec4 `+m+`(int b, int row, int col) {
|
||
|
return `+m+"("+La(G,z)+`);
|
||
|
}
|
||
|
`}var Z=I[0],be=I[1],Ce=Math.ceil(p[2]/2),De=Ce*Math.ceil(p[1]/2),Te=tn();return`
|
||
|
vec4 `+m+`(int b, int row, int col) {
|
||
|
vec2 uv = packedUVfrom3D(
|
||
|
`+Z+", "+be+", "+De+", "+Ce+`, b, row, col);
|
||
|
return `+Te.texture2D+"("+l+`, uv);
|
||
|
}
|
||
|
`}function zi(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=p[1]*p[2],I=p[2],R=i.util.squeezeShape(p),z=R.newShape,L=R.keptDims,G=z;if(G.length<p.length){var Z=qa(f,G),be=["row","col","depth"];return`
|
||
|
`+Ea(Z)+`
|
||
|
float `+m+`(int row, int col, int depth) {
|
||
|
return `+m+"("+La(be,L)+`);
|
||
|
}
|
||
|
`}if(f.shapeInfo.isUniform)return`
|
||
|
float `+m+`(int row, int col, int depth) {
|
||
|
int index = round(dot(vec3(row, col, depth),
|
||
|
vec3(`+g+", "+I+`, 1)));
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var Ce=f.shapeInfo.texShape,De=Ce[0],Te=Ce[1],Ge=f.shapeInfo.flatOffset;if(Te===g&&Ge==null)return`
|
||
|
float `+m+`(int row, int col, int depth) {
|
||
|
float texR = float(row);
|
||
|
float texC = dot(vec2(col, depth), vec2(`+I+`, 1));
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+Te+".0, "+De+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;if(Te===I&&Ge==null)return`
|
||
|
float `+m+`(int row, int col, int depth) {
|
||
|
float texR = dot(vec2(row, col), vec2(`+p[1]+`, 1));
|
||
|
float texC = float(depth);
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+Te+".0, "+De+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;var Ze=In(l);return`
|
||
|
float `+m+`(int row, int col, int depth) {
|
||
|
// Explicitly use integer operations as dot() only works on floats.
|
||
|
int index = row * `+g+" + col * "+I+" + depth + "+Ze+`;
|
||
|
vec2 uv = uvFromFlat(`+De+", "+Te+`, index);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}function An(f){for(var p=f.shapeInfo.logicalShape,l=p.length,m=f.name,g="get"+m.charAt(0).toUpperCase()+m.slice(1),I=f.shapeInfo.texShape,R=[Math.ceil(I[0]/2),Math.ceil(I[1]/2)],z=R[0],L=R[1],G=Math.ceil(p[l-1]/2),Z=G*Math.ceil(p[l-2]/2),be="int b, int row, int col",Ce="b * "+Z+" + (row / 2) * "+G+" + (col / 2)",De=2;De<l-1;De++)be="int b"+De+", "+be,Z*=p[l-De-1],Ce="b"+De+" * "+Z+" + "+Ce;var Te=tn();return`
|
||
|
vec4 `+g+"("+be+`) {
|
||
|
int index = `+Ce+`;
|
||
|
int texR = index / `+L+`;
|
||
|
int texC = index - texR * `+L+`;
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+L+", "+z+`);
|
||
|
return `+Te.texture2D+"("+m+`, uv);
|
||
|
}
|
||
|
`}function ba(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=p[3],I=p[2]*g,R=p[1]*I,z=i.util.squeezeShape(p),L=z.newShape,G=z.keptDims;if(L.length<p.length){var Z=qa(f,L),be=["row","col","depth","depth2"];return`
|
||
|
`+Ea(Z)+`
|
||
|
float `+m+`(int row, int col, int depth, int depth2) {
|
||
|
return `+m+"("+La(be,G)+`);
|
||
|
}
|
||
|
`}if(f.shapeInfo.isUniform)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2) {
|
||
|
int index = round(dot(vec4(row, col, depth, depth2),
|
||
|
vec4(`+R+", "+I+", "+g+`, 1)));
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var Ce=f.shapeInfo.flatOffset,De=f.shapeInfo.texShape,Te=De[0],Ge=De[1];if(Ge===R&&Ce==null)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2) {
|
||
|
float texR = float(row);
|
||
|
float texC =
|
||
|
dot(vec3(col, depth, depth2),
|
||
|
vec3(`+I+", "+g+`, 1));
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+Ge+".0, "+Te+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;if(Ge===g&&Ce==null)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2) {
|
||
|
float texR = dot(vec3(row, col, depth),
|
||
|
vec3(`+p[1]*p[2]+", "+p[2]+`, 1));
|
||
|
float texC = float(depth2);
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+Ge+".0, "+Te+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;var Ze=In(l);return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2) {
|
||
|
// Explicitly use integer operations as dot() only works on floats.
|
||
|
int index = row * `+R+" + col * "+I+` +
|
||
|
depth * `+g+` + depth2;
|
||
|
vec2 uv = uvFromFlat(`+Te+", "+Ge+", index + "+Ze+`);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}function qi(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=p[4],I=p[3]*g,R=p[2]*I,z=p[1]*R,L=i.util.squeezeShape(p),G=L.newShape,Z=L.keptDims;if(G.length<p.length){var be=qa(f,G),Ce=["row","col","depth","depth2","depth3"];return`
|
||
|
`+Ea(be)+`
|
||
|
float `+m+`(int row, int col, int depth, int depth2, int depth3) {
|
||
|
return `+m+"("+La(Ce,Z)+`);
|
||
|
}
|
||
|
`}if(f.shapeInfo.isUniform)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2, int depth3) {
|
||
|
float index = dot(
|
||
|
vec4(row, col, depth, depth2),
|
||
|
vec4(`+z+", "+R+", "+I+", "+g+`)) +
|
||
|
depth3;
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var De=f.shapeInfo.flatOffset,Te=f.shapeInfo.texShape,Ge=Te[0],Ze=Te[1];if(Ze===z&&De==null)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2, int depth3) {
|
||
|
int texR = row;
|
||
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
||
|
vec4(`+R+", "+I+", "+g+`, 1));
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+Ze+".0, "+Ge+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;if(Ze===g&&De==null)return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2, int depth3) {
|
||
|
float texR = dot(
|
||
|
vec4(row, col, depth, depth2),
|
||
|
vec4(`+p[1]*p[2]*p[3]+`,
|
||
|
`+p[2]*p[3]+", "+p[3]+`, 1));
|
||
|
int texC = depth3;
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+Ze+".0, "+Ge+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;var s=In(l);return`
|
||
|
float `+m+`(int row, int col, int depth, int depth2, int depth3) {
|
||
|
// Explicitly use integer operations as dot() only works on floats.
|
||
|
int index = row * `+z+" + col * "+R+" + depth * "+I+` +
|
||
|
depth2 * `+g+" + depth3 + "+s+`;
|
||
|
vec2 uv = uvFromFlat(`+Ge+", "+Ze+`, index);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}function yi(f){var p=f.shapeInfo.logicalShape,l=f.name,m="get"+l.charAt(0).toUpperCase()+l.slice(1),g=i.util.squeezeShape(p),I=g.newShape,R=g.keptDims;if(I.length<p.length){var z=qa(f,I),L=["row","col","depth","depth2","depth3","depth4"];return`
|
||
|
`+Ea(z)+`
|
||
|
float `+m+`(int row, int col, int depth,
|
||
|
int depth2, int depth3, int depth4) {
|
||
|
return `+m+"("+La(L,R)+`);
|
||
|
}
|
||
|
`}var G=p[5],Z=p[4]*G,be=p[3]*Z,Ce=p[2]*be,De=p[1]*Ce;if(f.shapeInfo.isUniform)return`
|
||
|
float `+m+`(int row, int col, int depth,
|
||
|
int depth2, int depth3, int depth4) {
|
||
|
int index = round(dot(
|
||
|
vec4(row, col, depth, depth2),
|
||
|
vec4(`+De+", "+Ce+", "+be+", "+Z+`)) +
|
||
|
dot(
|
||
|
vec2(depth3, depth4),
|
||
|
vec2(`+G+`, 1)));
|
||
|
`+ii(f)+`
|
||
|
}
|
||
|
`;var Te=f.shapeInfo.flatOffset,Ge=f.shapeInfo.texShape,Ze=Ge[0],s=Ge[1];if(s===De&&Te==null)return`
|
||
|
float `+m+`(int row, int col, int depth,
|
||
|
int depth2, int depth3, int depth4) {
|
||
|
int texR = row;
|
||
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
||
|
vec4(`+Ce+", "+be+", "+Z+", "+G+`)) +
|
||
|
float(depth4);
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+s+".0, "+Ze+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;if(s===G&&Te==null)return`
|
||
|
float `+m+`(int row, int col, int depth,
|
||
|
int depth2, int depth3, int depth4) {
|
||
|
float texR = dot(vec4(row, col, depth, depth2),
|
||
|
vec4(`+p[1]*p[2]*p[3]*p[4]+`,
|
||
|
`+p[2]*p[3]*p[4]+`,
|
||
|
`+p[3]*p[4]+`,
|
||
|
`+p[4]+`)) + float(depth3);
|
||
|
int texC = depth4;
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
||
|
vec2(`+s+".0, "+Ze+`.0);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`;var u=In(l);return`
|
||
|
float `+m+`(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 * `+De+" + col * "+Ce+" + depth * "+be+` +
|
||
|
depth2 * `+Z+" + depth3 * "+G+" + depth4 + "+u+`;
|
||
|
vec2 uv = uvFromFlat(`+Ze+", "+s+`, index);
|
||
|
return sampleTexture(`+l+`, uv);
|
||
|
}
|
||
|
`}function ii(f){var p=f.name,l=i.util.sizeFromShape(f.shapeInfo.logicalShape);return l<2?"return "+p+";":`
|
||
|
for (int i = 0; i < `+l+`; i++) {
|
||
|
if (i == index) {
|
||
|
return `+p+`[i];
|
||
|
}
|
||
|
}
|
||
|
`}function qr(f,p){var l=f.name,m=l.charAt(0).toUpperCase()+l.slice(1),g="get"+m+"AtOutCoords",I=f.shapeInfo.logicalShape.length,R=p.logicalShape.length,z=ma(f.shapeInfo.logicalShape,p.logicalShape),L=nn(R),G=R-I,Z,be=["x","y","z","w","u","v"];I===0?Z="":R<2&&z.length>=1?Z="coords = 0;":Z=z.map(function(o){return"coords."+be[o+G]+" = 0;"}).join(`
|
||
|
`);var Ce="";R<2&&I>0?Ce="coords":Ce=f.shapeInfo.logicalShape.map(function(o,h){return"coords."+be[h+G]}).join(", ");var De="return outputValue;",Te=i.util.sizeFromShape(f.shapeInfo.logicalShape),Ge=Te===1,Ze=i.util.sizeFromShape(p.logicalShape),s=Ze===1;if(I===1&&!Ge&&!s)De=`
|
||
|
return vec4(outputValue.xy, outputValue.xy);
|
||
|
`;else if(Ge&&!s)R===1?De=`
|
||
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
||
|
`:De=`
|
||
|
return vec4(outputValue.x);
|
||
|
`;else if(z.length){var u=I-2,r=I-1;z.indexOf(u)>-1&&z.indexOf(r)>-1?De="return vec4(outputValue.x);":z.indexOf(u)>-1?De="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":z.indexOf(r)>-1&&(De="return vec4(outputValue.xx, outputValue.zz);")}return`
|
||
|
vec4 `+g+`() {
|
||
|
`+L+` coords = getOutputCoords();
|
||
|
`+Z+`
|
||
|
vec4 outputValue = get`+m+"("+Ce+`);
|
||
|
`+De+`
|
||
|
}
|
||
|
`}function Io(f,p){var l=f.name,m=l.charAt(0).toUpperCase()+l.slice(1),g="get"+m+"AtOutCoords",I=p.texShape,R=f.shapeInfo.texShape,z=f.shapeInfo.logicalShape.length,L=p.logicalShape.length;if(!f.shapeInfo.isUniform&&z===L&&f.shapeInfo.flatOffset==null&&i.util.arraysEqual(R,I))return`
|
||
|
float `+g+`() {
|
||
|
return sampleTexture(`+l+`, resultUV);
|
||
|
}
|
||
|
`;var G=nn(L),Z=ma(f.shapeInfo.logicalShape,p.logicalShape),be=L-z,Ce,De=["x","y","z","w","u","v"];z===0?Ce="":L<2&&Z.length>=1?Ce="coords = 0;":Ce=Z.map(function(Ge){return"coords."+De[Ge+be]+" = 0;"}).join(`
|
||
|
`);var Te="";return L<2&&z>0?Te="coords":Te=f.shapeInfo.logicalShape.map(function(Ge,Ze){return"coords."+De[Ze+be]}).join(", "),`
|
||
|
float `+g+`() {
|
||
|
`+G+` coords = getOutputCoords();
|
||
|
`+Ce+`
|
||
|
return get`+m+"("+Te+`);
|
||
|
}
|
||
|
`}function nn(f){if(f<=1)return"int";if(f===2)return"ivec2";if(f===3)return"ivec3";if(f===4)return"ivec4";if(f===5)return"ivec5";if(f===6)return"ivec6";throw Error("GPU for rank "+f+" is not yet supported")}function qa(f,p){var l=JSON.parse(JSON.stringify(f));return l.shapeInfo.logicalShape=p,l}function La(f,p){return p.map(function(l){return f[l]}).join(", ")}var Ki=function(){function f(p,l,m,g){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,i.util.assert(p.length>2,function(){return"Packed arg"+(m.charAt(0).toUpperCase()+m.slice(1))+" supports only inputs with rank above 2."});var I=p[p.length-1],R=Math.ceil(I/l);this.outputShape=p.slice(0,-1),R>1&&this.outputShape.push(R),g||this.variableNames.push("bestIndicesA");var z=this.outputShape,L=z.length,G=nn(L),Z=Vr("coords",L),be,Ce;if(R===1){Ce=L+1;var De=nn(Ce);be=`
|
||
|
`+De+" sourceLocR = "+De+"("+Z.join()+`, 0);
|
||
|
++`+Z[L-1]+`;
|
||
|
`+De+" sourceLocG = "+De+"("+Z.join()+`, 0);
|
||
|
++`+Z[L-2]+`;
|
||
|
`+De+" sourceLocA = "+De+"("+Z.join()+`, 0);
|
||
|
--`+Z[L-1]+`;
|
||
|
`+De+" sourceLocB = "+De+"("+Z.join()+`, 0);
|
||
|
--`+Z[L-2]+";"}else Ce=L,be=`
|
||
|
`+G+` sourceLocR = coords;
|
||
|
++`+Z[L-1]+`;
|
||
|
`+G+` sourceLocG = coords;
|
||
|
++`+Z[L-2]+`;
|
||
|
`+G+` sourceLocA = coords;
|
||
|
--`+Z[L-1]+`;
|
||
|
`+G+` sourceLocB = coords;
|
||
|
--`+Z[L-2]+";";var Te=["x","y","z","w","u","v"].slice(0,Ce),Ge="."+Te[Ce-1],Ze=Te.map(function(q){return"int "+q}),s=Vr("sourceLocR",Ce-1).concat("inIdx.r"),u=Vr("sourceLocG",Ce-1).concat("inIdx.g"),r=Vr("sourceLocB",Ce-1).concat("inIdx.b"),o=Vr("sourceLocA",Ce-1).concat("inIdx.a"),h=m==="max"?"greaterThan":"lessThan",b=g?"":`
|
||
|
inIdx = round(vec4(getBestIndicesAChannel(`+s.join()+`),
|
||
|
getBestIndicesAChannel(`+u.join()+`),
|
||
|
getBestIndicesAChannel(`+r.join()+`),
|
||
|
getBestIndicesAChannel(`+o.join()+")));",T=`vec4(
|
||
|
getAChannel(`+s.join()+`),
|
||
|
hasNextCol ? getAChannel(`+u.join()+`) : 0.,
|
||
|
hasNextRow ? getAChannel(`+r.join()+`) : 0.,
|
||
|
hasNextRow && hasNextCol ? getAChannel(`+o.join()+") : 0.)",M=g?"":`
|
||
|
float getBestIndicesAChannel(`+Ze.join()+`) {
|
||
|
return getChannel(getBestIndicesA(`+Te.join()+`),
|
||
|
vec2(`+Te.slice(-2).join()+`));
|
||
|
}`;this.userCode=`
|
||
|
float getAChannel(`+Ze.join()+`) {
|
||
|
return getChannel(getA(`+Te.join()+`),
|
||
|
vec2(`+Te.slice(-2).join()+`));
|
||
|
}
|
||
|
`+M+`
|
||
|
void main() {
|
||
|
`+G+` coords = getOutputCoords();
|
||
|
bool hasNextCol = `+Z[L-1]+" < "+(z[L-1]-1)+`;
|
||
|
bool hasNextRow = `+Z[L-2]+" < "+(z[L-2]-1)+`;
|
||
|
`+be+`
|
||
|
ivec4 srcIdx = ivec4(sourceLocR`+Ge+", sourceLocG"+Ge+`,
|
||
|
sourceLocB`+Ge+", sourceLocA"+Ge+") * "+l+`;
|
||
|
ivec4 inIdx = srcIdx;
|
||
|
vec4 bestIndex = vec4(inIdx);
|
||
|
vec4 bestValue = `+T+`;
|
||
|
|
||
|
for (int i = 0; i < `+l+`; i++) {
|
||
|
inIdx = srcIdx;
|
||
|
`+b+`
|
||
|
vec4 candidate = `+T+`;
|
||
|
bvec4 nan = isnan(candidate);
|
||
|
bvec4 replace = bvec4(
|
||
|
vec4(`+h+`(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);
|
||
|
}
|
||
|
`}return f}(),oi=function(){function f(p){this.variableNames=["dy"],this.outputShape=p.inShape;var l=p.filterHeight,m=p.filterWidth,g=p.strideHeight,I=p.strideWidth,R=p.dilationHeight,z=p.dilationWidth,L=p.effectiveFilterHeight,G=p.effectiveFilterWidth,Z=L-1-p.padInfo.top,be=G-1-p.padInfo.left,Ce=1/(l*m);this.userCode=`
|
||
|
const ivec2 pads = ivec2(`+Z+", "+be+`);
|
||
|
const float avgMultiplier = float(`+Ce+`);
|
||
|
|
||
|
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 += `+R+`) {
|
||
|
float dyR = float(dyRCorner + wR) / `+g+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 || fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
for (int wC = 0; wC < `+G+`;
|
||
|
wC+= `+z+`) {
|
||
|
float dyC = float(dyCCorner + wC) / `+I+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
float dyValue = getDy(b, idyR, idyC, d);
|
||
|
|
||
|
dotProd += dyValue * avgMultiplier;
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),Pi=function(){function f(p){this.variableNames=["dy"],this.outputShape=p.inShape;var l=p.filterDepth,m=p.filterHeight,g=p.filterWidth,I=p.strideDepth,R=p.strideHeight,z=p.strideWidth,L=p.dilationDepth,G=p.dilationHeight,Z=p.dilationWidth,be=p.effectiveFilterDepth,Ce=p.effectiveFilterHeight,De=p.effectiveFilterWidth,Te=be-1-p.padInfo.front,Ge=Ce-1-p.padInfo.top,Ze=De-1-p.padInfo.left,s=1/(l*m*g);this.userCode=`
|
||
|
const ivec3 pads = ivec3(`+Te+", "+Ge+", "+Ze+`);
|
||
|
const float avgMultiplier = float(`+s+`);
|
||
|
|
||
|
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 < `+be+`;
|
||
|
wD += `+L+`) {
|
||
|
float dyD = float(dyDCorner + wD) / `+I+`.0;
|
||
|
|
||
|
if (dyD < 0.0 || dyD >= `+p.outDepth+`.0 || fract(dyD) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyD = int(dyD);
|
||
|
|
||
|
for (int wR = 0; wR < `+Ce+`;
|
||
|
wR += `+G+`) {
|
||
|
float dyR = float(dyRCorner + wR) / `+R+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 ||
|
||
|
fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
for (int wC = 0; wC < `+De+`;
|
||
|
wC += `+Z+`) {
|
||
|
float dyC = float(dyCCorner + wC) / `+z+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
||
|
|
||
|
dotProd += dyValue * avgMultiplier;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),no=`
|
||
|
if (isnan(a)) return a;
|
||
|
if (isnan(b)) return b;
|
||
|
`,mo=`
|
||
|
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;
|
||
|
}
|
||
|
`,Ka=`
|
||
|
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);
|
||
|
`,ao="return float(a == b);",Ko="return float(a < b);",No="return float(a <= b);",Co="return float(a > b);",io="return float(a >= b);",ia="return float(a >= 1.0 && b >= 1.0);",Pr="return float(a >= 1.0 || b >= 1.0);",oa=no+`
|
||
|
return max(a, b);
|
||
|
`,Xa=no+`
|
||
|
return min(a, b);
|
||
|
`,Qn=`if (b == 0.0) return NAN;
|
||
|
return mod(a, b);`,oo="return (b >= 1.0) ? a : a * (b + 1.0);",ka="return (a < 0.) ? b * a : a;",vn=function(){function f(p,l,m){this.variableNames=["A","B"],this.outputShape=i.backend_util.assertAndGetBroadcastShape(l,m),this.userCode=`
|
||
|
float binaryOperation(float a, float b) {
|
||
|
`+p+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
float a = getAAtOutCoords();
|
||
|
float b = getBAtOutCoords();
|
||
|
setOutput(binaryOperation(a, b));
|
||
|
}
|
||
|
`}return f}(),Bi=`
|
||
|
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;
|
||
|
`,yo=`
|
||
|
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);
|
||
|
`,vo=`
|
||
|
// 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));
|
||
|
`+Bi+`
|
||
|
return result;
|
||
|
`,Aa=`
|
||
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
||
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
||
|
`,go=`
|
||
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
||
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
||
|
`,To=`
|
||
|
return vec4(equal(a, b));
|
||
|
`,Rs=`
|
||
|
return vec4(lessThan(a, b));
|
||
|
`,Eo=`
|
||
|
return vec4(lessThanEqual(a, b));
|
||
|
`,As=`
|
||
|
return vec4(greaterThan(a, b));
|
||
|
`,Ds=`
|
||
|
return vec4(greaterThanEqual(a, b));
|
||
|
`,Xo=`
|
||
|
return vec4(
|
||
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
||
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
||
|
`,Ro=`
|
||
|
return min(
|
||
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
||
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
||
|
vec4(1.0));
|
||
|
`,Yo=`
|
||
|
vec4 result = vec4(max(a, b));
|
||
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
||
|
`+Bi+`
|
||
|
return result;
|
||
|
`,Ao=`
|
||
|
vec4 result = vec4(min(a, b));
|
||
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
||
|
`+Bi+`
|
||
|
return result;
|
||
|
`,Qo=`
|
||
|
vec4 result = mod(a, b);
|
||
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
||
|
`+Bi+`
|
||
|
return result;
|
||
|
`,vi=function(){function f(p,l,m,g){g===void 0&&(g=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=i.backend_util.assertAndGetBroadcastShape(l,m);var I=this.outputShape.length,R="";if(g)if(I===0||i.util.sizeFromShape(this.outputShape)===1)R=`
|
||
|
result.y = 0.;
|
||
|
result.z = 0.;
|
||
|
result.w = 0.;
|
||
|
`;else{var z=nn(I);if(R=`
|
||
|
`+z+` coords = getOutputCoords();
|
||
|
`,I===1)R+=`
|
||
|
result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
|
||
|
result.z = 0.;
|
||
|
result.w = 0.;
|
||
|
`;else{var L=Vr("coords",I);R+=`
|
||
|
bool nextRowOutOfBounds =
|
||
|
(`+L[I-2]+" + 1) >= "+this.outputShape[I-2]+`;
|
||
|
bool nextColOutOfBounds =
|
||
|
(`+L[I-1]+" + 1) >= "+this.outputShape[I-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) {
|
||
|
`+p+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
vec4 a = getAAtOutCoords();
|
||
|
vec4 b = getBAtOutCoords();
|
||
|
|
||
|
vec4 result = binaryOperation(a, b);
|
||
|
`+R+`
|
||
|
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),Fs=function(){function f(p){this.variableNames=["A"],this.outputShape=p,this.userCode=`
|
||
|
uniform float minVal;
|
||
|
uniform float maxVal;
|
||
|
|
||
|
void main() {
|
||
|
float value = getAAtOutCoords();
|
||
|
if (isnan(value)) {
|
||
|
setOutput(value);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
setOutput(clamp(value, minVal, maxVal));
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p,l){var m=this;return function(g,I){m.minLoc==null&&(m.minLoc=g.getUniformLocationNoThrow(I,"minVal"),m.maxLoc=g.getUniformLocationNoThrow(I,"maxVal")),g.gl.uniform1f(m.minLoc,p),g.gl.uniform1f(m.maxLoc,l)}},f}(),tu=function(){function f(p){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p,this.userCode=`
|
||
|
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)));
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p,l){var m=this;return function(g,I){m.minLoc==null&&(m.minLoc=g.getUniformLocationNoThrow(I,"minVal"),m.maxLoc=g.getUniformLocationNoThrow(I,"maxVal")),g.gl.uniform1f(m.minLoc,p),g.gl.uniform1f(m.maxLoc,l)}},f}(),ps=function(){function f(p){this.variableNames=["real","imag"],this.outputShape=p,this.userCode=`
|
||
|
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))
|
||
|
);
|
||
|
}
|
||
|
`}return f}(),ru=function(){function f(p){this.variableNames=["x","dy"],this.outputShape=p.filterShape;var l=p.strideHeight,m=p.strideWidth,g=p.padInfo.top,I=p.padInfo.left,R=p.dataFormat==="channelsLast";this.userCode=`
|
||
|
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 < `+p.batchSize+`; b++) {
|
||
|
for (int yR = 0; yR < `+p.outHeight+`; yR++) {
|
||
|
int xR = wR + yR * `+l+" - "+g+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int yC = 0; yC < `+p.outWidth+`; yC++) {
|
||
|
int xC = wC + yC * `+m+" - "+I+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.inWidth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
if (`+R+`) {
|
||
|
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);
|
||
|
}
|
||
|
`}return f}(),Os=function(){function f(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var l=p.filterHeight,m=p.filterWidth,g=p.strideHeight,I=p.strideWidth,R=p.dataFormat==="channelsLast",z=l-1-p.padInfo.top,L=m-1-p.padInfo.left,G=R?1:2,Z=R?2:3,be=R?3:1;this.userCode=`
|
||
|
const ivec2 pads = ivec2(`+z+", "+L+`);
|
||
|
|
||
|
void main() {
|
||
|
ivec4 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int d1 = coords[`+be+`];
|
||
|
|
||
|
ivec2 dyCorner = ivec2(coords[`+G+"], coords["+Z+`]) - 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 < `+l+`; wR++) {
|
||
|
float dyR = float(dyRCorner + wR) / `+g+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 || fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
int wRPerm = `+l+` - 1 - wR;
|
||
|
|
||
|
for (int wC = 0; wC < `+m+`; wC++) {
|
||
|
float dyC = float(dyCCorner + wC) / `+I+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
int wCPerm = `+m+` - 1 - wC;
|
||
|
|
||
|
for (int d2 = 0; d2 < `+p.outChannels+`; d2++) {
|
||
|
|
||
|
if (`+R+`) {
|
||
|
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);
|
||
|
}
|
||
|
`}return f}(),ds=function(){function f(p){this.variableNames=["x","dy"],this.outputShape=p.filterShape;var l=p.strideDepth,m=p.strideHeight,g=p.strideWidth,I=p.padInfo.front,R=p.padInfo.top,z=p.padInfo.left;this.userCode=`
|
||
|
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 < `+p.batchSize+`; b++) {
|
||
|
for (int yF = 0; yF < `+p.outDepth+`; yF++) {
|
||
|
int xF = wF + yF * `+l+" - "+I+`;
|
||
|
|
||
|
if (xF < 0 || xF >= `+p.inDepth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int yR = 0; yR < `+p.outHeight+`; yR++) {
|
||
|
int xR = wR + yR * `+m+" - "+R+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int yC = 0; yC < `+p.outWidth+`; yC++) {
|
||
|
int xC = wC + yC * `+g+" - "+z+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.inWidth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
||
|
float xValue = getX(b, xF, xR, xC, d1);
|
||
|
dotProd += (xValue * dyValue);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),Ms=function(){function f(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var l=p.filterDepth,m=p.filterHeight,g=p.filterWidth,I=p.strideDepth,R=p.strideHeight,z=p.strideWidth,L=l-1-p.padInfo.front,G=m-1-p.padInfo.top,Z=g-1-p.padInfo.left;this.userCode=`
|
||
|
const ivec3 pads = ivec3(`+L+", "+G+", "+Z+`);
|
||
|
|
||
|
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 < `+l+`; wF++) {
|
||
|
float dyF = float(dyFCorner + wF) / `+I+`.0;
|
||
|
|
||
|
if (dyF < 0.0 || dyF >= `+p.outDepth+`.0 || fract(dyF) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyF = int(dyF);
|
||
|
|
||
|
int wFPerm = `+l+` - 1 - wF;
|
||
|
|
||
|
for (int wR = 0; wR < `+m+`; wR++) {
|
||
|
float dyR = float(dyRCorner + wR) / `+R+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 ||
|
||
|
fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
int wRPerm = `+m+` - 1 - wR;
|
||
|
|
||
|
for (int wC = 0; wC < `+g+`; wC++) {
|
||
|
float dyC = float(dyCCorner + wC) / `+z+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
int wCPerm = `+g+` - 1 - wC;
|
||
|
|
||
|
for (int d2 = 0; d2 < `+p.outChannels+`; d2++) {
|
||
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
||
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
||
|
dotProd += xValue * wValue;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),Ls=function(){function f(p){this.variableNames=["x","dy"],this.outputShape=p.filterShape;var l=p.strideHeight,m=p.strideWidth,g=p.padInfo.top,I=p.padInfo.left,R=p.outChannels/p.inChannels;this.userCode=`
|
||
|
void main() {
|
||
|
ivec4 coords = getOutputCoords();
|
||
|
int wR = coords.x;
|
||
|
int wC = coords.y;
|
||
|
int d1 = coords.z;
|
||
|
int dm = coords.w;
|
||
|
int d2 = d1 * `+R+` + dm;
|
||
|
|
||
|
float dotProd = 0.0;
|
||
|
|
||
|
// TO DO: Vec4 over the batch size
|
||
|
for (int b = 0; b < `+p.batchSize+`; b++) {
|
||
|
for (int yR = 0; yR < `+p.outHeight+`; yR++) {
|
||
|
int xR = wR + yR * `+l+" - "+g+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int yC = 0; yC < `+p.outWidth+`; yC++) {
|
||
|
int xC = wC + yC * `+m+" - "+I+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.inWidth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
float dyValue = getDy(b, yR, yC, d2);
|
||
|
float xValue = getX(b, xR, xC, d1);
|
||
|
dotProd += (xValue * dyValue);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),nu=function(){function f(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var l=p.filterHeight,m=p.filterWidth,g=p.strideHeight,I=p.strideWidth,R=l-1-p.padInfo.top,z=m-1-p.padInfo.left,L=p.outChannels/p.inChannels;this.userCode=`
|
||
|
const ivec2 pads = ivec2(`+R+", "+z+`);
|
||
|
|
||
|
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 < `+l+`; wR++) {
|
||
|
float dyR = float(dyRCorner + wR) / `+g+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 || fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
int wRPerm = `+l+` - 1 - wR;
|
||
|
|
||
|
for (int wC = 0; wC < `+m+`; wC++) {
|
||
|
float dyC = float(dyCCorner + wC) / `+I+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
int wCPerm = `+m+` - 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);
|
||
|
}
|
||
|
`}return f}(),fs=function(){function f(p,l,m,g){l===void 0&&(l=!1),m===void 0&&(m=null),g===void 0&&(g=!1),this.variableNames=["x","W"],this.outputShape=p.outShape;var I=p.padInfo.top,R=p.padInfo.left,z=p.strideHeight,L=p.strideWidth,G=p.dilationHeight,Z=p.dilationWidth,be=p.filterHeight,Ce=p.filterWidth,De=Math.floor(p.inChannels/4)*4,Te=p.inChannels%4,Ge=p.dataFormat==="channelsLast",Ze=Ge?1:2,s=Ge?2:3,u=Ge?3:1,r="",o="";m&&(g?r=`float activation(float a) {
|
||
|
float b = getPreluActivationWeightsAtOutCoords();
|
||
|
`+m+`
|
||
|
}`:r=`
|
||
|
float activation(float x) {
|
||
|
`+m+`
|
||
|
}
|
||
|
`,o="result = activation(result);");var h=l?"result += getBiasAtOutCoords();":"";l&&this.variableNames.push("bias"),g&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
||
|
`+r+`
|
||
|
|
||
|
const ivec2 strides = ivec2(`+z+", "+L+`);
|
||
|
const ivec2 pads = ivec2(`+I+", "+R+`);
|
||
|
|
||
|
void main() {
|
||
|
ivec4 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int d2 = coords[`+u+`];
|
||
|
|
||
|
ivec2 xRCCorner =
|
||
|
ivec2(coords[`+Ze+"], coords["+s+`]) * 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 < `+be+`; wR++) {
|
||
|
int xR = xRCorner + wR * `+G+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+Ce+`; wC++) {
|
||
|
int xC = xCCorner + wC * `+Z+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.inWidth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int d1 = 0; d1 < `+De+`; 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 (`+Ge+`) {
|
||
|
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 (`+(Te===1)+`) {
|
||
|
|
||
|
if (`+Ge+`) {
|
||
|
dotProd +=
|
||
|
getX(batch, xR, xC, `+De+`) *
|
||
|
getW(wR, wC, `+De+`, d2);
|
||
|
} else {
|
||
|
dotProd +=
|
||
|
getX(batch, `+De+`, xR, xC) *
|
||
|
getW(wR, wC, `+De+`, d2);
|
||
|
}
|
||
|
|
||
|
} else if (`+(Te===2)+`) {
|
||
|
vec2 wValues = vec2(
|
||
|
getW(wR, wC, `+De+`, d2),
|
||
|
getW(wR, wC, `+De+` + 1, d2)
|
||
|
);
|
||
|
|
||
|
if (`+Ge+`) {
|
||
|
vec2 xValues = vec2(
|
||
|
getX(batch, xR, xC, `+De+`),
|
||
|
getX(batch, xR, xC, `+De+` + 1)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
} else {
|
||
|
vec2 xValues = vec2(
|
||
|
getX(batch, `+De+`, xR, xC),
|
||
|
getX(batch, `+De+` + 1, xR, xC)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
}
|
||
|
|
||
|
} else if (`+(Te===3)+`) {
|
||
|
vec3 wValues = vec3(
|
||
|
getW(wR, wC, `+De+`, d2),
|
||
|
getW(wR, wC, `+De+` + 1, d2),
|
||
|
getW(wR, wC, `+De+` + 2, d2)
|
||
|
);
|
||
|
|
||
|
if (`+Ge+`) {
|
||
|
vec3 xValues = vec3(
|
||
|
getX(batch, xR, xC, `+De+`),
|
||
|
getX(batch, xR, xC, `+De+` + 1),
|
||
|
getX(batch, xR, xC, `+De+` + 2)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
} else {
|
||
|
vec3 xValues = vec3(
|
||
|
getX(batch, `+De+`, xR, xC),
|
||
|
getX(batch, `+De+` + 1, xR, xC),
|
||
|
getX(batch, `+De+` + 2, xR, xC)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
float result = dotProd;
|
||
|
`+h+`
|
||
|
`+o+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),au=function(){function f(p){this.variableNames=["x","W"],this.outputShape=p.outShape;var l=p.padInfo.front,m=p.padInfo.top,g=p.padInfo.left,I=p.strideDepth,R=p.strideHeight,z=p.strideWidth,L=p.dilationDepth,G=p.dilationHeight,Z=p.dilationWidth,be=p.filterDepth,Ce=p.filterHeight,De=p.filterWidth,Te=Math.floor(p.inChannels/4)*4,Ge=p.inChannels%4;this.userCode=`
|
||
|
const ivec3 strides = ivec3(`+I+", "+R+", "+z+`);
|
||
|
const ivec3 pads = ivec3(`+l+", "+m+", "+g+`);
|
||
|
|
||
|
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 < `+be+`; wF++) {
|
||
|
int xF = xFCorner + wF * `+L+`;
|
||
|
|
||
|
if (xF < 0 || xF >= `+p.inDepth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wR = 0; wR < `+Ce+`; wR++) {
|
||
|
int xR = xRCorner + wR * `+G+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+De+`; wC++) {
|
||
|
int xC = xCCorner + wC * `+Z+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.inWidth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int d1 = 0; d1 < `+Te+`; 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 (`+(Ge===1)+`) {
|
||
|
dotProd +=
|
||
|
getX(batch, xF, xR, xC, `+Te+`) *
|
||
|
getW(wF, wR, wC, `+Te+`, d2);
|
||
|
} else if (`+(Ge===2)+`) {
|
||
|
vec2 xValues = vec2(
|
||
|
getX(batch, xF, xR, xC, `+Te+`),
|
||
|
getX(batch, xF, xR, xC, `+Te+` + 1)
|
||
|
);
|
||
|
vec2 wValues = vec2(
|
||
|
getW(wF, wR, wC, `+Te+`, d2),
|
||
|
getW(wF, wR, wC, `+Te+` + 1, d2)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
} else if (`+(Ge===3)+`) {
|
||
|
vec3 xValues = vec3(
|
||
|
getX(batch, xF, xR, xC, `+Te+`),
|
||
|
getX(batch, xF, xR, xC, `+Te+` + 1),
|
||
|
getX(batch, xF, xR, xC, `+Te+` + 2)
|
||
|
);
|
||
|
vec3 wValues = vec3(
|
||
|
getW(wF, wR, wC, `+Te+`, d2),
|
||
|
getW(wF, wR, wC, `+Te+` + 1, d2),
|
||
|
getW(wF, wR, wC, `+Te+` + 2, d2)
|
||
|
);
|
||
|
dotProd += dot(xValues, wValues);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),ms=function(){function f(p,l,m,g){l===void 0&&(l=!1),m===void 0&&(m=null),g===void 0&&(g=!1),this.variableNames=["x","W"],this.outputShape=p.outShape;var I=p.inHeight,R=p.inWidth,z=p.padInfo.top,L=p.padInfo.left,G=p.strideHeight,Z=p.strideWidth,be=p.dilationHeight,Ce=p.dilationWidth,De=p.filterHeight,Te=p.filterWidth,Ge=p.outChannels/p.inChannels,Ze="",s="";m&&(g?Ze=`float activation(float a) {
|
||
|
float b = getPreluActivationWeightsAtOutCoords();
|
||
|
`+m+`
|
||
|
}`:Ze=`
|
||
|
float activation(float x) {
|
||
|
`+m+`
|
||
|
}
|
||
|
`,s="result = activation(result);");var u=l?"result += getBiasAtOutCoords();":"";l&&this.variableNames.push("bias"),g&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
||
|
`+Ze+`
|
||
|
|
||
|
const ivec2 strides = ivec2(`+G+", "+Z+`);
|
||
|
const ivec2 pads = ivec2(`+z+", "+L+`);
|
||
|
|
||
|
void main() {
|
||
|
ivec4 coords = getOutputCoords();
|
||
|
int batch = coords.x;
|
||
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
||
|
int d2 = coords.w;
|
||
|
int d1 = d2 / `+Ge+`;
|
||
|
int q = d2 - d1 * `+Ge+`;
|
||
|
|
||
|
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 < `+De+`; wR++) {
|
||
|
int xR = xRCorner + wR * `+be+`;
|
||
|
|
||
|
if (xR < 0 || xR >= `+I+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+Te+`; wC++) {
|
||
|
int xC = xCCorner + wC * `+Ce+`;
|
||
|
|
||
|
if (xC < 0 || xC >= `+R+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
float xVal = getX(batch, xR, xC, d1);
|
||
|
float wVal = getW(wR, wC, d1, q);
|
||
|
dotProd += xVal * wVal;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
float result = dotProd;
|
||
|
`+u+`
|
||
|
`+s+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),Do=function(){function f(p,l,m,g){l===void 0&&(l=!1),m===void 0&&(m=null),g===void 0&&(g=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p.outShape;for(var I=p.inHeight,R=p.inWidth,z=p.padInfo.top,L=p.padInfo.left,G=p.strideHeight,Z=p.strideWidth,be=p.dilationHeight,Ce=p.dilationWidth,De=p.filterHeight,Te=p.filterWidth,Ge=Te,Ze="int xR; int xC; int xCOffset;",s=0;s<De;s++)for(var u=0;u<Te;u++)Ze+=`
|
||
|
vec4 xTexelR`+s+"C"+u*2+` = vec4(0.);
|
||
|
vec4 wR`+s+"C"+u+` = vec4(0.);
|
||
|
vec4 xR`+s+"C"+u+" = vec4(0.);";for(var s=0;s<De;s++)for(var r=0;r<Ge;r++){var u=r*2;if(Ze+=`
|
||
|
xR = xRCorner + `+s*be+`;
|
||
|
xC = xCCorner + `+u*Ce+`;
|
||
|
`,Z===1){if(u<Te&&(L%2===1?Ze+=`
|
||
|
xCOffset = xC + 1;
|
||
|
if(xR >= 0 && xR < `+I+" && xCOffset >= 0 && xCOffset < "+R+`) {
|
||
|
xTexelR`+s+"C"+u+` = getX(batch, xR, xCOffset, d1);
|
||
|
|
||
|
// Need to manually clear unused channels in case
|
||
|
// we're reading from recycled texture.
|
||
|
if(xCOffset + 1 >= `+R+`) {
|
||
|
xTexelR`+s+"C"+u+`.zw = vec2(0.);
|
||
|
}
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+u+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
xCOffset = xC + 1 - 2;
|
||
|
if(xR >= 0 && xR < `+I+" && xCOffset >= 0 && xCOffset < "+R+`) {
|
||
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
||
|
|
||
|
// Need to manually clear unused channels in case
|
||
|
// we're reading from recycled texture.
|
||
|
if(xCOffset + 1 >= `+R+`) {
|
||
|
previous.zw = vec2(0.);
|
||
|
}
|
||
|
|
||
|
xR`+s+"C"+u+" = vec4(previous.zw, xTexelR"+s+"C"+u+`.xy);
|
||
|
} else {
|
||
|
xR`+s+"C"+u+" = vec4(0, 0, xTexelR"+s+"C"+u+`.xy);
|
||
|
}
|
||
|
`:Ze+=`
|
||
|
if(xR >= 0 && xR < `+I+" && xC >= 0 && xC < "+R+`) {
|
||
|
xTexelR`+s+"C"+u+` = getX(batch, xR, xC, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+u+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
xR`+s+"C"+u+" = xTexelR"+s+"C"+u+`;
|
||
|
`,u+1<Te)){var o=L%2===0?i.util.nearestLargerEven(Ce):Ce;Ce%2===0&&L%2===1||Ce%2!==0&&L%2!==1?(Ze+=`
|
||
|
xCOffset = xC + `+L%2+" + "+o+`;
|
||
|
|
||
|
if(xR >= 0 && xR < `+I+` &&
|
||
|
xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
xTexelR`+s+"C"+(u+2)+` = getX(batch, xR, xCOffset, d1);
|
||
|
}
|
||
|
`,Ce>1&&(Ze+=`
|
||
|
xCOffset -= 2;
|
||
|
if(xR >= 0 && xR < `+I+` &&
|
||
|
xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
xTexelR`+s+"C"+u+` = getX(batch, xR, xCOffset, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+u+` = vec4(0.);
|
||
|
}
|
||
|
`),Ze+=`
|
||
|
xR`+s+"C"+(u+1)+` = vec4(
|
||
|
xTexelR`+s+"C"+u+".zw, xTexelR"+s+"C"+(u+2)+`.xy);
|
||
|
`):Ze+=`
|
||
|
xCOffset = xC + `+o+`;
|
||
|
|
||
|
if(xR >= 0 && xR < `+I+` &&
|
||
|
xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
xTexelR`+s+"C"+(u+2)+` = getX(batch, xR, xCOffset, d1);
|
||
|
}
|
||
|
|
||
|
xR`+s+"C"+(u+1)+" = xTexelR"+s+"C"+(u+2)+`;
|
||
|
`}}else u<Te&&(Ze+=`
|
||
|
if(xR >= 0 && xR < `+I+`) {
|
||
|
`,L%2===1?(Ze+=`
|
||
|
xCOffset = xC + 1 - `+Z+`;
|
||
|
if(xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
xTexelR`+s+"C"+u+` = getX(batch, xR, xCOffset, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+u+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
if(xC + 1 >= 0 && xC + 1 < `+R+`) {
|
||
|
xTexelR`+s+"C"+(u+2)+` = getX(batch, xR, xC + 1, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+(u+2)+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
xR`+s+"C"+u+` = vec4(
|
||
|
xTexelR`+s+"C"+u+".zw, xTexelR"+s+"C"+(u+2)+`.zw);
|
||
|
`,u+1<Te&&(Ze+=`
|
||
|
vec4 final = vec4(0.);
|
||
|
xCOffset = xC + 1 + `+Z+`;
|
||
|
if(xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
final = getX(batch, xR, xCOffset, d1);
|
||
|
}
|
||
|
xR`+s+"C"+(u+1)+" = vec4(xTexelR"+s+"C"+(u+2)+`.xy, final.xy);
|
||
|
`)):(Ze+=`
|
||
|
if(xC >= 0 && xC < `+R+`) {
|
||
|
xTexelR`+s+"C"+u+` = getX(batch, xR, xC, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+u+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
xCOffset = xC + `+Z+`;
|
||
|
if(xCOffset >= 0 && xCOffset < `+R+`) {
|
||
|
xTexelR`+s+"C"+(u+2)+` = getX(batch, xR, xCOffset, d1);
|
||
|
} else {
|
||
|
xTexelR`+s+"C"+(u+2)+` = vec4(0.);
|
||
|
}
|
||
|
|
||
|
xR`+s+"C"+u+` = vec4(
|
||
|
xTexelR`+s+"C"+u+".xy, xTexelR"+s+"C"+(u+2)+`.xy);
|
||
|
`,u+1<Te&&(Ze+=`
|
||
|
xR`+s+"C"+(u+1)+` = vec4(
|
||
|
xTexelR`+s+"C"+u+".zw, xTexelR"+s+"C"+(u+2)+`.zw);
|
||
|
`)),Ze+="}");u<Te&&(Ze+=`
|
||
|
vec4 wTexelR`+s+"C"+u+" = getW("+s+", "+u+`, d1, q);
|
||
|
wR`+s+"C"+u+" = vec4(wTexelR"+s+"C"+u+".xz, wTexelR"+s+"C"+u+`.xz);
|
||
|
`,u+1<Te&&(Ze+=`
|
||
|
vec4 wTexelR`+s+"C"+(u+1)+" = getW("+s+", "+(u+1)+`, d1, q);
|
||
|
wR`+s+"C"+(u+1)+` =
|
||
|
vec4(wTexelR`+s+"C"+(u+1)+".xz, wTexelR"+s+"C"+(u+1)+".xz);"))}for(var s=0;s<De;s++)for(var u=0;u<Te;u++)Ze+="dotProd += xR"+s+"C"+u+" * wR"+s+"C"+u+";";var h="",b="";m&&(g?h=`vec4 activation(vec4 a) {
|
||
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
||
|
`+m+`
|
||
|
}`:h=`vec4 activation(vec4 x) {
|
||
|
`+m+`
|
||
|
}`,b="result = activation(result);");var T=l?"result += getBiasAtOutCoords();":"";l&&this.variableNames.push("bias"),g&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
||
|
`+h+`
|
||
|
|
||
|
const ivec2 strides = ivec2(`+G+", "+Z+`);
|
||
|
const ivec2 pads = ivec2(`+z+", "+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.);
|
||
|
|
||
|
`+Ze+`
|
||
|
|
||
|
vec4 result = dotProd;
|
||
|
`+T+`
|
||
|
`+b+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),zs=function(){function f(p,l,m,g,I){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var R=p[0],z=p[1],L=p[2],G=p[3],Z=l[0],be=m[0],Ce=m[1];this.outputShape=[Z,be,Ce,G];var De=g==="bilinear"?1:0,Te=[z-1+".0",L-1+".0"],Ge=Te[0],Ze=Te[1],s=be>1?[""+(z-1)/(be-1),"(y2-y1) * height_ratio","y1*"+Ge+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+Ge],u=s[0],r=s[1],o=s[2],h=Ce>1?[""+(L-1)/(Ce-1),"(x2-x1) * width_ratio","x1*"+Ze+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+Ze],b=h[0],T=h[1],M=h[2];this.userCode=`
|
||
|
const float height_ratio = float(`+u+`);
|
||
|
const float width_ratio = float(`+b+`);
|
||
|
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 >= `+R+`) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
float height_scale = `+r+`;
|
||
|
float width_scale = `+T+`;
|
||
|
|
||
|
float in_y = `+o+`;
|
||
|
if( in_y < 0.0 || in_y > `+Ge+` ) {
|
||
|
setOutput(float(`+I+`));
|
||
|
return;
|
||
|
}
|
||
|
float in_x = `+M+`;
|
||
|
if( in_x < 0.0 || in_x > `+Ze+` ) {
|
||
|
setOutput(float(`+I+`));
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
||
|
if(`+De+` == 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);
|
||
|
}
|
||
|
}
|
||
|
`}return f}(),Zo=function(){function f(p,l,m){this.variableNames=["x"],this.outputShape=p;var g=p.length,I=l?"0.0":"getX("+xo(g,"coords")+")",R=p[p.length-1],z="",L="";l?(z=m?"end != "+(R-1):"end != 0",L=m?"end + 1":"end - 1"):(z=m?"end + pow2 < "+R:"end >= pow2",L=m?"end + pow2":"end - pow2"),this.userCode=`
|
||
|
uniform float index;
|
||
|
void main() {
|
||
|
`+nn(g)+` coords = getOutputCoords();
|
||
|
int end = `+ys(g,"coords")+`;
|
||
|
float val = `+I+`;
|
||
|
int pow2 = int(pow(2.0, index));
|
||
|
if (`+z+`) {
|
||
|
int idx = `+L+`;
|
||
|
`+ys(g,"coords")+` = idx;
|
||
|
val += getX(`+xo(g,"coords")+`);
|
||
|
}
|
||
|
setOutput(val);
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p){var l=this;return function(m,g){l.index==null&&(l.index=m.getUniformLocation(g,"index")),m.gl.uniform1f(l.index,p)}},f}();function xo(f,p){if(f===1)return""+p;if(f===2)return p+".x, "+p+".y";if(f===3)return p+".x, "+p+".y, "+p+".z";if(f===4)return p+".x, "+p+".y, "+p+".z, "+p+".w";throw Error("Cumulative sum for rank "+f+" is not yet supported")}function ys(f,p){if(f===1)return""+p;if(f===2)return p+".y";if(f===3)return p+".z";if(f===4)return p+".w";throw Error("Cumulative sum for rank "+f+" is not yet supported")}var Fo=function(){function f(p){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ae.DENSE;var l=nt(p),m=tn();this.outputShape=p,this.userCode=`
|
||
|
ivec3 outCoordsFromFlatIndex(int index) {
|
||
|
`+Rn(["r","c","d"],p)+`
|
||
|
return ivec3(r, c, d);
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
int index = 4 * (resTexRC.x * `+l[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);
|
||
|
}
|
||
|
|
||
|
`+m.output+` = result;
|
||
|
}
|
||
|
`}return f}(),Ps=function(){function f(p){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ae.DENSE;var l=nt(p),m=tn();this.outputShape=p,this.userCode=`
|
||
|
ivec3 outCoordsFromFlatIndex(int index) {
|
||
|
`+Rn(["r","c","d"],p)+`
|
||
|
return ivec3(r, c, d);
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
||
|
vec2(`+l[0]+", "+l[1]+`));
|
||
|
int index = 4 * (resTexRC.x * `+l[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));
|
||
|
}
|
||
|
|
||
|
`+m.output+` = result;
|
||
|
}
|
||
|
`}return f}(),Jo=function(){function f(p,l,m){this.variableNames=["x"],this.outputShape=[],this.outputShape=p,this.blockSize=l,this.dataFormat=m,this.userCode=`
|
||
|
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 / `+l+`;
|
||
|
int offset_h = imod(h, `+l+`);
|
||
|
int in_w = w / `+l+`;
|
||
|
int offset_w = imod(w, `+l+`);
|
||
|
int offset_d = (offset_h * `+l+` + offset_w) *
|
||
|
`+this.getOutputDepthSize()+`;
|
||
|
int in_d = d + offset_d;
|
||
|
|
||
|
float result = `+this.getInputSamplingString()+`;
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},f.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},f.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},f.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},f.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},f}(),_o=function(){function f(p){this.variableNames=["X"],this.outputShape=[p,p],this.userCode=`
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
|
||
|
setOutput(val);
|
||
|
}
|
||
|
`}return f}(),wo=function(){function f(p){this.variableNames=["A"],this.outTexUsage=w.DOWNLOAD;var l=tn();this.outputShape=p,this.userCode=`
|
||
|
`+aa+`
|
||
|
|
||
|
void main() {
|
||
|
float x = getAAtOutCoords();
|
||
|
`+l.output+` = encode_float(x);
|
||
|
}
|
||
|
`}return f}(),Bs=function(){function f(p){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=w.DOWNLOAD;var l=tn();this.outputShape=p,this.userCode=`
|
||
|
`+aa+`
|
||
|
|
||
|
void main() {
|
||
|
ivec3 coords = getOutputCoords();
|
||
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
||
|
`+l.output+` = encode_float(x);
|
||
|
}
|
||
|
`}return f}(),Ws=function(){function f(p,l,m){m===void 0&&(m=!1),this.variableNames=["A"];var g=tn(),I=l[0],R=l[1];this.outputShape=p;var z="result";m&&(z="floor(result * 255. + 0.5)"),this.userCode=`
|
||
|
`+Kn(p)+`
|
||
|
|
||
|
void main() {
|
||
|
ivec3 coords = getOutputCoords();
|
||
|
|
||
|
int flatIndex = getFlatIndex(coords);
|
||
|
int offset = imod(flatIndex, 4);
|
||
|
|
||
|
flatIndex = idiv(flatIndex, 4, 1.);
|
||
|
|
||
|
int r = flatIndex / `+R+`;
|
||
|
int c = imod(flatIndex, `+R+`);
|
||
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(`+R+".0, "+I+`.0);
|
||
|
vec4 values = `+g.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];
|
||
|
}
|
||
|
|
||
|
`+g.output+" = vec4("+z+`, 0., 0., 0.);
|
||
|
}
|
||
|
`}return f}(),vs=function(){function f(p,l,m){m===void 0&&(m=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var g=tn(),I=l[0],R=l[1];this.outputShape=p;var z="",L="result";m&&(L="floor(result * 255. + 0.5)");for(var G=0;G<=1;G++)for(var Z=0;Z<=1;Z++){var be=G*2+Z;z+=`
|
||
|
localCoords = coords;
|
||
|
if(localCoords[2] + `+Z+" < "+p[2]+`) {
|
||
|
localCoords[2] += `+Z+`;
|
||
|
if(localCoords[1] + `+G+" < "+p[1]+`) {
|
||
|
localCoords[1] += `+G+`;
|
||
|
|
||
|
flatIndex = getFlatIndex(localCoords);
|
||
|
offset = imod(flatIndex, 4);
|
||
|
|
||
|
flatIndex = idiv(flatIndex, 4, 1.);
|
||
|
|
||
|
r = flatIndex / `+R+`;
|
||
|
c = imod(flatIndex, `+R+`);
|
||
|
uv = (vec2(c, r) + halfCR) / vec2(`+R+".0, "+I+`.0);
|
||
|
values = `+g.texture2D+`(A, uv);
|
||
|
|
||
|
if(offset == 0) {
|
||
|
result[`+be+`] = values[0];
|
||
|
} else if(offset == 1) {
|
||
|
result[`+be+`] = values[1];
|
||
|
} else if(offset == 2) {
|
||
|
result[`+be+`] = values[2];
|
||
|
} else {
|
||
|
result[`+be+`] = values[3];
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
`}this.userCode=`
|
||
|
`+Kn(p)+`
|
||
|
|
||
|
void main() {
|
||
|
ivec3 coords = getOutputCoords();
|
||
|
|
||
|
vec4 result = vec4(0.);
|
||
|
int flatIndex, r, c, offset;
|
||
|
ivec3 localCoords;
|
||
|
vec2 uv;
|
||
|
vec4 values;
|
||
|
|
||
|
`+z+`
|
||
|
|
||
|
`+g.output+" = "+L+`;
|
||
|
}
|
||
|
`}return f}(),$o=function(){function f(p,l){this.outputShape=[],this.variableNames=["x"],this.outputShape=p,this.userCode=`
|
||
|
uniform float value;
|
||
|
void main() {
|
||
|
// Input can be obtained from uniform value.
|
||
|
setOutput(value);
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p){var l=this;return function(m,g){l.valueLoc==null&&(l.valueLoc=m.getUniformLocationNoThrow(g,"value")),m.gl.uniform1f(l.valueLoc,p)}},f}(),iu=function(){function f(p,l,m){this.variableNames=["A","indices"];var g=p.slice();g[m]=l,this.outputShape=g,this.rank=g.length;var I=nn(this.rank),R=ku(p,m);this.userCode=`
|
||
|
void main() {
|
||
|
`+I+` resRC = getOutputCoords();
|
||
|
setOutput(getA(`+R+`));
|
||
|
}
|
||
|
`}return f}();function ku(f,p){var l=f.length;if(l>4)throw Error("Gather for rank "+l+" is not yet supported");if(l===1)return"int(getIndices(resRC))";for(var m=["resRC.x","resRC.y","resRC.z","resRC.w"],g=[],I=0;I<f.length;I++)I===p?g.push("int(getIndices("+m[I]+"))"):g.push(""+m[I]);return g.join()}var ou=function(){function f(p,l,m){this.sliceDim=p,this.strides=l,this.variableNames=["x","indices"],this.outputShape=m;var g=nn(l.length),I=nn(m.length),R=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
||
|
`+g+" strides = "+g+"("+this.strides+`);
|
||
|
void main() {
|
||
|
`+I+` coords = getOutputCoords();
|
||
|
int flattenIndex = 0;
|
||
|
for (int j = 0; j < `+this.sliceDim+`; j++) {
|
||
|
int index = round(getIndices(coords[0], j));
|
||
|
flattenIndex += index * `+R+`;
|
||
|
}
|
||
|
setOutput(getX(flattenIndex, coords[1]));
|
||
|
}
|
||
|
`}return f}();function Oo(f){var p=tn(),l=p.version+`
|
||
|
precision highp float;
|
||
|
`+p.attribute+` vec3 clipSpacePos;
|
||
|
`+p.attribute+` vec2 uv;
|
||
|
`+p.varyingVs+` vec2 resultUV;
|
||
|
|
||
|
void main() {
|
||
|
gl_Position = vec4(clipSpacePos, 1);
|
||
|
resultUV = uv;
|
||
|
}`;return Zt(f,l)}function Mo(f){var p=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return Fa(f,p)}function gs(f){var p=new Uint16Array([0,1,2,2,1,3]);return Oa(f,p)}function es(f,p,l,m,g,I){Na(p,l);var R=Wa(f),z=f.TEXTURE_2D;return Qe(f,function(){return f.bindTexture(z,R)}),Qe(f,function(){return f.texParameteri(z,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE)}),Qe(f,function(){return f.texParameteri(z,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE)}),Qe(f,function(){return f.texParameteri(z,f.TEXTURE_MIN_FILTER,f.NEAREST)}),Qe(f,function(){return f.texParameteri(z,f.TEXTURE_MAG_FILTER,f.NEAREST)}),Qe(f,function(){return f.texImage2D(z,0,m,p,l,0,g,I,null)}),Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,null)}),R}function Si(f){return f.internalFormatFloat}function Lo(f,p,l,m){var g=ze(p,l),I=g[0],R=g[1];return es(f,I,R,Si(m),m.textureFormatFloat,f.FLOAT)}function zo(f){return f.internalFormatHalfFloat}function Xi(f,p,l,m){var g=ze(p,l),I=g[0],R=g[1];return es(f,I,R,zo(m),m.textureFormatFloat,m.textureTypeHalfFloat)}function ts(f){return f.downloadTextureFormat}function ne(f,p,l,m){var g=ze(p,l),I=g[0],R=g[1];return es(f,I,R,ts(m),f.RGBA,f.UNSIGNED_BYTE)}function ue(f){return f.internalFormatPackedFloat}function E(f,p,l,m){var g=tt(p,l),I=g[0],R=g[1];return es(f,I,R,ue(m),f.RGBA,f.FLOAT)}function F(f){return f.internalFormatPackedHalfFloat}function A(f,p,l,m){var g=tt(p,l),I=g[0],R=g[1];return es(f,I,R,F(m),f.RGBA,m.textureTypeHalfFloat)}function V(f,p,l){var m=0,g=3*4,I=3*4+2*4;Qe(f,function(){return f.bindBuffer(f.ARRAY_BUFFER,l)});var R=Ma(f,p,"clipSpacePos",l,3,I,m);return R&&Ma(f,p,"uv",l,2,I,g)}function oe(f,p,l,m,g,I){Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,p)});var R,z,L;g instanceof Uint8Array?(R=new Uint8Array(l*m*4),z=f.UNSIGNED_BYTE,L=f.RGBA):(R=new Float32Array(l*m*4),z=f.FLOAT,L=I.internalFormatPackedFloat),R.set(g),Qe(f,function(){return f.texImage2D(f.TEXTURE_2D,0,L,l,m,0,f.RGBA,z,R)}),Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,null)})}function ee(f,p,l){Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,p)}),l.data instanceof Uint8Array?Qe(f,function(){return f.texImage2D(f.TEXTURE_2D,0,f.RGBA,l.width,l.height,0,f.RGBA,f.UNSIGNED_BYTE,l.data)}):Qe(f,function(){return f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,l)}),Qe(f,function(){return f.bindTexture(f.TEXTURE_2D,null)})}function _e(f,p,l,m){var g=f.createBuffer();Qe(f,function(){return f.bindBuffer(f.PIXEL_PACK_BUFFER,g)});var I=4,R=4,z=I*R*p*l;return Qe(f,function(){return f.bufferData(f.PIXEL_PACK_BUFFER,z,f.STREAM_READ)}),Qe(f,function(){return f.readPixels(0,0,l,p,f.RGBA,f.FLOAT,0)}),Qe(f,function(){return f.bindBuffer(f.PIXEL_PACK_BUFFER,null)}),g}function ce(f,p,l){var m=f,g=new Float32Array(l);return m.bindBuffer(m.PIXEL_PACK_BUFFER,p),m.getBufferSubData(m.PIXEL_PACK_BUFFER,0,g),m.bindBuffer(m.PIXEL_PACK_BUFFER,null),g}function de(f,p,l,m){var g=ze(p,l),I=g[0],R=g[1],z=4,L=new Uint8Array(W(p*l,z));return Qe(f,function(){return f.readPixels(0,0,I,R,m.downloadTextureFormat,f.UNSIGNED_BYTE,L)}),new Float32Array(L.buffer)}function ye(f,p,l,m,g,I,R,z){var L=f,G=new Float32Array(nr(I,R));return L.bindBuffer(L.PIXEL_PACK_BUFFER,p),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,G),L.bindBuffer(L.PIXEL_PACK_BUFFER,null),G}function ve(f,p,l){var m=new Float32Array(p*l*4);return Qe(f,function(){return f.readPixels(0,0,l,p,f.RGBA,f.FLOAT,m)}),m}var Re={__proto__:null,createVertexShader:Oo,createVertexBuffer:Mo,createIndexBuffer:gs,getInternalFormatForFloat32MatrixTexture:Si,createFloat32MatrixTexture:Lo,getInternalFormatForFloat16MatrixTexture:zo,createFloat16MatrixTexture:Xi,getInternalFormatForUnsignedBytesMatrixTexture:ts,createUnsignedBytesMatrixTexture:ne,getInternalFormatForPackedMatrixTexture:ue,createPackedMatrixTexture:E,getInternalFormatForFloat16PackedMatrixTexture:F,createFloat16PackedMatrixTexture:A,bindVertexProgramAttributeStreams:V,uploadDenseMatrixToTexture:oe,uploadPixelDataToTexture:ee,createBufferFromOutputTexture:_e,downloadFloat32MatrixFromBuffer:ce,downloadByteEncodedFloatMatrixFromOutputTexture:de,downloadPa
|
||
|
blockIndex = rc.y + `+b+`;
|
||
|
pos = rc.x + `+h+`;
|
||
|
|
||
|
if(blockIndex < `+p[1]+" && pos < "+p[0]+`) {
|
||
|
offsetY = int(blockIndex / (`+G+")) * "+z+" - "+Te+`;
|
||
|
d0 = offsetY + `+be+" * (pos / "+Ge+`);
|
||
|
|
||
|
if(d0 < `+l[u]+` && d0 >= 0) {
|
||
|
|
||
|
offsetX = int(mod(float(blockIndex), `+G+".) * "+R+". - "+De+`.);
|
||
|
d1 = offsetX + `+Z+" * (int(mod(float(pos), "+Ge+".) / "+I+`.));
|
||
|
|
||
|
if(d1 < `+l[r]+` && d1 >= 0) {
|
||
|
|
||
|
ch = int(mod(float(pos), `+I+`.));
|
||
|
|
||
|
if (`+s+`) {
|
||
|
innerDims = vec2(d1, ch);
|
||
|
result[`+(h*2+b)+`] = getChannel(
|
||
|
getA(d0, int(innerDims.x),
|
||
|
int(innerDims.y)), innerDims);
|
||
|
} else {
|
||
|
innerDims = vec2(d0, d1);
|
||
|
result[`+(h*2+b)+`] = 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;
|
||
|
|
||
|
`+o+`
|
||
|
|
||
|
`+Ze.output+` = result;
|
||
|
}
|
||
|
`}return f}(),et=function(){function f(p,l,m,g,I){this.variableNames=["x"],this.outputShape=[];var R=l,z=p[3]-1;this.outputShape=p;var L,G="float("+m+") + float("+g+") * sum";I===.5?L="inversesqrt("+G+")":I===1?L="1.0/("+G+")":L="exp(log("+G+") * float(-"+I+"));",this.userCode=`
|
||
|
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 = -`+R+"; j <= "+R+`; j++) {
|
||
|
int idx = d + j;
|
||
|
if (idx >= 0 && idx <= `+z+`) {
|
||
|
float z = getX(b, r, c, idx);
|
||
|
sum += z * z;
|
||
|
}
|
||
|
}
|
||
|
float val = x * `+L+`;
|
||
|
setOutput(val);
|
||
|
}
|
||
|
`}return f}(),gt=function(){function f(p,l,m,g,I){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=p,this.depth=p[3],this.depthRadius=l,this.bias=m,this.alpha=g,this.beta=I,this.userCode=`
|
||
|
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 - `+l+`)));
|
||
|
int depthEnd = int(min(float(`+this.depth+`),
|
||
|
float(d + `+l+` + 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(`+g+") * norm + float("+m+`);
|
||
|
|
||
|
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(`+g+`)
|
||
|
* float(`+I+`)
|
||
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
||
|
/ norm;
|
||
|
if (k == d) {
|
||
|
dyi += pow(norm, -1.0 * `+I+`);
|
||
|
}
|
||
|
if (k == coords[3]) {
|
||
|
dyi *= getDy(b, r, c, d);
|
||
|
result += dyi;
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),lt=function(){function f(p,l,m,g,I){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var R=l,z=p[3]-1;this.outputShape=p;var L,G="float("+m+") + float("+g+") * sum";I===.5?L="inversesqrt("+G+")":I===1?L="1.0/("+G+")":L="exp(log("+G+") * float(-"+I+"));",this.userCode=`
|
||
|
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 - `+R+`;
|
||
|
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 = - `+R+"; j <= "+R+`; j++) {
|
||
|
ivec2 idx = depth + j;
|
||
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
||
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+z+`));
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
`}return f}(),_t=function(){function f(p){this.variableNames=["dy","maxPos"],this.outputShape=p.inShape;var l=p.strideHeight,m=p.strideWidth,g=p.dilationHeight,I=p.effectiveFilterHeight,R=p.effectiveFilterWidth,z=I-1-p.padInfo.top,L=R-1-p.padInfo.left,G=I*R-1;this.userCode=`
|
||
|
const ivec2 pads = ivec2(`+z+", "+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 < `+I+`;
|
||
|
wR += `+g+`) {
|
||
|
float dyR = float(dyRCorner + wR) / `+l+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 || fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
for (int wC = 0; wC < `+R+`; wC++) {
|
||
|
float dyC = float(dyCCorner + wC) / `+m+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
float dyValue = getDy(b, idyR, idyC, d);
|
||
|
int maxPosValue = `+G+` - int(getMaxPos(b, idyR, idyC, d));
|
||
|
|
||
|
// Get the current value, check it against the value from the
|
||
|
// position matrix.
|
||
|
int curPosValue = wR * `+R+` + wC;
|
||
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
||
|
|
||
|
dotProd += dyValue * mask;
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),At=function(){function f(p){this.variableNames=["dy","maxPos"],this.outputShape=p.inShape;var l=p.strideDepth,m=p.strideHeight,g=p.strideWidth,I=p.dilationDepth,R=p.dilationHeight,z=p.dilationWidth,L=p.effectiveFilterDepth,G=p.effectiveFilterHeight,Z=p.effectiveFilterWidth,be=L-1-p.padInfo.front,Ce=G-1-p.padInfo.top,De=Z-1-p.padInfo.left,Te=L*G*Z-1;this.userCode=`
|
||
|
const ivec3 pads = ivec3(`+be+", "+Ce+", "+De+`);
|
||
|
|
||
|
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 += `+I+`) {
|
||
|
float dyD = float(dyDCorner + wD) / `+l+`.0;
|
||
|
|
||
|
if (dyD < 0.0 || dyD >= `+p.outDepth+`.0 || fract(dyD) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyD = int(dyD);
|
||
|
|
||
|
for (int wR = 0; wR < `+G+`;
|
||
|
wR += `+R+`) {
|
||
|
float dyR = float(dyRCorner + wR) / `+m+`.0;
|
||
|
|
||
|
if (dyR < 0.0 || dyR >= `+p.outHeight+`.0 ||
|
||
|
fract(dyR) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyR = int(dyR);
|
||
|
|
||
|
for (int wC = 0; wC < `+Z+`;
|
||
|
wC += `+z+`) {
|
||
|
float dyC = float(dyCCorner + wC) / `+g+`.0;
|
||
|
|
||
|
if (dyC < 0.0 || dyC >= `+p.outWidth+`.0 ||
|
||
|
fract(dyC) > 0.0) {
|
||
|
continue;
|
||
|
}
|
||
|
int idyC = int(dyC);
|
||
|
|
||
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
||
|
int maxPosValue = `+Te+` -
|
||
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
||
|
|
||
|
// Get the current value, check it against the value from the
|
||
|
// position matrix.
|
||
|
int curPosValue =
|
||
|
wD * `+G+" * "+Z+` +
|
||
|
wR * `+Z+` + wC;
|
||
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
||
|
|
||
|
dotProd += dyValue * mask;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(dotProd);
|
||
|
}
|
||
|
`}return f}(),Lt=function(){function f(p,l,m,g,I,R,z,L){g===void 0&&(g=!1),I===void 0&&(I=!1),R===void 0&&(R=!1),z===void 0&&(z=null),L===void 0&&(L=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=m;var G=g?p[1]:p[2],Z=Math.ceil(G/2),be=g?"i * 2, rc.y":"rc.y, i * 2",Ce=I?"rc.z, i * 2":"i * 2, rc.z",De=g?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],Te=I?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],Ge="",Ze="";z&&(L?Ge=`vec4 activation(vec4 a) {
|
||
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
||
|
`+z+`
|
||
|
}`:Ge=`vec4 activation(vec4 x) {
|
||
|
`+z+`
|
||
|
}`,Ze="result = activation(result);");var s=R?"result += getBiasAtOutCoords();":"";R&&this.variableNames.push("bias"),L&&this.variableNames.push("preluActivationWeights");var u="rc.x",r="rc.x";p[0]<l[0]?u="int(min(float(rc.x), "+(p[0]-1)+".))":l[0]<p[0]&&(r="int(min(float(rc.x), "+(l[0]-1)+".))"),this.userCode=`
|
||
|
`+Ge+`
|
||
|
|
||
|
const float sharedDimension = `+Z+`.0;
|
||
|
|
||
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
||
|
vec4 result = vec4(0);
|
||
|
for (int i = 0; i < `+Z+`; i++) {
|
||
|
int batchA = `+u+`;
|
||
|
int batchB = `+r+`;
|
||
|
vec4 a = getMatrixA(batchA, `+be+`);
|
||
|
vec4 b = getMatrixB(batchB, `+Ce+`);
|
||
|
|
||
|
// These swizzled products need to be separately added.
|
||
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
||
|
result += (`+De[0]+" * "+Te[0]+`);
|
||
|
result += (`+De[1]+" * "+Te[1]+`);
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec3 rc = getOutputCoords();
|
||
|
vec4 result = dot2x2ARowBCol(rc);
|
||
|
|
||
|
`+s+`
|
||
|
|
||
|
`+Ze+`
|
||
|
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),Pt=function(){function f(p,l,m){this.variableNames=["probs"],this.outputShape=[p,m],this.userCode=`
|
||
|
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 < `+(l-1)+`; i++) {
|
||
|
cdf += getProbs(batch, i);
|
||
|
|
||
|
if (r < cdf) {
|
||
|
setOutput(float(i));
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// If no other event happened, last event happened.
|
||
|
setOutput(float(`+(l-1)+`));
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p){var l=this;return function(m,g){l.seedLoc==null&&(l.seedLoc=m.getUniformLocation(g,"seed")),m.gl.uniform1f(l.seedLoc,p)}},f}(),Ut=function(){function f(p,l,m,g){this.variableNames=["indices"],this.outputShape=[p,l],this.userCode=`
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int index = round(getIndices(coords.x));
|
||
|
setOutput(mix(float(`+g+"), float("+m+`),
|
||
|
float(index == coords.y)));
|
||
|
}
|
||
|
`}return f}(),Nt=function(){function f(p){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=p;var l=p.length;if(l===0)this.userCode=`
|
||
|
void main() {
|
||
|
setOutput(vec4(getA(), 0., 0., 0.));
|
||
|
}
|
||
|
`;else{var m=Vr("rc",l),g=nn(l),I=Ht(l,p,m),R=Ot(l,p[p.length-1],p[p.length-2],m),z=Rt(p,m);this.userCode=`
|
||
|
void main() {
|
||
|
`+g+` rc = getOutputCoords();
|
||
|
|
||
|
if(`+I+`) {
|
||
|
setOutput(vec4(0));
|
||
|
} else {
|
||
|
`+R+`
|
||
|
|
||
|
setOutput(vec4(`+z+`));
|
||
|
}
|
||
|
}
|
||
|
`}}return f}();function Kt(f,p){for(var l=[],m=0;m<=1;m++)for(var g=0;g<=1;g++){for(var I=(m===0?"r":"rp1")+", "+(g===0?"c":"cp1"),R=2;R<f;R++)I=p[p.length-1-R]+","+I;l.push(I)}return l}function Ht(f,p,l){if(f===1)return"rc > "+p[0];for(var m="",g=f-2;g<f;g++)m+=l[g]+" >= "+p[g],g<f-1&&(m+="||");return m}function Ot(f,p,l,m){if(f===1)return"";var g=m.slice(-2);return`
|
||
|
int r = `+g[0]+`;
|
||
|
int c = `+g[1]+`;
|
||
|
int rp1 = r + 1;
|
||
|
int cp1 = c + 1;
|
||
|
|
||
|
bool cEdge = cp1 >= `+p+`;
|
||
|
bool rEdge = rp1 >= `+l+`;
|
||
|
`}function Rt(f,p){var l=f.length,m=Kt(l,p);return l===1?`getA(rc),
|
||
|
rc + 1 >= `+f[0]+` ? 0. : getA(rc + 1),
|
||
|
0, 0`:"getA("+m[0]+`),
|
||
|
cEdge ? 0. : getA(`+m[1]+`),
|
||
|
rEdge ? 0. : getA(`+m[2]+`),
|
||
|
rEdge || cEdge ? 0. : getA(`+m[3]+")"}var wt=function(){function f(p,l,m){this.variableNames=["x"],this.outputShape=l.map(function(G,Z){return G[0]+p[Z]+G[1]});var g=p.length,I=nn(g),R=l.map(function(G){return G[0]}).join(","),z=l.map(function(G,Z){return G[0]+p[Z]}).join(","),L=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,g);if(g===1){this.userCode=`
|
||
|
int start = `+R+`;
|
||
|
int end = `+z+`;
|
||
|
|
||
|
void main() {
|
||
|
int outC = getOutputCoords();
|
||
|
if (outC < start || outC >= end) {
|
||
|
setOutput(float(`+m+`));
|
||
|
} else {
|
||
|
setOutput(getX(outC - start));
|
||
|
}
|
||
|
}
|
||
|
`;return}this.userCode=`
|
||
|
`+I+" start = "+I+"("+R+`);
|
||
|
`+I+" end = "+I+"("+z+`);
|
||
|
|
||
|
void main() {
|
||
|
`+I+` outC = getOutputCoords();
|
||
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
||
|
setOutput(float(`+m+`));
|
||
|
} else {
|
||
|
`+I+` coords = outC - start;
|
||
|
setOutput(getX(`+L+`));
|
||
|
}
|
||
|
}
|
||
|
`}return f}(),Et=function(){function f(p,l,m){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=l.map(function(s,u){return s[0]+p[u]+s[1]});for(var g=p.length,I=nn(g),R=l.map(function(s){return s[0]}).join(","),z=l.map(function(s,u){return s[0]+p[u]}).join(","),L=Vr("rc",g),G=Vr("source",g),Z=L[g-1]+" < "+this.outputShape[g-1],be=g===1?"source":"vec2("+G.slice(-2).join()+")",Ce=[I+" rc = outputLoc;",L[g-1]+` += 1;
|
||
|
if(`+Z+`) {
|
||
|
`,g===1?"":`}
|
||
|
rc = outputLoc;
|
||
|
`+L[g-2]+` += 1;
|
||
|
if(`+L[g-2]+" < "+this.outputShape[g-2]+") {",g===1?"":" "+L[g-1]+` += 1;
|
||
|
if(`+Z+") {"],De=g===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",Te="",Ge=0,Ze=g===1?2:4;Ge<Ze;Ge++)Te+=`
|
||
|
`+Ce[Ge]+`
|
||
|
if (`+De+`) {
|
||
|
result[`+Ge+"] = float("+m+`);
|
||
|
} else {
|
||
|
`+I+` source = rc - start;
|
||
|
result[`+Ge+"] = getChannel(getX("+G.join()+"), "+be+`);
|
||
|
}
|
||
|
`;Te+=g===1?"} ":"}}",this.userCode=`
|
||
|
const `+I+" start = "+I+"("+R+`);
|
||
|
const `+I+" end = "+I+"("+z+`);
|
||
|
|
||
|
void main() {
|
||
|
`+I+` outputLoc = getOutputCoords();
|
||
|
vec4 result = vec4(0.);
|
||
|
`+Te+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),Vt=function(){function f(p,l,m,g,I){if(g===void 0&&(g=!1),I===void 0&&(I=!1),this.variableNames=["x"],l==="avg"&&m)throw new Error("Cannot compute positions for average pool.");var R=p.filterWidth,z=p.strideHeight,L=p.strideWidth,G=p.dilationHeight,Z=p.dilationWidth,be=p.effectiveFilterHeight,Ce=p.effectiveFilterWidth,De=p.padInfo.top,Te=p.padInfo.left;this.outputShape=p.outShape;var Ge=l==="avg",Ze="((batch * "+p.inHeight+" + xR) * "+p.inWidth+" + xC) * "+p.inChannels+" + d",s="(xR * "+p.inWidth+" + xC) * "+p.inChannels+" + d",u="0.0";if(Ge||(u="-1.0 / 1e-20"),m){var r=">=";this.userCode=`
|
||
|
const ivec2 strides = ivec2(`+z+", "+L+`);
|
||
|
const ivec2 pads = ivec2(`+De+", "+Te+`);
|
||
|
|
||
|
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 < `+be+`;
|
||
|
wR += `+G+`) {
|
||
|
int xR = xRCorner + wR;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+Ce+`;
|
||
|
wC += `+Z+`) {
|
||
|
int xC = xCCorner + wC;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.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 `+r+` currMinMaxValue) {
|
||
|
minMaxValue = value;
|
||
|
minMaxValueFound = 1.0;
|
||
|
minMaxPosition = `+(g?I?Ze:s:"wR * "+Ce+" + wC")+`;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(float(minMaxPosition));
|
||
|
}
|
||
|
`;return}var o="max",h=l+"("+l+"("+l+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";l==="avg"&&(h="avgValue / count");var b=Math.floor(R/4)*4,T=R%4,M=`
|
||
|
if (`+Ge+`) {
|
||
|
avgValue += dot(values, ones);
|
||
|
} else {
|
||
|
minMaxValue = `+o+`(values, minMaxValue);
|
||
|
}
|
||
|
`;this.userCode=`
|
||
|
const ivec2 strides = ivec2(`+z+", "+L+`);
|
||
|
const ivec2 pads = ivec2(`+De+", "+Te+`);
|
||
|
const float initializationValue = `+u+`;
|
||
|
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 >= `+p.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(`+u+`);
|
||
|
float avgValue = 0.0;
|
||
|
count = 0.0;
|
||
|
|
||
|
for (int wR = 0; wR < `+be+`;
|
||
|
wR += `+G+`) {
|
||
|
int xR = xRCorner + wR;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+b+`; wC += 4) {
|
||
|
int xC = xCCorner + wC * `+Z+`;
|
||
|
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xR, xC, d),
|
||
|
getValue(batch, xR, xC + `+Z+`, d),
|
||
|
getValue(batch, xR, xC + 2 * `+Z+`, d),
|
||
|
getValue(batch, xR, xC + 3 * `+Z+`, d)
|
||
|
);
|
||
|
|
||
|
`+M+`
|
||
|
}
|
||
|
|
||
|
int xC = xCCorner + `+b+`;
|
||
|
if (`+(T===1)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xR, xC, d),
|
||
|
initializationValue,
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+M+`
|
||
|
} else if (`+(T===2)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xR, xC, d),
|
||
|
getValue(batch, xR, xC + `+Z+`, d),
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+M+`
|
||
|
} else if (`+(T===3)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xR, xC, d),
|
||
|
getValue(batch, xR, xC + `+Z+`, d),
|
||
|
getValue(batch, xR, xC + 2 * `+Z+`, d),
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+M+`
|
||
|
}
|
||
|
}
|
||
|
setOutput(`+h+`);
|
||
|
}
|
||
|
`}return f}(),jt=function(){function f(p,l,m,g,I){if(g===void 0&&(g=!1),I===void 0&&(I=!1),this.variableNames=["x"],l==="avg"&&m)throw new Error("Cannot compute positions for average pool.");var R=p.filterWidth,z=p.strideDepth,L=p.strideHeight,G=p.strideWidth,Z=p.dilationDepth,be=p.dilationHeight,Ce=p.dilationWidth,De=p.effectiveFilterDepth,Te=p.effectiveFilterHeight,Ge=p.effectiveFilterWidth,Ze=p.padInfo.front,s=p.padInfo.top,u=p.padInfo.left;this.outputShape=p.outShape;var r=l==="avg",o="0.0";if(r||(o="-1.0 / 1e-20"),m){var h=">=";this.userCode=`
|
||
|
const ivec3 strides =
|
||
|
ivec3(`+z+", "+L+", "+G+`);
|
||
|
const ivec3 pads = ivec3(`+Ze+", "+s+", "+u+`);
|
||
|
|
||
|
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 < `+De+`;
|
||
|
wD += `+Z+`) {
|
||
|
int xD = xDCorner + wD;
|
||
|
|
||
|
if (xD < 0 || xD >= `+p.inDepth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wR = 0; wR < `+Te+`;
|
||
|
wR += `+be+`) {
|
||
|
int xR = xRCorner + wR;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+Ge+`;
|
||
|
wC += `+Ce+`) {
|
||
|
int xC = xCCorner + wC;
|
||
|
|
||
|
if (xC < 0 || xC >= `+p.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 `+h+` currMinMaxValue) {
|
||
|
minMaxValue = value;
|
||
|
minMaxValueFound = 1.0;
|
||
|
minMaxPosition = `+(g?I?"(((batch * "+p.inDepth+" + xD) * "+p.inHeight+" + xR) * "+p.inWidth+" + xC) * "+p.inChannels+" + ch":"((xD * "+p.inHeight+" + xR) * "+p.inWidth+" + xC) * "+p.inChannels+" + ch":"wD * "+Te+" * "+Ge+` +
|
||
|
wR * `+Ge+" + wC")+`;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
setOutput(float(minMaxPosition));
|
||
|
}
|
||
|
`;return}var b="max",T=l+"("+l+"("+l+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";l==="avg"&&(T="avgValue / count");var M=Math.floor(R/4)*4,q=R%4,Y=`
|
||
|
if (`+r+`) {
|
||
|
avgValue += dot(values, ones);
|
||
|
} else {
|
||
|
minMaxValue = `+b+`(values, minMaxValue);
|
||
|
}
|
||
|
`;this.userCode=`
|
||
|
const ivec3 strides =
|
||
|
ivec3(`+z+", "+L+", "+G+`);
|
||
|
const ivec3 pads = ivec3(`+Ze+", "+s+", "+u+`);
|
||
|
const float initializationValue = `+o+`;
|
||
|
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 >= `+p.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(`+o+`);
|
||
|
float avgValue = 0.0;
|
||
|
count = 0.0;
|
||
|
|
||
|
for (int wD = 0; wD < `+De+`;
|
||
|
wD += `+Z+`) {
|
||
|
int xD = xDCorner + wD;
|
||
|
|
||
|
if (xD < 0 || xD >= `+p.inDepth+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wR = 0; wR < `+Te+`;
|
||
|
wR += `+be+`) {
|
||
|
int xR = xRCorner + wR;
|
||
|
|
||
|
if (xR < 0 || xR >= `+p.inHeight+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
for (int wC = 0; wC < `+M+`; wC += 4) {
|
||
|
int xC = xCCorner + wC * `+Ce+`;
|
||
|
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xD, xR, xC, ch),
|
||
|
getValue(batch, xD, xR, xC + `+Ce+`, ch),
|
||
|
getValue(batch, xD, xR, xC + 2 * `+Ce+`, ch),
|
||
|
getValue(batch, xD, xR, xC + 3 * `+Ce+`, ch)
|
||
|
);
|
||
|
|
||
|
`+Y+`
|
||
|
}
|
||
|
|
||
|
int xC = xCCorner + `+M+`;
|
||
|
if (`+(q===1)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xD, xR, xC, ch),
|
||
|
initializationValue,
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Y+`
|
||
|
} else if (`+(q===2)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xD, xR, xC, ch),
|
||
|
getValue(batch, xD, xR, xC + `+Ce+`, ch),
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Y+`
|
||
|
} else if (`+(q===3)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, xD, xR, xC, ch),
|
||
|
getValue(batch, xD, xR, xC + `+Ce+`, ch),
|
||
|
getValue(batch, xD, xR, xC + 2 * `+Ce+`, ch),
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Y+`
|
||
|
}
|
||
|
}
|
||
|
setOutput(`+T+`);
|
||
|
}
|
||
|
}
|
||
|
`}return f}(),cr=function(){function f(p,l){this.variableNames=["x"];var m=p.windowSize,g=p.batchSize,I=p.inSize,R=p.outSize;this.outputShape=[g,R];var z="0.0",L="";l==="prod"?z="1.0":l==="min"?(z="1.0 / 1e-20",L="min"):l==="max"&&(z="-1.0 / 1e-20",L="max");var G=l+"("+l+"("+l+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";l==="sum"?G="sumValue":l==="prod"?G="prodValue":l==="all"?G="allValue":l==="any"&&(G="anyValue");var Z=Math.floor(m/4)*4,be=m%4,Ce=`
|
||
|
if (`+(l==="sum")+`) {
|
||
|
sumValue += dot(values, ones);
|
||
|
} else if (`+(l==="prod")+`) {
|
||
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
||
|
prodValue *= tmp[0] * tmp[1];
|
||
|
} else {
|
||
|
minMaxValue = `+L+`(values, minMaxValue);
|
||
|
}
|
||
|
`,De="vec4";l==="all"?(z="1.0",Ce=`
|
||
|
bool reducedAllValue = all(values);
|
||
|
float floatedReducedAllValue = float(reducedAllValue);
|
||
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
||
|
`,De="bvec4"):l==="any"&&(z="0.0",Ce=`
|
||
|
bool reducedAnyValue = any(values);
|
||
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
||
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
||
|
`,De="bvec4");var Te="";I%m>0&&(Te=`
|
||
|
if (inIdx < 0 || inIdx >= `+I+`) {
|
||
|
return initializationValue;
|
||
|
}
|
||
|
`),this.userCode=`
|
||
|
const float initializationValue = `+z+`;
|
||
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
||
|
|
||
|
float getValue(int batch, int inIdx) {
|
||
|
`+Te+`
|
||
|
return getX(batch, inIdx);
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int outIdx = coords[1];
|
||
|
int inOffset = outIdx * `+m+`;
|
||
|
|
||
|
vec4 minMaxValue = vec4(`+z+`);
|
||
|
float prodValue = 1.0;
|
||
|
float sumValue = 0.0;
|
||
|
float allValue = 1.0;
|
||
|
float anyValue = 0.0;
|
||
|
|
||
|
for (int i = 0; i < `+Z+`; i += 4) {
|
||
|
int inIdx = inOffset + i;
|
||
|
`+De+" values = "+De+`(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1),
|
||
|
getValue(batch, inIdx + 2),
|
||
|
getValue(batch, inIdx + 3)
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
}
|
||
|
|
||
|
int inIdx = inOffset + `+Z+`;
|
||
|
if (`+(be===1)+`) {
|
||
|
`+De+" values = "+De+`(
|
||
|
getValue(batch, inIdx),
|
||
|
initializationValue,
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
} else if (`+(be===2)+`) {
|
||
|
`+De+" values = "+De+`(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1),
|
||
|
initializationValue,
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
} else if (`+(be===3)+`) {
|
||
|
`+De+" values = "+De+`(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1),
|
||
|
getValue(batch, inIdx + 2),
|
||
|
initializationValue
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
}
|
||
|
setOutput(`+G+`);
|
||
|
}
|
||
|
`}return f}(),rr=function(){function f(p,l){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p;for(var m="",g=0;g<4;g++){var I="thisRC = rc;";g%2===1&&(I+="thisRC.z += 1;"),g>1&&(I+="thisRC.y += 1;"),m+=`
|
||
|
`+I+`
|
||
|
`+(g>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[`+g+`] =
|
||
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
||
|
`+(g>0?"}":"")+`
|
||
|
`}this.userCode=`
|
||
|
`+Ie(l)+`
|
||
|
`+Kn(p)+`
|
||
|
|
||
|
void main() {
|
||
|
ivec3 rc = getOutputCoords();
|
||
|
|
||
|
vec4 result = vec4(0.);
|
||
|
|
||
|
ivec3 thisRC;
|
||
|
int rows = `+p[1]+`;
|
||
|
int cols = `+p[2]+`;
|
||
|
|
||
|
`+m+`
|
||
|
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}();function Ie(f){var p=Rn(["r","c","d"],f);return`
|
||
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
||
|
`+p+`
|
||
|
return ivec3(r, c, d);
|
||
|
}
|
||
|
`}var br=function(){function f(p,l,m){this.variableNames=["dy"],this.outputShape=[],this.outputShape=l.shape;var g=l.shape,I=g[1],R=g[2],z=p.shape,L=z[1],G=z[2],Z=[m&&L>1?I-1:I,m&&G>1?R-1:R],be=[m&&L>1?L-1:L,m&&G>1?G-1:G],Ce=Z[0]/be[0],De=Z[1]/be[1],Te=1/Ce,Ge=1/De,Ze=Math.ceil(Te)*2+2,s=Math.ceil(Ge)*2+2;this.userCode=`
|
||
|
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(`+Ce+`);
|
||
|
const float widthScale = float(`+De+`);
|
||
|
|
||
|
const float invHeightScale = float(`+Te+`);
|
||
|
const float invWidthScale = float(`+Ge+`);
|
||
|
|
||
|
const int winHeight = int(`+Ze+`);
|
||
|
const int winWidth = int(`+s+`);
|
||
|
|
||
|
// 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 >= `+G+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
float dxR = float(dyR) * heightScale;
|
||
|
int topDxRIndex = int(floor(dxR));
|
||
|
int bottomDxRIndex = int(min(ceil(dxR), `+(I-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), `+(R-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);
|
||
|
}
|
||
|
`}return f}(),Nr=function(){function f(p,l,m,g){this.variableNames=["A"],this.outputShape=[];var I=p[0],R=p[1],z=p[2],L=p[3];this.outputShape=[I,l,m,L];var G=[g&&l>1?R-1:R,g&&m>1?z-1:z],Z=[g&&l>1?l-1:l,g&&m>1?m-1:m];this.userCode=`
|
||
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
||
|
`+G[0]/Z[0]+`,
|
||
|
`+G[1]/Z[1]+`);
|
||
|
const vec2 inputShapeRC = vec2(`+R+".0, "+z+`.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);
|
||
|
}
|
||
|
`}return f}(),Tr=function(){function f(p,l,m,g){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var I=p[0],R=p[1],z=p[2],L=p[3];this.outputShape=[I,l,m,L];var G=[g&&l>1?R-1:R,g&&m>1?z-1:z],Z=[g&&l>1?l-1:l,g&&m>1?m-1:m];this.userCode=`
|
||
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
||
|
`+G[0]/Z[0]+`,
|
||
|
`+G[1]/Z[1]+`,
|
||
|
`+G[1]/Z[1]+`);
|
||
|
const vec3 inputShapeRC = vec3(`+R+".0, "+z+`.0,
|
||
|
`+z+`.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 < `+(m-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);
|
||
|
}
|
||
|
`}return f}(),hr=function(){function f(p,l,m){this.variableNames=["dy"],this.outputShape=[],this.outputShape=l.shape;var g=l.shape,I=g[1],R=g[2],z=p.shape,L=z[1],G=z[2],Z=[m&&L>1?I-1:I,m&&G>1?R-1:R],be=[m&&L>1?L-1:L,m&&G>1?G-1:G],Ce=Z[0]/be[0],De=Z[1]/be[1],Te=1/Ce,Ge=1/De,Ze=Math.ceil(Te)*2+2,s=Math.ceil(Ge)*2+2;this.userCode=`
|
||
|
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(`+Ce+`);
|
||
|
const float widthScale = float(`+De+`);
|
||
|
|
||
|
const float invHeightScale = float(`+Te+`);
|
||
|
const float invWidthScale = float(`+Ge+`);
|
||
|
|
||
|
const int winHeight = int(`+Ze+`);
|
||
|
const int winWidth = int(`+s+`);
|
||
|
|
||
|
// 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 >= `+G+`) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
float sourceFracRow =
|
||
|
float(`+Z[0]+`) *
|
||
|
(float(dyR) / float(`+be[0]+`));
|
||
|
|
||
|
float sourceFracCol =
|
||
|
float(`+Z[1]+`) *
|
||
|
(float(dyC) / float(`+be[1]+`));
|
||
|
|
||
|
int sourceNearestRow = int(min(
|
||
|
float(int(`+I+`) - 1),
|
||
|
`+m+` ? float(round(sourceFracRow)) :
|
||
|
float(floor(sourceFracRow))));
|
||
|
|
||
|
int sourceNearestCol = int(min(
|
||
|
float(int(`+R+`) - 1),
|
||
|
`+m+` ? float(round(sourceFracCol)) :
|
||
|
float(floor(sourceFracCol))));
|
||
|
|
||
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
||
|
accumulator += getDy(b, dyR, dyC, d);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
// End loop over dy
|
||
|
|
||
|
setOutput(accumulator);
|
||
|
}
|
||
|
`}return f}(),Dr=function(){function f(p,l,m,g){this.variableNames=["A"],this.outputShape=[];var I=p[0],R=p[1],z=p[2],L=p[3];this.outputShape=[I,l,m,L];var G=[g&&l>1?R-1:R,g&&m>1?z-1:z],Z=[g&&l>1?l-1:l,g&&m>1?m-1:m],be=g?"0.5":"0.0";this.userCode=`
|
||
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
||
|
`+G[0]/Z[0]+`,
|
||
|
`+G[1]/Z[1]+`);
|
||
|
const vec2 inputShapeRC = vec2(`+R+".0, "+z+`.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 + `+be+`)));
|
||
|
|
||
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
||
|
|
||
|
setOutput(newValue);
|
||
|
}
|
||
|
`}return f}(),fr=function(){function f(p,l){this.variableNames=["x"];var m=p.length;if(m>4)throw new Error("WebGL backend: Reverse of rank-"+m+" tensor is not yet supported");if(this.outputShape=p,m===1){this.userCode=`
|
||
|
void main() {
|
||
|
int coord = getOutputCoords();
|
||
|
setOutput(getX(`+p[0]+` - coord - 1));
|
||
|
}
|
||
|
`;return}var g=function(z){return l.indexOf(z)!==-1&&p[z]!==1?p[z]+" - coords["+z+"] - 1":"coords["+z+"]"},I=p.map(function(z,L){return g(L)}).join(","),R=nn(m);this.userCode=`
|
||
|
void main() {
|
||
|
`+R+` coords = getOutputCoords();
|
||
|
setOutput(getX(`+I+`));
|
||
|
}
|
||
|
`}return f}(),Er=function(){function f(p,l){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var m=p.length;if(m>4)throw new Error("WebGL backend: Reverse of rank-"+m+" tensor is not yet supported");this.outputShape=p;var g=Vr("rc",m),I=g[m-1]+" + 1 < "+this.outputShape[m-1],R=g[m-2]+" + 1 < "+this.outputShape[m-2],z=nn(m);m===1?this.userCode=`
|
||
|
void main(){
|
||
|
int rc = getOutputCoords();
|
||
|
vec4 result = vec4(0.);
|
||
|
result.r = getChannel(getX(`+p[0]+` - rc - 1),
|
||
|
`+p[0]+` - rc - 1);
|
||
|
if(`+I+`){
|
||
|
result.g = getChannel(getX(`+p[0]+` - (rc + 1) - 1),
|
||
|
`+p[0]+` - (rc + 1) - 1);
|
||
|
}
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`:this.userCode=`
|
||
|
void main() {
|
||
|
`+z+` rc = getOutputCoords();
|
||
|
vec4 result = vec4(0.);
|
||
|
result.r = `+L(g.slice())+`;
|
||
|
if(`+I+`){
|
||
|
result.g = `+G(g.slice())+`;
|
||
|
}
|
||
|
if(`+R+`) {
|
||
|
result.b = `+Z(g.slice())+`;
|
||
|
if(`+I+`) {
|
||
|
result.a = `+be(g.slice())+`;
|
||
|
}
|
||
|
}
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`;function L(Te){return Ce(Te)}function G(Te){return Te[m-1]="("+Te[m-1]+" + 1)",Ce(Te)}function Z(Te){return Te[m-2]="("+Te[m-2]+" + 1)",Ce(Te)}function be(Te){return Te[m-1]="("+Te[m-1]+" + 1)",Te[m-2]="("+Te[m-2]+" + 1)",Ce(Te)}function Ce(Te){var Ge=p.map(function(u,r){return De(r,Te)}),Ze=Ge.join(","),s=Ge.slice(-2).join(",");return"getChannel(getX("+Ze+"), vec2("+s+"))"}function De(Te,Ge){return l.indexOf(Te)!==-1&&p[Te]!==1?p[Te]+" - "+Ge[Te]+" - 1":""+Ge[Te]}}return f}(),an=function(){function f(p,l,m,g,I,R,z){this.variableNames=["updates","indices","defaultValue"],this.outputShape=R;var L=nn(I.length),G=nn(R.length),Z="";m===1?Z="i":m===2&&(Z="i, j");var be="getIndices("+Z+")",Ce="";g===1?Ce="i":g===2&&(Ce="i, coords[1]");var De="getUpdates("+Ce+")",Te=l>1?"strides[j]":"strides";this.userCode=`
|
||
|
`+L+" strides = "+L+"("+I+`);
|
||
|
|
||
|
void main() {
|
||
|
`+G+` coords = getOutputCoords();
|
||
|
float sum = 0.0;
|
||
|
bool found = false;
|
||
|
for (int i = 0; i < `+p+`; i++) {
|
||
|
int flattenedIndex = 0;
|
||
|
for (int j = 0; j < `+l+`; j++) {
|
||
|
int index = round(`+be+`);
|
||
|
flattenedIndex += index * `+Te+`;
|
||
|
}
|
||
|
if (flattenedIndex == coords[0]) {
|
||
|
sum += `+De+`;
|
||
|
found = true;
|
||
|
}
|
||
|
}
|
||
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
||
|
}
|
||
|
`}return f}(),wn=function(){function f(p,l){this.variableNames=["x","segmentIds"];var m=p.windowSize,g=p.batchSize,I=p.inSize,R=p.numSegments,z=R*Math.ceil(I/m);this.outputShape=[g,z];var L="0.0",G="sumValue",Z=Math.floor(m/4)*4,be=m%4,Ce=`
|
||
|
sumValue += dot(values, segFilter);
|
||
|
`,De="";I%m>0&&(De=`
|
||
|
if (inIdx < 0 || inIdx >= `+I+`) {
|
||
|
return initializationValue;
|
||
|
}
|
||
|
`);var Te="";I%m>0&&(Te=`
|
||
|
if (inIdx < 0 || inIdx >= `+I+`) {
|
||
|
return -1.0;
|
||
|
}
|
||
|
`),this.userCode=`
|
||
|
const float initializationValue = `+L+`;
|
||
|
|
||
|
float getValue(int batch, int inIdx) {
|
||
|
`+De+`
|
||
|
return getX(batch, inIdx);
|
||
|
}
|
||
|
|
||
|
float getSegmentIdAtIndex(int inIdx) {
|
||
|
`+Te+`
|
||
|
return getSegmentIds(inIdx);
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int outIdx = coords[1];
|
||
|
int inOffset = int(floor(float(outIdx) / float(
|
||
|
`+R+")) * float("+m+`));
|
||
|
int currentSeg = int(mod(float(outIdx), float(`+R+`)));
|
||
|
|
||
|
float sumValue = 0.0;
|
||
|
|
||
|
for (int i = 0; i < `+Z+`; 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
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
}
|
||
|
|
||
|
int inIdx = inOffset + `+Z+`;
|
||
|
if (`+(be===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
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
} else if (`+(be===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
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
} else if (`+(be===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
|
||
|
);
|
||
|
|
||
|
`+Ce+`
|
||
|
}
|
||
|
setOutput(`+G+`);
|
||
|
}
|
||
|
`}return f}(),ie=function(){function f(p,l,m){this.variableNames=["c","a","b"],this.outputShape=l;var g,I;if(m>4)throw Error("Where for rank "+m+" is not yet supported");if(m===1)I="resRC",g="resRC";else{for(var R=["resRC.x","resRC.y","resRC.z","resRC.w"],z=[],L=[],G=0;G<l.length;G++)L.push(""+R[G]),G<p&&z.push(""+R[G]);g=z.join(),I=L.join()}var Z=nn(m);this.userCode=`
|
||
|
void main() {
|
||
|
`+Z+` resRC = getOutputCoords();
|
||
|
float cVal = getC(`+g+`);
|
||
|
if (cVal >= 1.0) {
|
||
|
setOutput(getA(`+I+`));
|
||
|
} else {
|
||
|
setOutput(getB(`+I+`));
|
||
|
}
|
||
|
}
|
||
|
`}return f}(),Nn=function(){function f(p){this.variableNames=["source"],this.outputShape=p,this.rank=p.length;var l=nn(this.rank),m="uniform int start["+this.rank+"];",g=Ee(this.rank),I,R=p.map(function(z,L){return"sourceLoc."+bn[L]+" = start["+L+"] + coords."+bn[L]+";"});I=`
|
||
|
`+l+` sourceLoc;
|
||
|
`+l+` coords = getOutputCoords();
|
||
|
`+R.join(`
|
||
|
`)+`
|
||
|
`,this.userCode=`
|
||
|
`+m+`
|
||
|
void main() {
|
||
|
`+I+`
|
||
|
setOutput(getSource(`+g+`));
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p){var l=this;if(p.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+p.length+")"));return function(m,g){if(l.startLoc==null&&(l.startLoc=m.getUniformLocationNoThrow(g,"start"),l.startLoc==null))return;m.gl.uniform1iv(l.startLoc,p)}},f}(),bn=["x","y","z","w","u","v"];function Ee(f){if(f===1)return"sourceLoc";if(f<=6)return bn.slice(0,f).map(function(p){return"sourceLoc."+p}).join(",");throw Error("Slicing for rank "+f+" is not yet supported")}var Bn=function(){function f(p){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p,this.rank=p.length;var l=nn(this.rank),m=Vr("coords",this.rank),g=Vr("sourceLoc",this.rank),I=this.rank===1?"sourceLoc":"vec2("+g.slice(-2).join()+")",R="getChannel(getSource("+g.join()+"), "+I+")",z=`
|
||
|
result.x = `+R+`;
|
||
|
if (++`+m[this.rank-1]+" < "+p[this.rank-1]+`) {
|
||
|
++`+g[this.rank-1]+`;
|
||
|
result.y = `+R+`;
|
||
|
--`+g[this.rank-1]+`;
|
||
|
}
|
||
|
`,L=this.rank===1?"":`
|
||
|
--`+m[this.rank-1]+`;
|
||
|
if (++`+m[this.rank-2]+" < "+p[this.rank-2]+`) {
|
||
|
++`+g[this.rank-2]+`;
|
||
|
result.z = `+R+`;
|
||
|
if (++`+m[this.rank-1]+" < "+p[this.rank-1]+`) {
|
||
|
++`+g[this.rank-1]+`;
|
||
|
result.w = `+R+`;
|
||
|
}
|
||
|
}
|
||
|
`,G=this.rank<=4?`sourceLoc = coords +
|
||
|
`+l+"("+p.map(function(Z,be){return"start["+be+"]"}).join()+");":p.map(function(Z,be){return g[be]+" = "+m[be]+" + start["+be+"];"}).join(`
|
||
|
`);this.userCode=`
|
||
|
uniform int start[`+this.rank+`];
|
||
|
void main() {
|
||
|
`+l+` coords = getOutputCoords();
|
||
|
`+l+` sourceLoc;
|
||
|
`+G+`
|
||
|
vec4 result = vec4(0.);
|
||
|
`+z+`
|
||
|
`+L+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f.prototype.getCustomSetupFunc=function(p){var l=this;if(p.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+p.length+")"));return function(m,g){if(l.startLoc==null&&(l.startLoc=m.getUniformLocationNoThrow(g,"start"),l.startLoc==null))return;m.gl.uniform1iv(l.startLoc,p)}},f}(),Pn=function(){function f(p,l,m){this.variableNames=["x"],this.outputShape=m;var g=m.length,I=nn(m.length),R=nn(m.length),z="";if(g===1)z="coords * strides + begin";else{var L=0;z=m.map(function(G,Z){return L++,m.length===1?"coords * strides["+Z+"] + begin["+Z+"]":"coords["+(L-1)+"] * strides["+Z+"] + begin["+Z+"]"}).join(",")}this.userCode=`
|
||
|
`+I+" begin = "+I+"("+p+`);
|
||
|
`+I+" strides = "+I+"("+l+`);
|
||
|
|
||
|
void main() {
|
||
|
`+R+` coords = getOutputCoords();
|
||
|
setOutput(getX(`+z+`));
|
||
|
}
|
||
|
`}return f}(),Da=function(){function f(p){this.gpgpu=p,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return f.prototype.acquireTexture=function(p,l,m){var g=ya(l,m),I=va(p,g,m);I in this.freeTextures||(this.freeTextures[I]=[]),I in this.usedTextures||(this.usedTextures[I]=[]);var R=Ya(p,g,this.gpgpu.gl,this.gpgpu.textureConfig,m);if(this.freeTextures[I].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=R,this.log();var z=this.freeTextures[I].shift();return this.usedTextures[I].push(z),z}var L;return g===ge.PACKED_2X2_FLOAT32?L=this.gpgpu.createPackedMatrixTexture(p[0],p[1]):g===ge.PACKED_2X2_FLOAT16?L=this.gpgpu.createFloat16PackedMatrixTexture(p[0],p[1]):g===ge.UNPACKED_FLOAT32?L=this.gpgpu.createFloat32MatrixTexture(p[0],p[1]):g===ge.UNPACKED_FLOAT16?L=this.gpgpu.createFloat16MatrixTexture(p[0],p[1]):g===ge.PACKED_4X1_UNSIGNED_BYTE&&(L=this.gpgpu.createUnsignedBytesMatrixTexture(p[0],p[1])),this.usedTextures[I].push(L),this.numUsedTextures++,this._numBytesAllocated+=R,this.log(),L},f.prototype.releaseTexture=function(p,l,m,g){if(this.freeTextures==null)return;var I=ya(m,g),R=va(l,I,g);R in this.freeTextures||(this.freeTextures[R]=[]);var z=Ya(l,I,this.gpgpu.gl,this.gpgpu.textureConfig,g),L=i.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");L!==-1&&this._numBytesAllocated>L?(this.gpgpu.deleteMatrixTexture(p),this._numBytesAllocated-=z):(this.freeTextures[R].push(p),this.numFreeTextures++,this._numBytesFree+=z),this.numUsedTextures--;var G=this.usedTextures[R],Z=G.indexOf(p);if(Z<0)throw new Error("Cannot release a texture that was never provided by this texture manager");G.splice(Z,1),this.log()},f.prototype.log=function(){if(!this.logEnabled)return;var p=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+p+")");var l=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated),console.log("Bytes unused: "+this._numBytesFree+" ("+Math.round(100*l)+"%)")},Object.defineProperty(f.prototype,"numBytesAllocated",{get:function(){return this._numBytesAllocated},enumerable:!0,configurable:!0}),Object.defineProperty(f.prototype,"numBytesFree",{get:function(){return this._numBytesFree},enumerable:!0,configurable:!0}),f.prototype.getNumUsedTextures=function(){return this.numUsedTextures},f.prototype.getNumFreeTextures=function(){return this.numFreeTextures},f.prototype.dispose=function(){var p=this;if(this.freeTextures==null)return;for(var l in this.freeTextures)this.freeTextures[l].forEach(function(m){p.gpgpu.deleteMatrixTexture(m)});for(var l in this.usedTextures)this.usedTextures[l].forEach(function(g){p.gpgpu.deleteMatrixTexture(g)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0},f}();function Dn(f,p){var l=f;if(p===l.R32F)return 4;if(p===l.R16F)return 2;if(p===l.RGBA32F)return 16;if(p===f.RGBA)return 16;if(p===l.RGBA16F)return 8;throw new Error("Unknown internal format "+p)}function Ya(f,p,l,m,g){var I=za(p,m),R;if(g){var z=tt(f[0],f[1]),L=z[0],G=z[1];R=L*G}else{var Z=ze(f[0],f[1]),be=Z[0],Ce=Z[1];R=be*Ce}var De=Dn(l,I);return R*De}function za(f,p){switch(f){case ge.PACKED_2X2_FLOAT32:return ue(p);case ge.PACKED_2X2_FLOAT16:return F(p);case ge.UNPACKED_FLOAT32:return Si(p);case ge.UNPACKED_FLOAT16:return zo(p);case ge.PACKED_4X1_UNSIGNED_BYTE:return ts(p);default:throw new Error("Unknown physical texture type "+f)}}function Qa(f){return i.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?f?ge.PACKED_2X2_FLOAT32:ge.UNPACKED_FLOAT32:f?ge.PACKED_2X2_FLOAT16:ge.UNPACKED_FLOAT16}function ya(f,p){if(f===w.UPLOAD)return ge.PACKED_2X2_FLOAT32;if(f===w.RENDER||f==null)return Qa(p);if(f===w.DOWNLOAD||f===w.PIXELS)return ge.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+f)}function va(f,p,l){return f[0]+"_"+f[1]+"_"+p+"_"+l}var Yi=function(){function f(p,l){this.variableNames=["A"];for(va
|
||
|
void main() {
|
||
|
`+I+` resRC = getOutputCoords();
|
||
|
setOutput(getA(`+R+`));
|
||
|
}
|
||
|
`}return f}();function Wi(f){var p=f.length;if(p>5)throw Error("Tile for rank "+p+" is not yet supported");if(p===1)return"imod(resRC, "+f[0]+")";for(var l=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],m=[],g=0;g<f.length;g++)m.push("imod("+l[g]+", "+f[g]+")");return m.join()}var Or=function(){function f(p,l){this.variableNames=["A"],this.outputShape=p,this.userCode=`
|
||
|
float unaryOperation(float x) {
|
||
|
`+l+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
float x = getAAtOutCoords();
|
||
|
float y = unaryOperation(x);
|
||
|
|
||
|
setOutput(y);
|
||
|
}
|
||
|
`}return f}(),Za="if (isnan(x)) return x;",rs="return x;",Po="return abs(x);",dn=Za+`
|
||
|
return (x < 0.0) ? 0.0 : x;
|
||
|
`,Bo=Za+`
|
||
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
||
|
`,Fn="return (x >= 0.0) ? x : (exp(x) - 1.0);",su=`
|
||
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
||
|
// see: https://arxiv.org/abs/1706.02515
|
||
|
float scaleAlpha = `+i.backend_util.SELU_SCALEALPHA+`;
|
||
|
float scale = `+i.backend_util.SELU_SCALE+`;
|
||
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
||
|
`;function cc(f){return f===void 0&&(f=0),Za+(`
|
||
|
return x > 0.0 ? 1.0 : float(`+f+`);
|
||
|
`)}var si="return -x;",Su="return ceil(x);",Iu="return floor(x);",lc=`
|
||
|
if (isnan(x)) { return 0.0; }
|
||
|
return sign(x);
|
||
|
`,xs="return float(isnan(x));",Ii="return float(isinf(x));",_s="return float(!isnan(x) && !isinf(x));",bo=`
|
||
|
// 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;
|
||
|
}
|
||
|
}
|
||
|
`,so="return exp(x);",Nu="return exp(x) - 1.0;",uu=`if (x < 0.0) return NAN;
|
||
|
return log(x);`,ws="return log(1.0 + x);",Cu="return sqrt(x);",cu="return inversesqrt(x);",Tu="return 1.0 / (1.0 + exp(-1.0 * x));",hc=`
|
||
|
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;
|
||
|
`,uo=Za+`
|
||
|
if (abs(x) > 1.) {
|
||
|
return NAN;
|
||
|
}
|
||
|
return asin(x);
|
||
|
`,bs=Za+`
|
||
|
if (abs(x) > 1.) {
|
||
|
return NAN;
|
||
|
}
|
||
|
return acos(x);
|
||
|
`,Eu=Za+`
|
||
|
return atan(x);
|
||
|
`,pc=`
|
||
|
float e2x = exp(x);
|
||
|
return (e2x - 1.0 / e2x) / 2.0;
|
||
|
`,dc=`
|
||
|
float e2x = exp(-x);
|
||
|
return (e2x + 1.0 / e2x) / 2.0;
|
||
|
`,fc=`
|
||
|
float e2x = exp(-2.0 * abs(x));
|
||
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
||
|
`,vl=Za+"return log(x + sqrt(x * x + 1.0));",Ru=Za+`
|
||
|
if (x < 1.0) return NAN;
|
||
|
return log(x + sqrt(x * x - 1.0));`,mc=Za+`
|
||
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
||
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,yc=`
|
||
|
// Error function is calculated approximately with elementary function.
|
||
|
// See "Handbook of Mathematical Functions with Formulas,
|
||
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
||
|
float p = `+i.backend_util.ERF_P+`;
|
||
|
float a1 = `+i.backend_util.ERF_A1+`;
|
||
|
float a2 = `+i.backend_util.ERF_A2+`;
|
||
|
float a3 = `+i.backend_util.ERF_A3+`;
|
||
|
float a4 = `+i.backend_util.ERF_A4+`;
|
||
|
float a5 = `+i.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));
|
||
|
`,Ni="return 1.0 / x;",ns="return float(!(x >= 1.0));",ks="return x;",vc="return x;",Wo=`
|
||
|
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;
|
||
|
`,co=`
|
||
|
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;
|
||
|
`,Uo=`
|
||
|
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;
|
||
|
`,lu=`
|
||
|
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;
|
||
|
`,as=function(){function f(p,l){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=p,this.userCode=`
|
||
|
vec4 unaryOperation(vec4 x) {
|
||
|
`+l+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
vec4 x = getAAtOutCoords();
|
||
|
vec4 y = unaryOperation(x);
|
||
|
|
||
|
setOutput(y);
|
||
|
}
|
||
|
`}return f}(),Vo=function(){function f(p){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=p;var l=p.length,m=Vr("rc",l),g=nn(l),I=Jn(l,m),R=m.slice(-2),z=l<=1?"rc":"vec2("+R.join(",")+")";this.userCode=`
|
||
|
void main() {
|
||
|
`+g+` rc = getOutputCoords();
|
||
|
vec4 packedInput = getA(`+I+`);
|
||
|
|
||
|
setOutput(getChannel(packedInput, `+z+`));
|
||
|
}
|
||
|
`}return f}(),gl=i.backend_util.segment_util,xl=i.kernel_impls.split,Au=i.kernel_impls.tile,gc=i.kernel_impls.topkImpl,Us=i.kernel_impls.whereImpl,xc=1e-7,Qi=1e-4,hu={};function pr(f){return f in hu||(hu[f]={}),hu[f]}function Vs(f,p){if(p===void 0&&(p=!1),f==="linear")return p?vc:rs;if(f==="relu")return p?co:dn;if(f==="elu")return p?lu:Fn;if(f==="relu6")return p?Uo:Bo;if(f==="prelu")return p?Aa:ka;throw new Error("Activation "+f+" has not been implemented for the WebGL backend.")}var Ho=128,Du=600;function _c(){return i.env().global.screen==null?1024:i.env().global.screen.height*i.env().global.screen.width*window.devicePixelRatio*Du/1024/1024}var Fu=1e3,Go=function(f){O(p,f);function p(l){var m=f.call(this)||this;if(m.pendingRead=new WeakMap,m.pendingDisposal=new WeakSet,m.dataRefCount=new WeakMap,m.numBytesInGPU=0,m.uploadWaitMs=0,m.downloadWaitMs=0,m.warnedAboutMemory=!1,m.warnedAboutCPUBackend=!1,m.pendingDeletes=0,m.disposed=!1,!i.env().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(l==null){var g=P(i.env().getNumber("WEBGL_VERSION"));m.binaryCache=pr(i.env().getNumber("WEBGL_VERSION")),m.gpgpu=new Oe(g),m.canvas=g.canvas,m.gpgpuCreatedLocally=!0}else m.gpgpu=l,m.binaryCache={},m.gpgpuCreatedLocally=!1,m.canvas=l.gl.canvas;return m.textureManager=new Da(m.gpgpu),m.numMBBeforeWarning=_c(),m.texData=new i.DataStorage(m,i.engine()),m}return p.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},p.prototype.write=function(l,m,g){if((i.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||i.env().getBool("DEBUG"))&&this.checkNumericalProblems(l),g==="complex64"&&l!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var I={};return this.texData.set(I,{shape:m,dtype:g,values:l,usage:w.UPLOAD,refCount:1,complexParentRefCount:0}),I},p.prototype.incRef=function(l){var m=this.texData.get(l);m.refCount++},p.prototype.decRef=function(l){if(this.texData.has(l)){var m=this.texData.get(l);m.refCount--}},p.prototype.move=function(l,m,g,I){if(i.env().getBool("DEBUG")&&this.checkNumericalProblems(m),I==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(l,{shape:g,dtype:I,values:m,usage:w.UPLOAD,refCount:1,complexParentRefCount:0})},p.prototype.disposeIntermediateTensorInfo=function(l){var m=l.dataId;if(this.texData.has(m)){var g=this.texData.get(m);g.refCount--,g.refCount<1&&this.disposeData(m)}},p.prototype.readSync=function(l){var m=this.texData.get(l),g=m.values,I=m.dtype,R=m.complexTensorInfos,z=m.slice,L=m.shape,G=m.isPacked;if(z!=null){var Z=void 0;G?Z=new as(L,ks):Z=new Or(L,ks);var be=this.runWebGLProgram(Z,[{dataId:l,shape:L,dtype:I}],I),Ce=this.readSync(be.dataId);return this.disposeIntermediateTensorInfo(be),Ce}if(g!=null)return this.convertAndCacheOnCPU(l);if(I==="string")return g;var De=this.activeTimers!=null,Te;De&&(Te=i.util.now());var Ge;if(I==="complex64"){var Ze=this.readSync(R.real.dataId),s=this.readSync(R.imag.dataId);Ge=i.backend_util.mergeRealAndImagArrays(Ze,s)}else Ge=this.getValuesFromTexture(l);return De&&(this.downloadWaitMs+=i.util.now()-Te),this.convertAndCacheOnCPU(l,Ge)},p.prototype.read=function(l){return H(this,void 0,void 0,function(){var m,g,I,R,z,L,G,Z,be,Ce,De,Te,Ge,Ze,s,u,r,o,h,b,T,M;return se(this,function(q){switch(q.label){case 0:if(this.pendingRead.has(l))return m=this.pendingRead.get(l),[2,new Promise(function(Y){return m.push(Y)})];if(g=this.texData.get(l),I=g.values,R=g.shape,z=g.slice,L=g.dtype,G=g.complexTensorInfos,Z=g.isPacked,z!=null)return be=void 0,Z?be=new as(R,ks):be=new Or(R,ks),Ce=this.runWebGLProgram(be,[{dataId:l,shape:R,dtype:L}],L),De=this.read(Ce.dataId),this.disposeIntermediateTensorInfo(Ce),[2,De];if(I!=null)return[2,this.convertAndCacheOnCPU(l)];if(!i.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&i.env().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");re
|
||
|
if (isnan(a)) return a;
|
||
|
if (isnan(b)) return b;
|
||
|
`,Mu=`
|
||
|
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;
|
||
|
`;function Gs(f){return function(p){var l=p.inputs,m=p.backend,g=l.x,I=m,R=new Or(g.shape,f);return I.runWebGLProgram(R,[g],g.dtype)}}function po(f){var p=f.opSnippet,l=f.packedOpSnippet,m=f.checkOutOfBounds,g=m===void 0?!1:m,I=f.supportsComplex,R=I===void 0?!1:I,z=f.cpuKernelImpl,L=f.dtype;return function(G){var Z=G.inputs,be=G.backend,Ce=Z,De=Ce.a,Te=Ce.b,Ge=be;if(R&&De.dtype==="complex64"){var Ze=Ge.texData.get(De.dataId),s=Ge.texData.get(Te.dataId),u=[[Ze.complexTensorInfos.real,s.complexTensorInfos.real],[Ze.complexTensorInfos.imag,s.complexTensorInfos.imag]].map(function(je){var qe=je[0],mt=je[1],pt={dataId:qe.dataId,dtype:qe.dtype,shape:De.shape},st={dataId:mt.dataId,dtype:mt.dtype,shape:Te.shape},dt=new vn(p,De.shape,Te.shape);return Ge.runWebGLProgram(dt,[pt,st],i.upcastType(qe.dtype,mt.dtype))}),r=u[0],o=u[1],h=ho({inputs:{real:r,imag:o},backend:Ge});return Ge.disposeIntermediateTensorInfo(r),Ge.disposeIntermediateTensorInfo(o),h}var b=L||i.upcastType(De.dtype,Te.dtype);if(Ge.shouldExecuteOnCPU([De,Te])&&z!=null){var Ze=Ge.texData.get(De.dataId),s=Ge.texData.get(Te.dataId),T=z(De.shape,Te.shape,Ze.values,s.values,b),M=T[0],q=T[1],Y=Ge.makeTensorInfo(q,b),le=Ge.texData.get(Y.dataId);return le.values=M,Y}var Ne=i.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&l!=null,We;return Ne?We=new vi(l,De.shape,Te.shape,g):We=new vn(p,De.shape,Te.shape),Ge.runWebGLProgram(We,[De,Te],b)}}var Lu="return a + b;",_l=po({opSnippet:Lu,packedOpSnippet:Lu,supportsComplex:!0,cpuKernelImpl:$e}),zu={kernelName:i.Add,backendName:"webgl",kernelFunc:_l},Pu=Ic+`
|
||
|
return atan(a, b);
|
||
|
`,du=`
|
||
|
vec4 result = atan(a, b);
|
||
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
||
|
`+Mu+`
|
||
|
return result;
|
||
|
`,wl=po({opSnippet:Pu,packedOpSnippet:du}),fu={kernelName:i.Atan2,backendName:"webgl",kernelFunc:wl};function mu(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x;ln(g,"avgPool");var I=m.filterSize,R=m.strides,z=m.pad,L=m.dimRoundingMode,G=1;i.util.assert(i.backend_util.eitherStridesOrDilationsAreOne(R,G),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+R+" and dilations '"+G+"'")});var Z=i.backend_util.computePool2DInfo(g.shape,I,R,G,z,L);if(Z.filterWidth===1&&Z.filterHeight===1&&i.util.arraysEqual(Z.inShape,Z.outShape))return lo({inputs:{x:g},backend:l});var be=new Vt(Z,"avg",!1);return l.runWebGLProgram(be,[g],"float32")}var Nc={kernelName:i.AvgPool,backendName:"webgl",kernelFunc:mu};function Cc(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.dy,I=p.input,R=I;ln([g,I],"avgPoolBackprop");var z=m.filterSize,L=m.strides,G=m.pad,Z=i.backend_util.computePool2DInfo(R.shape,z,L,1,G),be=new oi(Z);return l.runWebGLProgram(be,[g],R.dtype)}var Tc={kernelName:i.AvgPoolBackprop,backendName:"webgl",kernelFunc:Cc},Ec=function(){function f(p,l,m,g,I,R){this.outputShape=[],this.variableNames=["x","mean","variance"],i.backend_util.assertAndGetBroadcastShape(p,l),i.backend_util.assertAndGetBroadcastShape(p,m);var z="0.0";g!=null&&(i.backend_util.assertAndGetBroadcastShape(p,g),this.variableNames.push("offset"),z="getOffsetAtOutCoords()");var L="1.0";I!=null&&(i.backend_util.assertAndGetBroadcastShape(p,I),this.variableNames.push("scale"),L="getScaleAtOutCoords()"),this.outputShape=p,this.userCode=`
|
||
|
void main() {
|
||
|
float x = getXAtOutCoords();
|
||
|
float mean = getMeanAtOutCoords();
|
||
|
float variance = getVarianceAtOutCoords();
|
||
|
float offset = `+z+`;
|
||
|
float scale = `+L+`;
|
||
|
float inv = scale * inversesqrt(variance + float(`+R+`));
|
||
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
||
|
}
|
||
|
`}return f}(),Ke=function(){function f(p,l,m,g,I,R){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],i.backend_util.assertAndGetBroadcastShape(p,l),i.backend_util.assertAndGetBroadcastShape(p,m);var z="vec4(0.0)";g!=null&&(i.backend_util.assertAndGetBroadcastShape(p,g),this.variableNames.push("offset"),z="getOffsetAtOutCoords()");var L="vec4(1.0)";I!=null&&(i.backend_util.assertAndGetBroadcastShape(p,I),this.variableNames.push("scale"),L="getScaleAtOutCoords()"),this.outputShape=p,this.userCode=`
|
||
|
void main() {
|
||
|
vec4 offset = `+z+`;
|
||
|
vec4 scale = `+L+`;
|
||
|
|
||
|
vec4 x = getXAtOutCoords();
|
||
|
vec4 mean = getMeanAtOutCoords();
|
||
|
vec4 variance = getVarianceAtOutCoords();
|
||
|
|
||
|
vec4 inv = scale * inversesqrt(variance + vec4(`+R+`));
|
||
|
|
||
|
setOutput((x - mean) * inv + offset);
|
||
|
}
|
||
|
`}return f}(),Rc=function(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x,I=p.mean,R=p.variance,z=p.offset,L=p.scale;i.util.assert(I.shape.length===R.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),i.util.assert(z==null||I.shape.length===z.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),i.util.assert(L==null||I.shape.length===L.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var G=m.varianceEpsilon;G==null&&(G=.001);var Z=[g,I,R],be=null;z!=null&&(be=z.shape,Z.push(z));var Ce=null;L!=null&&(Ce=L.shape,Z.push(L));var De=i.env().getBool("WEBGL_PACK_NORMALIZATION")?new Ke(g.shape,I.shape,R.shape,be,Ce,G):new Ec(g.shape,I.shape,R.shape,be,Ce,G),Te=l.runWebGLProgram(De,Z,Z[0].dtype);return Te},un={kernelName:i.FusedBatchNorm,backendName:"webgl",kernelFunc:Rc},Ac="return float(a != b);",Ss=po({opSnippet:Ac,dtype:"bool"}),Dc={kernelName:i.NotEqual,backendName:"webgl",kernelFunc:Ss};function $n(f){var p=f.inputs,l=f.backend,m=p.input,g=l.texData.get(m.dataId);return lo({inputs:{x:g.complexTensorInfos.real},backend:l})}var Fc={kernelName:i.Real,backendName:"webgl",kernelFunc:$n},Oc="return float(int(x));";function Mc(f,p){var l=new Or(f.shape,Oc),m=p.runWebGLProgram(l,[f],"int32");return{dataId:m.dataId,shape:m.shape,dtype:m.dtype}}function js(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x,I=m.dtype;if(I==="complex64"){if(g.dtype==="complex64")return lo({inputs:{x:g},backend:l});var R=i.zeros(g.shape),z=js({inputs:{x:g},backend:l,attrs:{dtype:"float32"}}),L=ho({inputs:{real:z,imag:R},backend:l});return R.dispose(),l.disposeIntermediateTensorInfo(z),L}if(g.dtype==="complex64"){var G=$n({inputs:{input:g},backend:l}),L=js({inputs:{x:G},backend:l,attrs:{dtype:I}});return l.disposeIntermediateTensorInfo(G),L}if(!i.util.hasEncodingLoss(g.dtype,I)){var L=lo({inputs:{x:g},backend:l});return{dataId:L.dataId,shape:L.shape,dtype:I}}if(I==="int32")return Mc(g,l);if(I==="bool"){var Z=l.makeTensorInfo([],"bool",i.util.getTypedArrayFromDType("bool",1)),be={a:g,b:Z},L=Ss({inputs:be,backend:l});return l.disposeIntermediateTensorInfo(Z),L}throw new Error("Error in Cast: failed to cast "+g.dtype+" to "+I)}var is={kernelName:i.Cast,backendName:"webgl",kernelFunc:js},Lc=function(){function f(p){this.outputShape=[],this.outputShape=i.backend_util.computeOutShape(p,1),this.variableNames=p.map(function(L,G){return"T"+G});var l=new Array(p.length-1);l[0]=p[0][1];for(var m=1;m<l.length;m++)l[m]=l[m-1]+p[m][1];for(var g=["if (yC < "+l[0]+") setOutput(getT0(yR, yC));"],m=1;m<l.length;m++){var I=l[m-1];g.push("else if (yC < "+l[m]+") "+("setOutput(getT"+m+"(yR, yC-"+I+"));"))}var R=l.length,z=l[l.length-1];g.push("else setOutput(getT"+R+"(yR, yC-"+z+"));"),this.userCode=`
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int yR = coords.x;
|
||
|
int yC = coords.y;
|
||
|
|
||
|
`+g.join(`
|
||
|
`)+`
|
||
|
}
|
||
|
`}return f}(),zc=function(){function f(p,l){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=i.backend_util.computeOutShape(p,l);var m=this.outputShape,g=m.length,I=nn(g),R=Vr("coords",g),z=["x","y","z","w","u","v"].slice(0,g);this.variableNames=p.map(function(s,u){return"T"+u});var L=new Array(p.length-1);L[0]=p[0][l];for(var G=1;G<L.length;G++)L[G]=L[G-1]+p[G][l];for(var Z=z[l],be=z.slice(-2),Ce=z.join(),De="if ("+Z+" < "+L[0]+`) {
|
||
|
return getChannel(
|
||
|
getT0(`+Ce+"), vec2("+be.join()+`));
|
||
|
}`,G=1;G<L.length;G++){var Te=L[G-1];De+=`
|
||
|
if (`+Z+" < "+L[G]+" && "+Z+" >= "+L[G-1]+`) {
|
||
|
return getChannel(
|
||
|
getT`+G+"("+yu(z,Z,Te)+`),
|
||
|
vec2(`+yu(be,Z,Te)+`));
|
||
|
}`}var Ge=L.length,Ze=L[L.length-1];De+=`
|
||
|
return getChannel(
|
||
|
getT`+Ge+"("+yu(z,Z,Ze)+`),
|
||
|
vec2(`+yu(be,Z,Ze)+"));",this.userCode=`
|
||
|
float getValue(`+z.map(function(s){return"int "+s})+`) {
|
||
|
`+De+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
`+I+` coords = getOutputCoords();
|
||
|
vec4 result = vec4(getValue(`+R+`), 0., 0., 0.);
|
||
|
|
||
|
`+R[g-1]+" = "+R[g-1]+` + 1;
|
||
|
if (`+R[g-1]+" < "+m[g-1]+`) {
|
||
|
result.g = getValue(`+R+`);
|
||
|
}
|
||
|
|
||
|
`+R[g-2]+" = "+R[g-2]+` + 1;
|
||
|
if (`+R[g-2]+" < "+m[g-2]+`) {
|
||
|
result.a = getValue(`+R+`);
|
||
|
}
|
||
|
|
||
|
`+R[g-1]+" = "+R[g-1]+` - 1;
|
||
|
if (`+R[g-2]+" < "+m[g-2]+` &&
|
||
|
`+R[g-1]+" < "+m[g-1]+`) {
|
||
|
result.b = getValue(`+R+`);
|
||
|
}
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}();function yu(f,p,l){var m=f.indexOf(p),g=f.map(function(I,R){return R===m?I+" - "+l:I});return g.join()}function Pc(f){var p=f.inputs,l=f.backend,m=p.input,g=l.texData.get(m.dataId);return lo({inputs:{x:g.complexTensorInfos.imag},backend:l})}var Bu={kernelName:i.Imag,backendName:"webgl",kernelFunc:Pc};function bl(f,p,l){var m=[Ua(f.shape)].concat(ga(f.shape)),g={dtype:f.dtype,shape:m,dataId:f.dataId},I=[Ua(p)].concat(ga(p)),R=new rr(I,m),z=!0,L=l.runWebGLProgram(R,[g],f.dtype,null,z);return{dataId:L.dataId,shape:p,dtype:L.dtype}}function Zi(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x,I=m.shape,R=l,z=i.util.sizeFromShape(g.shape),L=i.util.inferFromImplicitShape(I,z),G=i.util.sizeFromShape(L);i.util.assert(z===G,function(){return"The new shape ("+L+") has "+G+" elements and the old "+("shape ("+g.shape+") has "+z+" elements. The new shape and old ")+"shape must have the same number of elements."});var Z=R.texData.get(g.dataId);return Z.isPacked&&!_n(g.shape,L)&&!(Z.texture!==null&&_n(Z.shape,L))?bl(g,L,R):(R.incRef(g.dataId),{dataId:g.dataId,shape:L,dtype:g.dtype})}var Wu={kernelName:i.Reshape,backendName:"webgl",kernelFunc:Zi};function os(f,p,l){var m=f[0].dtype;if(m==="complex64"){var g=f.map(function(r){return $n({inputs:{input:r},backend:l})}),I=f.map(function(r){return Pc({inputs:{input:r},backend:l})}),R=os(g,p,l),z=os(I,p,l),L=ho({inputs:{real:R,imag:z},backend:l});return g.forEach(function(r){return l.disposeIntermediateTensorInfo(r)}),I.forEach(function(r){return l.disposeIntermediateTensorInfo(r)}),l.disposeIntermediateTensorInfo(R),l.disposeIntermediateTensorInfo(z),L}if(f.length>i.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var G=Math.floor(f.length/2),Z=os(f.slice(0,G),p,l),be=os(f.slice(G),p,l),Ce=os([Z,be],p,l);return l.disposeIntermediateTensorInfo(Z),l.disposeIntermediateTensorInfo(be),Ce}if(i.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&f[0].shape.length>1){var De=new zc(f.map(function(r){return r.shape}),p);return l.runWebGLProgram(De,f,m)}var Te=i.backend_util.computeOutShape(f.map(function(r){return r.shape}),p),Ge=f.map(function(r){return Zi({inputs:{x:r},attrs:{shape:[-1,i.util.sizeFromShape(r.shape.slice(p))]},backend:l})}),Ze=new Lc(Ge.map(function(r){return r.shape})),s=l.runWebGLProgram(Ze,Ge,m);Ge.forEach(function(r){return l.disposeIntermediateTensorInfo(r)});var u=Zi({inputs:{x:s},attrs:{shape:Te},backend:l});return l.disposeIntermediateTensorInfo(s),u}function kl(f){var p=f.inputs,l=f.backend,m=f.attrs,g=m.axis,I=i.util.parseAxisParam(g,p[0].shape)[0],R=i.backend_util.computeOutShape(p.map(function(G){return G.shape}),I);if(i.util.sizeFromShape(R)===0)return l.makeTensorInfo(R,p[0].dtype,[]);var z=p.filter(function(G){return i.util.sizeFromShape(G.shape)>0});if(z.length===1)return z[0];var L=z.map(function(G){return G.shape});return i.backend_util.assertParamsConsistent(L,I),os(z,I,l)}var Bc={kernelName:i.Concat,backendName:"webgl",kernelFunc:kl},vu=pu+`
|
||
|
return cos(x);
|
||
|
`,Wc=Gs(vu),Uc={kernelName:i.Cos,backendName:"webgl",kernelFunc:Wc},Vc=`
|
||
|
if (a == b) {
|
||
|
return 1.0;
|
||
|
};
|
||
|
return a / b;`,Hc=`
|
||
|
// 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;
|
||
|
`,Gc=po({opSnippet:Vc,packedOpSnippet:Hc,checkOutOfBounds:!0}),jc={kernelName:i.Div,backendName:"webgl",kernelFunc:Gc},Uu=function(){function f(p,l,m){this.variableNames=["real","imag"];var g=l[1];this.outputShape=l;var I=m?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,R=m?g+".0":"1.0",z;if(p==="real")z="return real * expR - imag * expI;";else if(p==="imag")z="return real * expI + imag * expR;";else throw new Error('FFT component must be either "real" or "imag", got '+p+".");this.userCode=`
|
||
|
const float exponentMultiplier = `+I+`;
|
||
|
|
||
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
||
|
`+z+`
|
||
|
}
|
||
|
|
||
|
float mulMatDFT(int batch, int index) {
|
||
|
float indexRatio = float(index) / float(`+g+`);
|
||
|
float exponentMultiplierTimesIndexRatio =
|
||
|
exponentMultiplier * indexRatio;
|
||
|
|
||
|
float result = 0.0;
|
||
|
|
||
|
for (int i = 0; i < `+g+`; 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) / `+R+`;
|
||
|
}
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
||
|
}
|
||
|
`}return f}();function Vu(f,p,l){var m=l.texData.get(f.dataId),g=i.util.sizeFromShape(f.shape),I=f.shape[f.shape.length-1],R=g/I,z=Zi({inputs:{x:f},backend:l,attrs:{shape:[R,I]}}),L=z.shape,G=new Uu("real",L,p),Z=new Uu("imag",L,p),be=[{dataId:m.complexTensorInfos.real.dataId,dtype:m.complexTensorInfos.real.dtype,shape:L},{dataId:m.complexTensorInfos.imag.dataId,dtype:m.complexTensorInfos.imag.dtype,shape:L}],Ce=l.runWebGLProgram(G,be,"float32"),De=l.runWebGLProgram(Z,be,"float32"),Te=ho({inputs:{real:Ce,imag:De},backend:l});l.disposeIntermediateTensorInfo(Ce),l.disposeIntermediateTensorInfo(De);var Ge=Zi({inputs:{x:Te},backend:l,attrs:{shape:f.shape}});return l.disposeIntermediateTensorInfo(Ge),Ge}function qc(f){var p=f.inputs,l=f.backend,m=p.input;return Vu(m,!1,l)}var Kc={kernelName:i.FFT,backendName:"webgl",kernelFunc:qc},Sl=function(){function f(p){this.variableNames=["Image"],this.outputShape=[];var l=p[2];this.outputShape=p,this.userCode=`
|
||
|
void main() {
|
||
|
ivec4 coords = getOutputCoords();
|
||
|
int x = coords[2];
|
||
|
|
||
|
int coordX = `+l+` - x;
|
||
|
float outputValue;
|
||
|
if(coordX >= 0 && coordX < `+l+`) {
|
||
|
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
|
||
|
} else {
|
||
|
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
|
||
|
}
|
||
|
setOutput(outputValue);
|
||
|
}
|
||
|
`}return f}(),Il={kernelName:i.FlipLeftRight,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.backend,m=p.image,g=l,I=new Sl(m.shape),R=g.runWebGLProgram(I,[m],m.dtype);return R}},Hu=function(){function f(p){this.variableNames=["A"];var l=tn(),m=p[0],g=p[1];this.outputShape=p,this.userCode=`
|
||
|
void main() {
|
||
|
ivec3 coords = getOutputCoords();
|
||
|
int texR = coords[0];
|
||
|
int texC = coords[1];
|
||
|
int depth = coords[2];
|
||
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+g+".0, "+m+`.0);
|
||
|
|
||
|
vec4 values = `+l.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));
|
||
|
}
|
||
|
`}return f}(),Xc=function(){function f(p){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var l=tn(),m=p[0],g=p[1];this.outputShape=p,this.userCode=`
|
||
|
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(`+g+".0, "+m+`.0);
|
||
|
vec4 values = `+l.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);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
`+l.output+` = result;
|
||
|
}
|
||
|
`}return f}(),Yc={kernelName:i.FromPixels,backendName:"webgl",kernelFunc:jo},ss;function jo(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.pixels,I=m.numChannels,R=typeof HTMLVideoElement!="undefined"&&g instanceof HTMLVideoElement,z=typeof HTMLImageElement!="undefined"&&g instanceof HTMLImageElement,L=R?[g.videoWidth,g.videoHeight]:[g.width,g.height],G=L[0],Z=L[1],be=[Z,G],Ce=[Z,G,I];(z||R)&&(ss==null&&(ss=document.createElement("canvas").getContext("2d")),ss.canvas.width=G,ss.canvas.height=Z,ss.drawImage(g,0,0,G,Z),g=ss.canvas);var De=l.makeTensorInfo(be,"int32");l.texData.get(De.dataId).usage=w.PIXELS,l.gpgpu.uploadPixelDataToTexture(l.getTexture(De.dataId),g);var Te=i.env().getBool("WEBGL_PACK")?new Xc(Ce):new Hu(Ce),Ge=l.runWebGLProgram(Te,[De],"int32");return l.disposeData(De.dataId),Ge}function Nl(f){var p=f.inputs,l=f.backend,m=p.input;return Vu(m,!0,l)}var Cl={kernelName:i.IFFT,backendName:"webgl",kernelFunc:Nl},Gu=function(){function f(p,l){this.variableNames=["x"];var m=p.windowSize,g=p.batchSize,I=p.inSize,R=p.outSize;this.outputShape=[g,R];var z=Math.floor(m/4)*4,L=m%4,G="sumValue += dot(values, ones);";if(l!=null){var Z=1/l;G="sumValue += dot(values * "+(i.util.isInt(Z)?Z.toPrecision(2):Z)+", ones);"}var be="";I%m>0&&(be=`
|
||
|
if (inIdx < 0 || inIdx >= `+I+`) {
|
||
|
return 0.0;
|
||
|
}
|
||
|
`),this.userCode=`
|
||
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
||
|
|
||
|
float getValue(int batch, int inIdx) {
|
||
|
`+be+`
|
||
|
return getX(batch, inIdx);
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
ivec2 coords = getOutputCoords();
|
||
|
int batch = coords[0];
|
||
|
int outIdx = coords[1];
|
||
|
int inOffset = outIdx * `+m+`;
|
||
|
|
||
|
float sumValue = 0.0;
|
||
|
|
||
|
for (int i = 0; i < `+z+`; i += 4) {
|
||
|
int inIdx = inOffset + i;
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1),
|
||
|
getValue(batch, inIdx + 2),
|
||
|
getValue(batch, inIdx + 3)
|
||
|
);
|
||
|
|
||
|
`+G+`
|
||
|
}
|
||
|
|
||
|
int inIdx = inOffset + `+z+`;
|
||
|
if (`+(L===1)+`) {
|
||
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
||
|
|
||
|
`+G+`
|
||
|
} else if (`+(L===2)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
||
|
|
||
|
`+G+`
|
||
|
} else if (`+(L===3)+`) {
|
||
|
vec4 values = vec4(
|
||
|
getValue(batch, inIdx),
|
||
|
getValue(batch, inIdx + 1),
|
||
|
getValue(batch, inIdx + 2), 0.0);
|
||
|
|
||
|
`+G+`
|
||
|
}
|
||
|
setOutput(sumValue);
|
||
|
}
|
||
|
`}return f}();function Tl(f){for(var p=[];p.length===0||p[p.length-1].outSize!==1;){var l=p.length?p[p.length-1].outSize:f[1],m=i.backend_util.computeOptimalWindowSize(l);p.push({inSize:l,windowSize:m,outSize:Math.ceil(l/m)})}return p}function gu(f,p,l,m){for(var g=Tl(f.shape),I=f,R=0;R<g.length;R++){var z=g[R],L=z.inSize,G=z.windowSize,Z=z.outSize,be=void 0,Ce=void 0;l==="mean"?be=R===0?new Gu({windowSize:G,inSize:L,batchSize:f.shape[0],outSize:Z},L):new Gu({windowSize:G,inSize:L,batchSize:f.shape[0],outSize:Z}):be=new cr({windowSize:G,inSize:L,batchSize:f.shape[0],outSize:Z},l),Ce=I,I=m.runWebGLProgram(be,[I],p),Ce.dataId!==f.dataId&&m.disposeIntermediateTensorInfo(Ce)}return I}function ju(f,p,l,m){var g=i.util.sizeFromShape(p),I=i.util.sizeFromShape(f.shape),R=I/g,z=Zi({inputs:{x:f},attrs:{shape:[R,g]},backend:m}),L=gu(z,f.dtype,"max",m),G=Zi({inputs:{x:L},attrs:{shape:l},backend:m});return m.disposeIntermediateTensorInfo(z),m.disposeIntermediateTensorInfo(L),G}var El=function(){function f(p,l){this.variableNames=["A"];for(var m=new Array(p.length),g=0;g<m.length;g++)m[g]=p[l[g]];this.outputShape=m,this.rank=m.length;var I=nn(this.rank),R=Rl(l);this.userCode=`
|
||
|
void main() {
|
||
|
`+I+` resRC = getOutputCoords();
|
||
|
setOutput(getA(`+R+`));
|
||
|
}
|
||
|
`}return f}();function Rl(f){var p=f.length;if(p>6)throw Error("Transpose for rank "+p+" is not yet supported");for(var l=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],m=new Array(p),g=0;g<f.length;g++)m[f[g]]=l[g];return m.join()}var Al=function(){function f(p,l){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var m=new Array(p.length),g=0;g<m.length;g++)m[g]=p[l[g]];if(this.outputShape=m,this.rank=m.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var I=nn(this.rank),R=Jr("rc",this.rank),z=new Array(this.rank),g=0;g<l.length;g++)z[l[g]]=R[g];var L="vec2("+z.slice(-2).join()+")",G="++"+R[this.rank-1]+" < "+m[this.rank-1],Z="getChannel(getA("+z.join()+"), "+L+")";this.userCode=`
|
||
|
void main() {
|
||
|
`+I+` rc = getOutputCoords();
|
||
|
vec4 result = vec4(0.);
|
||
|
result[0] = `+Z+`;
|
||
|
if(`+G+`) {
|
||
|
result[1] = `+Z+`;
|
||
|
}
|
||
|
--`+R[this.rank-1]+`;
|
||
|
if(++`+R[this.rank-2]+" < "+m[this.rank-2]+`) {
|
||
|
result[2] = `+Z+`;
|
||
|
if(`+G+`) {
|
||
|
result[3] = `+Z+`;
|
||
|
}
|
||
|
}
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}();function qs(f,p,l){var m=i.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Al(f.shape,p):new El(f.shape,p);return l.runWebGLProgram(m,[f],f.dtype)}var qu={kernelName:i.Max,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.attrs,m=f.backend,g=p.x,I=l,R=I.reductionIndices,z=I.keepDims,L=m,G=g.shape.length,Z=i.util.parseAxisParam(R,g.shape),be=Z,Ce=i.backend_util.getAxesPermutation(be,G),De=Ce!=null,Te=L.shouldExecuteOnCPU([g]),Ge=g;if(De){if(Te){for(var Ze=L.texData.get(Ge.dataId),s=Ze.values,u=new Array(G),r=0;r<u.length;r++)u[r]=g.shape[Ce[r]];var o=Ha(s,g.shape,g.dtype,Ce,u);Ge=L.makeTensorInfo(u,g.dtype);var h=L.texData.get(Ge.dataId);h.values=o}else Ge=qs(g,Ce,L);be=i.backend_util.getInnerMostAxes(be.length,G)}i.backend_util.assertAxesAreInnerMostDims("max",be,G);var b=i.backend_util.computeOutAndReduceShapes(Ge.shape,be),T=b[0],M=b[1],q=T;z&&(q=i.backend_util.expandShapeToKeepDim(T,Z));var Y;if(Te){var Ze=L.texData.get(Ge.dataId),s=Ze.values,le=dr(s,i.util.sizeFromShape(M),q,g.dtype);Y=L.makeTensorInfo(q,g.dtype);var Ne=L.texData.get(Y.dataId);Ne.values=le}else Y=ju(Ge,M,q,L);return De&&L.disposeIntermediateTensorInfo(Ge),Y}};function Dl(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x;ln(g,"maxPool");var I=m.filterSize,R=m.strides,z=m.pad,L=m.dimRoundingMode,G=1;i.util.assert(i.backend_util.eitherStridesOrDilationsAreOne(R,G),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+R+" and dilations '"+G+"'")});var Z=i.backend_util.computePool2DInfo(g.shape,I,R,G,z,L);if(Z.filterWidth===1&&Z.filterHeight===1&&i.util.arraysEqual(Z.inShape,Z.outShape))return lo({inputs:{x:g},backend:l});var be=new Vt(Z,"max",!1);return l.runWebGLProgram(be,[g],g.dtype)}var Fl={kernelName:i.MaxPool,backendName:"webgl",kernelFunc:Dl};function Ku(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.dy,I=p.input,R=p.output,z=I;ln([I,R],"maxPoolBackprop");var L=m.filterSize,G=m.strides,Z=m.pad,be=m.dimRoundingMode,Ce=i.backend_util.computePool2DInfo(z.shape,L,G,1,Z,be),De=!0,Te=new Vt(Ce,"max",De),Ge=l.runWebGLProgram(Te,[z],z.dtype),Ze=new _t(Ce),s=l.runWebGLProgram(Ze,[g,Ge],z.dtype);return l.disposeIntermediateTensorInfo(Ge),s}var Ol={kernelName:i.MaxPoolBackprop,backendName:"webgl",kernelFunc:Ku};function Ml(f,p,l,m){var g=new Vt(l,"max",!1),I=m.runWebGLProgram(g,[f],"float32");g=new Vt(l,"max",!0,!0,p);var R=m.runWebGLProgram(g,[f],"float32");return[I,R]}var Xu={kernelName:i.MaxPoolWithArgmax,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.attrs,m=f.backend,g=p.x,I=l,R=I.filterSize,z=I.strides,L=I.pad,G=I.includeBatchInIndex,Z=m;i.util.assert(g.shape.length===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+g.shape.length+"."});var be=[1,1];i.util.assert(i.backend_util.eitherStridesOrDilationsAreOne(z,be),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+z+" and dilations '"+be+"'")});var Ce=i.backend_util.computePool2DInfo(g.shape,R,z,be,L),De=Ml(g,G,Ce,Z),Te=De[0],Ge=De[1];return[Te,Ge]}};function Sa(f,p,l,m){var g=i.util.sizeFromShape(p),I=i.util.sizeFromShape(f.shape),R=I/g,z=Zi({inputs:{x:f},attrs:{shape:[R,g]},backend:m}),L=gu(z,"float32","mean",m),G=Zi({inputs:{x:L},attrs:{shape:l},backend:m});return m.disposeIntermediateTensorInfo(z),m.disposeIntermediateTensorInfo(L),G}var Ll={kernelName:i.Mean,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.attrs,m=f.backend,g=p.x,I=l,R=I.keepDims,z=I.axis,L=m,G=g.shape.length,Z=i.util.parseAxisParam(z,g.shape),be=Z,Ce=i.backend_util.getAxesPermutation(be,G),De=Ce!=null,Te=L.shouldExecuteOnCPU([g]),Ge=[],Ze=g;if(De){if(Te){for(var s=L.texData.get(Ze.dataId),u=s.values,r=new Array(G),o=0;o<r.length;o++)r[o]=g.shape[Ce[o]];var h=Ha(u,g.shape,g.dtype,Ce,r);Ze=L.makeTensorInfo(r,g.dtype);var b=L.texData.get(Ze.dataId);b.values=h}else Ze=qs(g,Ce,L);Ge.push(Ze),be=i.backend_util.getInnerMostAxes(be.length,G)}i.backend_util.assertAxesAreInnerMostDims("sum",be,G);var T=i.backend_util.computeOutAndReduceShapes(Ze.shape,be),M=T[0],q=T[1],Y=M;R&&(Y=i.ba
|
||
|
int start = `+R+`;
|
||
|
int end = `+z+`;
|
||
|
|
||
|
void main() {
|
||
|
int outC = getOutputCoords();
|
||
|
if (outC < start) {
|
||
|
outC = start * 2 - outC - `+G+`;
|
||
|
} else if(outC >= end) {
|
||
|
outC = (end - 1) * 2 - outC + `+G+`;
|
||
|
}
|
||
|
setOutput(getX(outC - start));
|
||
|
}
|
||
|
`;return}this.userCode=`
|
||
|
`+I+" start = "+I+"("+R+`);
|
||
|
`+I+" end = "+I+"("+z+`);
|
||
|
|
||
|
void main() {
|
||
|
`+I+` outC = getOutputCoords();
|
||
|
for (int i = 0; i < `+g+`; i++) {
|
||
|
if (outC[i] < start[i]) {
|
||
|
outC[i] = start[i] * 2 - outC[i] - `+G+`;
|
||
|
} else if(outC[i] >= end[i]) {
|
||
|
outC[i] = (end[i] - 1) * 2 - outC[i] + `+G+`;
|
||
|
}
|
||
|
}
|
||
|
`+I+` coords = outC - start;
|
||
|
setOutput(getX(`+L+`));
|
||
|
}
|
||
|
`}return f}(),Pl=function(){function f(p,l,m){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=l.map(function(Ge,Ze){return Ge[0]+p[Ze]+Ge[1]});var g=p.length,I=nn(g),R=l.map(function(Ge){return Ge[0]}).join(","),z=l.map(function(Ge,Ze){return Ge[0]+p[Ze]}).join(","),L=Vr("rc",g),G=Vr("source",g),Z=L[g-1]+" < "+this.outputShape[g-1],be=g===1?"source":"vec2("+G.slice(-2).join()+")",Ce=m==="reflect"?0:1,De="";if(g===1){var Te=`
|
||
|
`+I+` source = rc;
|
||
|
if (source < start) {
|
||
|
source = start * 2 - source - `+Ce+`;
|
||
|
} else if (source >= end) {
|
||
|
source = (end - 1) * 2 - source + `+Ce+`;
|
||
|
}
|
||
|
source -= start;
|
||
|
`;De=`
|
||
|
`+I+` rc = outputLoc;
|
||
|
`+Te+`
|
||
|
result[0] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
`+L[g-1]+` += 1;
|
||
|
if(`+Z+`) {
|
||
|
`+Te+`
|
||
|
result[1] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
}
|
||
|
`}else{var Te=`
|
||
|
`+I+` source = rc;
|
||
|
`+I+" lt = "+I+`(lessThan(source, start));
|
||
|
`+I+" gte = "+I+`(greaterThanEqual(source, end));
|
||
|
`+I+` orig = 1 - (lt + gte);
|
||
|
source = orig * source +
|
||
|
lt * (start * 2 - source - `+Ce+`) +
|
||
|
gte * ((end - 1) * 2 - source + `+Ce+`);
|
||
|
source -= start;
|
||
|
`;De=`
|
||
|
`+I+` rc = outputLoc;
|
||
|
`+Te+`
|
||
|
result[0] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
`+L[g-1]+` += 1;
|
||
|
if(`+Z+`) {
|
||
|
`+Te+`
|
||
|
result[1] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
}
|
||
|
rc = outputLoc;
|
||
|
`+L[g-2]+` += 1;
|
||
|
if(`+L[g-2]+" < "+this.outputShape[g-2]+`) {
|
||
|
`+Te+`
|
||
|
result[2] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
`+L[g-1]+` += 1;
|
||
|
if(`+Z+`) {
|
||
|
`+Te+`
|
||
|
result[3] = getChannel(getX(`+G.join()+"), "+be+`);
|
||
|
}
|
||
|
}
|
||
|
`}this.userCode=`
|
||
|
const `+I+" start = "+I+"("+R+`);
|
||
|
const `+I+" end = "+I+"("+z+`);
|
||
|
|
||
|
void main() {
|
||
|
`+I+` outputLoc = getOutputCoords();
|
||
|
vec4 result = vec4(0.);
|
||
|
`+De+`
|
||
|
setOutput(result);
|
||
|
}
|
||
|
`}return f}(),Qc=function(f){var p=f.inputs,l=f.backend,m=f.attrs,g=p.x,I=m.paddings,R=m.mode,z=i.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Pl(g.shape,I,R):new zl(g.shape,I,R),L=l.runWebGLProgram(z,[g],g.dtype);return L},sa={kernelName:i.MirrorPad,backendName:"webgl",kernelFunc:Qc},Pa={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},xu=function(){function f(p,l,m){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=i.backend_util.assertAndGetBroadcastShape(l,m),this.userCode=`
|
||
|
float binaryOpComplex(
|
||
|
float areal, float aimag, float breal, float bimag) {
|
||
|
`+p+`
|
||
|
}
|
||
|
|
||
|
void main() {
|
||
|
float areal = getARealAtOutCoords();
|
||
|
float aimag = getAImagAtOutCoords();
|
||
|
float breal = getBRealAtOutCoords();
|
||
|
float bimag = getBImagAtOutCoords();
|
||
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
||
|
}
|
||
|
`}return f}(),Zc="return a * b;";function Bl(f){var p=f.inputs,l=f.backend,m=p.a,g=p.b,I=i.backend_util.upcastType(m.dtype,g.dtype);if(m.dtype==="complex64"){var R=l.texData.get(m.dataId),z=l.texData.get(g.dataId),L=new xu(Pa.REAL,m.shape,g.shape),G=new xu(Pa.IMAG,m.shape,g.shape),Z=[{dataId:R.complexTensorInfos.real.dataId,dtype:R.complexTensorInfos.real.dtype,shape:m.shape},{dataId:R.complexTensorInfos.imag.dataId,dtype:R.complexTensorInfos.imag.dtype,shape:m.shape},{dataId:z.complexTensorInfos.real.dataId,dtype:z.complexTensorInfos.real.dtype,shape:g.shape},{dataId:z.complexTensorInfos.imag.dataId,dtype:z.complexTensorInfos.imag.dtype,shape:g.shape}],be=l.runWebGLProgram(L,Z,"float32"),Ce=l.runWebGLProgram(G,Z,"float32"),De=ho({inputs:{real:be,imag:Ce},backend:l});return l.disposeIntermediateTensorInfo(be),l.disposeIntermediateTensorInfo(Ce),De}if(l.shouldExecuteOnCPU([m,g])){var R=l.texData.get(m.dataId),z=l.texData.get(g.dataId),Te=ir(m.shape,g.shape,R.values,z.values,I),Ge=Te[0],Ze=Te[1],s=l.makeTensorInfo(Ze,I),u=l.texData.get(s.dataId);return u.values=Ge,s}var r;return i.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?r=new vi(Zc,m.shape,g.shape):r=new vn(Zc,m.shape,g.shape),l.runWebGLProgram(r,[m,g],I)}var Wl={kernelName:i.Multiply,backendName:"webgl",kernelFunc:Bl},Ul={kernelName:i.NonMaxSuppressionV3,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.backend,m=f.attrs;i.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var g=p,I=g.boxes,R=g.scores,z=m,L=z.maxOutputSize,G=z.iouThreshold,Z=z.scoreThreshold,be=l,Ce=be.readSync(I.dataId),De=be.readSync(R.dataId),Te=L,Ge=G,Ze=Z;return i.kernel_impls.nonMaxSuppressionV3Impl(Ce,De,Te,Ge,Ze)}},Vl=i.kernel_impls.nonMaxSuppressionV4Impl,Hl={kernelName:i.NonMaxSuppressionV4,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.backend,m=f.attrs;i.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var g=p,I=g.boxes,R=g.scores,z=m,L=z.maxOutputSize,G=z.iouThreshold,Z=z.scoreThreshold,be=z.padToMaxOutputSize,Ce=l,De=Ce.readSync(I.dataId),Te=Ce.readSync(R.dataId),Ge=Vl(De,Te,L,G,Z,be),Ze=Ge.selectedIndices,s=Ge.validOutputs;return[Ze,s]}},Gl=i.kernel_impls.nonMaxSuppressionV5Impl,jl={kernelName:i.NonMaxSuppressionV5,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.backend,m=f.attrs;i.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var g=p,I=g.boxes,R=g.scores,z=m,L=z.maxOutputSize,G=z.iouThreshold,Z=z.scoreThreshold,be=z.softNmsSigma,Ce=l,De=Ce.readSync(I.dataId),Te=Ce.readSync(R.dataId),Ge=L,Ze=G,s=Z,u=be,r=Gl(De,Te,Ge,Ze,s,u),o=r.selectedIndices,h=r.selectedScores;return[o,h]}},ql=function(){function f(p,l,m,g){this.variableNames=["Image"],this.outputShape=[];var I=p[1],R=p[2],z=Math.sin(l).toFixed(3),L=Math.cos(l).toFixed(3);this.outputShape=p;var G=i.backend_util.getImageCenter(g,I,R),Z=G[0],be=G[1],Ce=Z.toFixed(3),De=be.toFixed(3),Te="";typeof m=="number"?Te="float outputValue = "+m.toFixed(2)+";":Te=`
|
||
|
vec3 fill = vec3(`+m.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) - `+Ce+") * "+L+" - (float(y) - "+De+") * "+z+`;
|
||
|
float coordYFloat = (float(x) - `+Ce+") * "+z+" + (float(y) - "+De+") * "+L+`;
|
||
|
int coordX = int(round(coordXFloat + `+Ce+`));
|
||
|
int coordY = int(round(coordYFloat + `+De+`));
|
||
|
`+Te+`
|
||
|
if(coordX >= 0 && coordX < `+R+" && coordY >= 0 && coordY < "+I+`) {
|
||
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
||
|
}
|
||
|
setOutput(outputValue);
|
||
|
}
|
||
|
`}return f}(),Kl={kernelName:i.RotateWithOffset,backendName:"webgl",kernelFunc:function(f){var p=f.inputs,l=f.attrs,m=f.backend,g=p.image,I=l,R=I.radians,z=I.fillValue,L=I.center,G=m,Z=new ql(g.shape,R,z,L),be=G.runWebGLProgram(Z,[g],g.dtype);return be}},Xl=pu+`
|
||
|
return sin(x);
|
||
|
`,Cr=Gs(Xl),Yl={kernelName:i.Sin,backendName:"webgl",kernelFunc:Cr},Yu="return x * x;",Ql=Gs(Yu),Br={kernelName:i.Square,backendName:"webgl",kernelFunc:Ql},Jc="return (a - b) * (a - b);",bt=po({opSnippet:Jc,packedOpSnippet:Jc}),Zl={kernelName:i.SquaredDifference,backendName:"webgl",kernelFunc:bt},ui="return a - b;",Jl=po({opSnippet:ui,packedOpSnippet:ui,supportsComplex:!0,cpuKernelImpl:ra}),$c={kernelName:i.Sub,backendName:"webgl",kernelFunc:Jl},$l="return tan(x);",el=Gs($l),eh={kernelName:i.Tan,backendName:"webgl",kernelFunc:el},th={kernelName:i.Transpose,backendName:"webgl",kernelFunc:function(f){for(var p=f.inputs,l=f.attrs,m=f.backend,g=p.x,I=l.perm,R=m,z=g.shape.length,L=new Array(z),G=0;G<L.length;G++)L[G]=g.shape[I[G]];var Z;if(R.shouldExecuteOnCPU([g])){var be=R.texData.get(g.dataId),Ce=be.values,De=Ha(Ce,g.shape,g.dtype,I,L);Z=R.makeTensorInfo(L,g.dtype);var Te=R.texData.get(Z.dataId);Te.values=De}else Z=qs(g,I,R);return Z}};function Qu(f){var p=f.inputs,l=f.attrs,m=f.backend,g=l.axis,I=p.x;ln(I,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");var R=m.readSync(I.dataId),z=ki(R,g,I.shape,I.dtype),L=z.outputValues,G=z.outputShape,Z=z.indices;return[m.makeTensorInfo(G,I.dtype,L),m.makeTensorInfo([Z.length],"int32",Z)]}for(var tl={kernelName:i.Unique,backendName:"webgl",kernelFunc:Qu},rl=[zu,fu,Nc,Tc,un,is,Sc,Bc,Uc,jc,Kc,Il,Yc,kc,Cl,Bu,qu,Fl,Ol,Xu,Ll,sa,Wl,Ul,Hl,jl,Dc,Fc,Wu,Kl,Yl,Br,$c,Zl,eh,th,tl],ci=0,nl=rl;ci<nl.length;ci++){var Ji=nl[ci];i.registerKernel(Ji)}N.GPGPUContext=Oe,N.MathBackendWebGL=Go,N.forceHalfFloat=Hs,N.gpgpu_util=Re,N.setWebGLContext=Ae,N.version_webgl=Ou,N.webgl=bc,N.webgl_util=ni}),to=Mr(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=ml(),ke=og(),O=sg(),H=cg(),se=gg(),xe=xg(),Q="2.7.0",Ae={"tfjs-core":i.version_core,"tfjs-backend-cpu":se.version_cpu,"tfjs-backend-webgl":xe.version_webgl,"tfjs-data":H.version_data,"tfjs-layers":ke.version_layers,"tfjs-converter":O.version_converter,tfjs:Q};Object.keys(i).forEach(function(P){P!=="default"&&Object.defineProperty(N,P,{enumerable:!0,get:function(){return i[P]}})}),Object.keys(ke).forEach(function(P){P!=="default"&&Object.defineProperty(N,P,{enumerable:!0,get:function(){return ke[P]}})}),Object.keys(O).forEach(function(P){P!=="default"&&Object.defineProperty(N,P,{enumerable:!0,get:function(){return O[P]}})}),N.data=H,N.version=Ae}),_g=Mr(N=>{const i=to(),ke=6;function O(me){const ae={strides:[me/16,me/8],anchors:[2,6]},w=[];for(let ge=0;ge<ae.strides.length;ge++){const ze=ae.strides[ge],W=Math.floor((me+ze-1)/ze),nt=Math.floor((me+ze-1)/ze),tt=ae.anchors[ge];for(let nr=0;nr<W;nr++){const Tt=ze*(nr+.5);for(let Qe=0;Qe<nt;Qe++){const it=ze*(Qe+.5);for(let xt=0;xt<tt;xt++)w.push([it,Tt])}}}return w}const H=me=>{me.startEndTensor.dispose(),me.startPoint.dispose(),me.endPoint.dispose()},se=me=>({startEndTensor:me,startPoint:i.slice(me,[0,0],[-1,2]),endPoint:i.slice(me,[0,2],[-1,2])}),xe=(me,ae)=>{const w=i.mul(me.startPoint,ae),ge=i.mul(me.endPoint,ae),ze=i.concat2d([w,ge],1);return se(ze)};function Q(me,ae,w){const ge=i.slice(me,[0,1],[-1,2]),ze=i.add(ge,ae),W=i.slice(me,[0,3],[-1,2]),nt=i.div(W,w),tt=i.div(ze,w),nr=i.div(nt,2),Tt=i.sub(tt,nr),Qe=i.add(tt,nr),it=i.mul(Tt,w),xt=i.mul(Qe,w),ot=1;return i.concat2d([it,xt],ot)}function Ae(me,ae){return i.tidy(()=>{const w=me.box?me.box:me;return xe(w,ae).startEndTensor.squeeze()})}class P{constructor(me,ae){this.blazeFaceModel=me,this.width=ae.detector.inputSize,this.height=ae.detector.inputSize,this.maxFaces=ae.detector.maxFaces,this.anchorsData=O(ae.detector.inputSize),this.anchors=i.tensor2d(this.anchorsData),this.inputSize=i.tensor1d([this.width,this.height]),this.iouThreshold=ae.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=ae.detector.scoreThreshold}async getBoundingBoxes(me){if(!me||me.isDisposedInternal||me.shape.length!==4||me.shape[1]<1||me.shape[2]<1)return null;const[ae,w,ge]=i.tidy(()=>{const Tt=me.resizeBilinear([this.width,this.height]),Qe=i.mul(i.sub(Tt.div(255),.5),2),it=this.blazeFaceModel.predict(Qe);
|
||
|
`),xt.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join(`
|
||
|
`);let ot={};ot.colorMatrix=function(ht){const ut=new Float32Array(ht);ut[4]/=255,ut[9]/=255,ut[14]/=255,ut[19]/=255;const yt=ut[18]===1&&ut[3]===0&&ut[8]===0&&ut[13]===0&&ut[15]===0&&ut[16]===0&&ut[17]===0&&ut[19]===0?ot.colorMatrix.SHADER.WITHOUT_ALPHA:ot.colorMatrix.SHADER.WITH_ALPHA,Zt=Qe(yt);W.uniform1fv(Zt.uniform.m,ut),Tt()},ot.colorMatrix.SHADER={},ot.colorMatrix.SHADER.WITH_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];","gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];","}"].join(`
|
||
|
`),ot.colorMatrix.SHADER.WITHOUT_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];","gl_FragColor.a = c.a;","}"].join(`
|
||
|
`),ot.brightness=function(ht){const ut=(ht||0)+1;ot.colorMatrix([ut,0,0,0,0,0,ut,0,0,0,0,0,ut,0,0,0,0,0,1,0])},ot.saturation=function(ht){const ut=(ht||0)*2/3+1,yt=(ut-1)*-.5;ot.colorMatrix([ut,yt,yt,0,0,yt,ut,yt,0,0,yt,yt,ut,0,0,0,0,0,1,0])},ot.desaturate=function(){ot.saturation(-1)},ot.contrast=function(ht){const ut=(ht||0)+1,yt=-128*(ut-1);ot.colorMatrix([ut,0,0,0,yt,0,ut,0,0,yt,0,0,ut,0,yt,0,0,0,1,0])},ot.negative=function(){ot.contrast(-2)},ot.hue=function(ht){ht=(ht||0)/180*Math.PI;const ut=Math.cos(ht),yt=Math.sin(ht),Zt=.213,ar=.715,qt=.072;ot.colorMatrix([Zt+ut*(1-Zt)+yt*-Zt,ar+ut*-ar+yt*-ar,qt+ut*-qt+yt*(1-qt),0,0,Zt+ut*-Zt+yt*.143,ar+ut*(1-ar)+yt*.14,qt+ut*-qt+yt*-.283,0,0,Zt+ut*-Zt+yt*-(1-Zt),ar+ut*-ar+yt*ar,qt+ut*(1-qt)+yt*qt,0,0,0,0,0,1,0])},ot.desaturateLuminance=function(){ot.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},ot.sepia=function(){ot.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},ot.brownie=function(){ot.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},ot.vintagePinhole=function(){ot.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},ot.kodachrome=function(){ot.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},ot.technicolor=function(){ot.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},ot.polaroid=function(){ot.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},ot.shiftToBGR=function(){ot.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},ot.convolution=function(ht){const ut=new Float32Array(ht),yt=1/he,Zt=1/me,ar=Qe(ot.convolution.SHADER);W.uniform1fv(ar.uniform.m,ut),W.uniform2f(ar.uniform.px,yt,Zt),Tt()},ot.convolution.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","uniform float m[9];","void main(void) {","vec4 c11 = texture2D(texture, vUv - px);","vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));","vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));","vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );","vec4 c22 = texture2D(texture, vUv);","vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );","vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );","vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );","vec4 c33 = texture2D(texture, vUv + px );","gl_FragColor = ","c11 * m[0] + c12 * m[1] + c22 * m[2] +","c21 * m[3] + c22 * m[4] + c23 * m[5] +","c31 * m[6] + c32 * m[7] + c33 * m[8];","gl_FragColor.a = c22.a;","}"].join(`
|
||
|
`),ot.detectEdges=function(){ot.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},ot.sobelX=function(){ot.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},ot.sobelY=function(){ot.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},ot.sharpen=function(ht){const ut=ht||1;ot.convolution.call(this,[0,-1*ut,0,-1*ut,1+4*ut,-1*ut,0,-1*ut,0])},ot.emboss=function(ht){const ut=ht||1;ot.convolution.call(this,[-2*ut,-1*ut,0,-1*ut,1,1*ut,0,1*ut,2*ut])},ot.blur=function(ht){const ut=ht/7/he,yt=ht/7/me,Zt=Qe(ot.blur.SHADER);W.uniform2f(Zt.uniform.px,0,yt),Tt(it.INTERMEDIATE),W.uniform2f(Zt.uniform.px,ut,0),Tt()},ot.blur.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","void main(void) {","gl_FragColor = vec4(0.0);","gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;","gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv )*0.159576912161;","gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;","}"].join(`
|
||
|
`),ot.pixelate=function(ht){const ut=ht/he,yt=ht/me,Zt=Qe(ot.pixelate.SHADER);W.uniform2f(Zt.uniform.size,ut,yt),Tt()},ot.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join(`
|
||
|
`)};N.Canvas=ke}),Vg=Mr(N=>{const i=to(),ke=Ug();let O=null,H=null;function se(xe,Q){let Ae;if(xe instanceof i.Tensor)Ae=i.clone(xe);else{const P=xe.naturalWidth||xe.videoWidth||xe.width||xe.shape&&xe.shape[1]>0,he=xe.naturalHeight||xe.videoHeight||xe.height||xe.shape&&xe.shape[2]>0;let me=P,ae=he;Q.filter.width>0?me=Q.filter.width:Q.filter.height>0&&(me=P*(Q.filter.height/he)),Q.filter.height>0?ae=Q.filter.height:Q.filter.width>0&&(ae=he*(Q.filter.width/P)),(!O||O.width!==me||O.height!==ae)&&(O=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(me,ae):document.createElement("canvas"),O.width!==me&&(O.width=me),O.height!==ae&&(O.height=ae));const w=O.getContext("2d");xe instanceof ImageData?w.putImageData(xe,0,0):w.drawImage(xe,0,0,P,he,0,0,O.width,O.height),Q.filter.enabled&&((!this.fx||!H||O.width!==H.width||O.height!==H.height)&&(H=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(O.width,O.height):document.createElement("canvas"),H.width!==O.width&&(H.width=O.width),H.height!==O.height&&(H.height=O.height),this.fx=i.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new ke.Canvas({canvas:H}):null),this.fx.reset(),this.fx.addFilter("brightness",Q.filter.brightness),Q.filter.contrast!==0&&this.fx.addFilter("contrast",Q.filter.contrast),Q.filter.sharpness!==0&&this.fx.addFilter("sharpen",Q.filter.sharpness),Q.filter.blur!==0&&this.fx.addFilter("blur",Q.filter.blur),Q.filter.saturation!==0&&this.fx.addFilter("saturation",Q.filter.saturation),Q.filter.hue!==0&&this.fx.addFilter("hue",Q.filter.hue),Q.filter.negative&&this.fx.addFilter("negative"),Q.filter.sepia&&this.fx.addFilter("sepia"),Q.filter.vintage&&this.fx.addFilter("brownie"),Q.filter.sepia&&this.fx.addFilter("sepia"),Q.filter.kodachrome&&this.fx.addFilter("kodachrome"),Q.filter.technicolor&&this.fx.addFilter("technicolor"),Q.filter.polaroid&&this.fx.addFilter("polaroid"),Q.filter.pixelate!==0&&this.fx.addFilter("pixelate",Q.filter.pixelate),this.fx.apply(O)),H||(H=O);let ge;if(Q.backend==="webgl"||H instanceof ImageData)ge=i.browser.fromPixels(H);else{const W=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(me,ae):document.createElement("canvas");W.width=me,W.height=ae;const nt=W.getContext("2d");nt.drawImage(H,0,0);const tt=nt.getImageData(0,0,me,ae);ge=i.browser.fromPixels(tt)}const ze=ge.toFloat();Ae=ze.expandDims(0),ge.dispose(),ze.dispose()}return{tensor:Ae,canvas:Q.filter.return?H:null}}N.process=se}),Hg=Mr(N=>{Kh(N,{default:()=>i});var i={backend:"webgl",console:!0,async:!1,profile:!1,deallocate:!1,scoped:!1,videoOptimized:!0,filter:{enabled:!0,width:0,height:0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"../models/blazeface-back.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5},mesh:{enabled:!0,modelPath:"../models/facemesh.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age-imdb.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender-imdb.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion.json"}},body:{enabled:!0,modelPath:"../models/posenet.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.5,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5,enlargeFactor:1.65,maxHands:10,detector:{modelPath:"../models/handdetect.json"},skeleton:{modelPath:"../models/handskeleton.json"}}}}),Gg=Mr((N,i)=>{i.exports={name:"@vladmandic/human",version:"0.6.7",description:"human: 3D Face Detection, Body Pose, Hand & Finger Tracking, Iris Tracking, Age & Gender Prediction, Emotion Prediction & Gesture Recognition",sideEffects:!1,main:"dist/human.node.js",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic <mandic00@live.com>",bugs:{url:"http
|
||
|
.menu { position: fixed; top: 0rem; right: 0; width: fit-content; padding: 0 0.8rem 0 0.8rem; line-height: 1.8rem; z-index: 10; max-height: calc(100% - 4rem);
|
||
|
box-shadow: 0 0 8px dimgrey; background: ${Ia.background}; border-radius: 1rem; border-color: black; border-style: solid; border-width: thin; }
|
||
|
|
||
|
.menu:hover { box-shadow: 0 0 8px ${Ia.hover}; }
|
||
|
.menu-container { display: block; max-height: 100vh; }
|
||
|
.menu-container-fadeout { max-height: 0; overflow: hidden; transition: max-height, 0.5s ease; }
|
||
|
.menu-container-fadein { max-height: 100vh; overflow: hidden; transition: max-height, 0.5s ease; }
|
||
|
.menu-item { display: flex; white-space: nowrap; padding: 0.2rem; width: max-content; cursor: default; }
|
||
|
.menu-title { text-align: right; cursor: pointer; }
|
||
|
.menu-hr { margin: 0.2rem; border: 1px solid rgba(0, 0, 0, 0.5) }
|
||
|
.menu-label { padding: 0; }
|
||
|
|
||
|
.menu-list { margin-right: 0.8rem; }
|
||
|
select:focus { outline: none; }
|
||
|
.menu-list-item { background: ${Ia.itemBackground}; color: ${Ia.itemColor}; border: none; padding: 0.2rem; font-family: inherit; font-variant: inherit; border-radius: 1rem; }
|
||
|
|
||
|
.menu-chart-title { padding: 0; font-size: 0.8rem; font-weight: 800; align-items: center}
|
||
|
.menu-chart-canvas { background: transparent; margin: 0.2rem 0 0.2rem 0.6rem; }
|
||
|
|
||
|
.menu-button { border: 0; background: ${Ia.buttonBackground}; width: -webkit-fill-available; padding: 8px; margin: 8px 0 8px 0; cursor: pointer; box-shadow: 4px 4px 4px 0 dimgrey; border-radius: 1rem; justify-content: center; }
|
||
|
.menu-button:hover { background: ${Ia.buttonHover}; box-shadow: 4px 4px 4px 0 black; }
|
||
|
.menu-button:focus { outline: none; }
|
||
|
|
||
|
.menu-checkbox { width: 2.8rem; height: 1rem; background: ${Ia.itemBackground}; margin: 0.5rem 0.8rem 0 0; position: relative; border-radius: 1rem; }
|
||
|
.menu-checkbox:after { content: 'OFF'; color: ${Ia.checkboxOff}; position: absolute; right: 0.2rem; top: -0.4rem; font-weight: 800; font-size: 0.5rem; }
|
||
|
.menu-checkbox:before { content: 'ON'; color: ${Ia.checkboxOn}; position: absolute; left: 0.3rem; top: -0.4rem; font-weight: 800; font-size: 0.5rem; }
|
||
|
.menu-checkbox-label { width: 1.3rem; height: 0.8rem; cursor: pointer; position: absolute; top: 0.1rem; left: 0.1rem; z-index: 1; background: ${Ia.checkboxOff}; border-radius: 1rem; transition: left 0.6s ease; }
|
||
|
input[type=checkbox] { visibility: hidden; }
|
||
|
input[type=checkbox]:checked + label { left: 1.4rem; background: ${Ia.checkboxOn}; }
|
||
|
|
||
|
.menu-range { margin: 0 0.8rem 0 0; width: 5rem; background: transparent; color: ${Ia.rangeBackground}; }
|
||
|
.menu-range:before { content: attr(value); color: ${Ia.rangeLabel}; margin: 0 0.4rem 0 0; font-weight: 800; font-size: 0.6rem; position: relative; top: 0.3rem; }
|
||
|
input[type=range] { -webkit-appearance: none; }
|
||
|
input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 1rem; cursor: pointer; background: ${Ia.itemBackground}; border-radius: 1rem; border: 1px; }
|
||
|
input[type=range]::-webkit-slider-thumb { border: 1px solid #000000; margin-top: 0.05rem; height: 0.9rem; width: 1.5rem; border-radius: 1rem; background: ${Ia.rangeBackground}; cursor: pointer; -webkit-appearance: none; }
|
||
|
`,i=document.createElement("style");i.innerHTML=N,document.getElementsByTagName("head")[0].appendChild(i),kf=!0}class tx{constructor(N,i,ke,O){O&&(Ia={...Ia,...O}),ex(),this.createMenu(N,i,ke),this.id=0,this.instance=gh,gh++,this._maxFPS=0,this.hidden=0}createMenu(N,i="",ke={top:null,left:null,bottom:null,right:null}){if(this.menu=document.createElement("div"),this.menu.id=`menu-${gh}`,this.menu.className="menu",ke&&(ke.top&&(this.menu.style.top=ke.top),ke.bottom&&(this.menu.style.bottom=ke.bottom),ke.left&&(this.menu.style.left=ke.left),ke.right&&(this.menu.style.right=ke.right)),this.container=document.createElement("div"),this.container.id=`menu-container-${gh}`,this.container.className="menu-container menu-container-fadein",i!==""){const O=document.createElement("div");O.className="menu-title",O.id=`menu-title-${gh}`,O.innerHTML=i,this.menu.appendChild(O),O.addEventListener("click",()=>{this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"),this.menu.style.borderStyle=this.container.classList.contains("menu-container-fadeout")?"none":"solid"})}this.menu.appendChild(this.container),typeof N=="object"?N.appendChild(this.menu):document.getElementById(N).appendChild(this.menu)}get newID(){return this.id++,`menu-${this.instance}-${this.id}`}get ID(){return`menu-${this.instance}-${this.id}`}get width(){return this.menu.offsetWidth}get height(){return this.menu.offsetHeight}hide(){this.container.classList.contains("menu-container-fadein")&&(this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"))}visible(){return this.container.classList.contains("menu-container-fadein")}toggle(N){if(this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"),this.container.classList.contains("menu-container-fadein")&&N){const i=N.x||(N.touches&&N.touches[0]?N.touches[0].pageX:null),ke=N.y||(N.touches&&N.touches[0]?N.touches[0].pageY:null);i&&(this.menu.style.left=`${i-105}px`),ke&&(this.menu.style.top="5.5rem"),this.menu.offsetLeft<0&&(this.menu.style.left=0),this.menu.offsetLeft+this.menu.offsetWidth>window.innerWidth&&(this.menu.style.left=null,this.menu.style.right=0),this.menu.style.borderStyle="solid"}else this.menu.style.borderStyle="none"}addTitle(N){const i=document.createElement("div");return i.className="menu-title",i.id=this.newID,i.innerHTML=N,this.menu.appendChild(i),i.addEventListener("click",()=>{this.hidden=!this.hidden;const ke=document.getElementsByClassName("menu");for(const O of ke)O.style.display=this.hidden?"none":"block"}),i}addLabel(N){const i=document.createElement("div");return i.className="menu-item menu-label",i.id=this.newID,i.innerHTML=N,this.container.appendChild(i),i}addBool(N,i,ke,O){const H=document.createElement("div");return H.className="menu-item",H.innerHTML=`<div class="menu-checkbox"><input class="menu-checkbox" type="checkbox" id="${this.newID}" ${i[ke]?"checked":""}/><label class="menu-checkbox-label" for="${this.ID}"></label></div>${N}`,this.container.appendChild(H),H.addEventListener("change",se=>{i[ke]=se.target.checked,O&&O(se.target.checked)}),H}async addList(N,i,ke,O){const H=document.createElement("div");H.className="menu-item";let se="";for(const xe of i){const Q=xe===ke?"selected":"";se+=`<option value="${xe}" ${Q}>${xe}</option>`}return H.innerHTML=`<div class="menu-list"><select name="${this.ID}" class="menu-list-item">${se}</select><label for="${this.ID}"></label></div>${N}`,H.style.fontFamily=document.body.style.fontFamily,H.style.fontSize=document.body.style.fontSize,H.style.fontVariant=document.body.style.fontVariant,this.container.appendChild(H),H.addEventListener("change",xe=>{O&&O(i[xe.target.selectedIndex])}),H}addRange(N,i,ke,O,H,se,xe){const Q=document.createElement("div");return Q.className="menu-item",Q.innerHTML=`<input class="menu-range" type="range" id="${this.newID}" min="${O}" max="${H}" step="${se}" value="${i[ke]}">${N}`,this.container.appendChild(Q),Q.addEventListener("change",Ae=>{i[ke]=Ae.tar
|
||
|
video: ${xh.name} | facing: ${xh.facing} | resolution: ${xh.width} x ${xh.height} ${Q}
|
||
|
backend: ${Ts.tf.getBackend()} | ${xe} | object size: ${Sf(i).length.toLocaleString()} bytes
|
||
|
performance: ${Sf(i.performance)} FPS:${Ae}
|
||
|
`}async function qp(){if(Cn.busy)return null;Cn.busy=!0;const N=document.getElementById("video"),i=document.getElementById("canvas"),ke=document.getElementById("log"),O=N.srcObject?N.srcObject.getVideoTracks()[0].readyState==="live"&&N.readyState>2&&!N.paused:!1;let H="";if(Es("starting camera"),!navigator.mediaDevices)return H="camera access not supported",ke.innerText+=`
|
||
|
${H}`,hs(H),Es(H),null;let se;try{se=await navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:Cn.facing?"user":"environment",width:window.innerWidth,height:window.innerHeight,resizeMode:"none",contrast:75}})}catch(Ae){ke.innerText+=`
|
||
|
Camera permission denied`,Es("camera permission denied"),hs(Ae)}if(se)N.srcObject=se;else return null;const xe=se.getVideoTracks()[0],Q=xe.getSettings();return hs("camera settings:",Q),hs("camera track:",xe),xh={name:xe.label,width:Q.width,height:Q.height,facing:Q.facingMode==="user"?"front":"back"},new Promise(Ae=>{N.onloadeddata=async()=>{N.width=N.videoWidth,N.height=N.videoHeight,i.width=N.width,i.height=N.height,O&&N.play(),Cn.busy=!1,Ae(N)}})}function rx(N,i,ke){Jh||(hs("Creating worker thread"),Jh=new Worker(Cn.worker,{type:"module"}),Jh.addEventListener("message",O=>jp(N,O.data,ke))),Jh.postMessage({image:i.data.buffer,width:ke.width,height:ke.height,config:yr},[i.data.buffer])}function Gp(N,i){if(Hp=performance.now(),N.srcObject){const ke=N.srcObject.getVideoTracks()[0].readyState==="live"&&N.readyState>2&&!N.paused;if(!ke){N.paused||(hs(`Video not ready: state: ${N.srcObject.getVideoTracks()[0].readyState} stream state: ${N.readyState}`),setTimeout(()=>Gp(N,i),500));return}if(Cn.useWorker){const O=new OffscreenCanvas(i.width,i.height),H=O.getContext("2d");H.drawImage(N,0,0,N.width,N.height,0,0,i.width,i.height);const se=H.getImageData(0,0,i.width,i.height);rx(N,se,i)}else Ts.detect(N,yr).then(O=>{O.error?hs(O.error):jp(N,O,i),yr.profile&&hs("Profile data:",Ts.profile())})}}async function nx(N){return Hp=performance.now(),new Promise(i=>{const ke=new Image;ke.onload=async()=>{hs("Processing image:",ke.src);const O=document.getElementById("canvas");ke.width=ke.naturalWidth,ke.height=ke.naturalHeight,O.width=yr.filter.width&&yr.filter.width>0?yr.filter.width:ke.naturalWidth,O.height=yr.filter.height&&yr.filter.height>0?yr.filter.height:ke.naturalHeight;const H=await Ts.detect(ke,yr);jp(ke,H,O);const se=document.createElement("canvas");se.className="thumbnail",se.width=window.innerWidth/(Cn.columns+.1),se.height=O.height/(window.innerWidth/se.width);const xe=se.getContext("2d");xe.drawImage(O,0,0,O.width,O.height,0,0,se.width,se.height),document.getElementById("samples-container").appendChild(se),ke.src="",i(!0)},ke.src=N})}async function ax(){yr.videoOptimized=!0,document.getElementById("samples-container").style.display="none",document.getElementById("canvas").style.display="block";const N=document.getElementById("video"),i=document.getElementById("canvas");Cn.baseFont=Cn.baseFontProto.replace(/{size}/,"1.3rem"),Cn.baseLineHeight=Cn.baseLineHeightProto,N.srcObject!==null&&!N.paused?(document.getElementById("play").style.display="block",Es("paused"),N.pause()):(await qp(),document.getElementById("play").style.display="none",Es(""),N.play()),Gp(N,i)}async function ix(){document.getElementById("play").style.display="none",yr.videoOptimized=!1,Cn.baseFont=Cn.baseFontProto.replace(/{size}/,`${1.3*Cn.columns}rem`),Cn.baseLineHeight=Cn.baseLineHeightProto*Cn.columns,document.getElementById("canvas").style.display="none",document.getElementById("samples-container").style.display="block",hs("Running detection of sample images"),Es("processing images"),document.getElementById("samples-container").innerHTML="";for(const N of Cn.samples)await nx(N);Es("")}function ox(){Vn=new Vp(document.body,"...",{top:"1rem",right:"1rem"});const N=Vn.addButton("Start Video","Pause Video",()=>ax());Vn.addButton("Process Images","Process Images",()=>ix()),document.getElementById("play").addEventListener("click",()=>N.click()),Vn.addHTML('<hr style="min-width: 200px; border-style: inset; border-color: dimgray">'),Vn.addList("Backend",["cpu","webgl","wasm","webgpu"],yr.backend,i=>yr.backend=i),Vn.addBool("Enable Profiler",yr,"profile"),Vn.addBool("Memory Shield",yr,"deallocate"),Vn.addBool("Use Web Worker",Cn,"useWorker"),Vn.addHTML('<hr style="min-width: 200px; border-style: inset; border-color: dimgray">'),Vn.addLabel("Enabled Models"),Vn.addBool("Face Detect",yr.face,"enabled"),Vn.addBool("Face Mesh",yr.face.mesh,"enabled"),Vn.addBool("Face Iris",yr.face.iris,"enabled"),Vn.addBool("Face Age",yr.face.age,"enabled"),Vn.addBool("Face Gender",yr.face.gender,"enabled"),Vn.addBool("Face Emotion",yr.face.emotion,"enabled"),Vn.addBool("Body Pose",
|
||
|
/*! *****************************************************************************
|
||
|
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
|
||
|
*
|
||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||
|
*
|
||
|
* Unless required by applicable law or agreed to in writing, software
|
||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
* See the License for the specific language governing permissions and
|
||
|
* limitations under the License.
|
||
|
* =============================================================================
|
||
|
*/
|
||
|
/**
|
||
|
* @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=demo-browser-index.js.map
|