(self.webpackChunk=self.webpackChunk||[]).push([[1512],{40001:function(Qt,$e,H){"use strict";H.d($e,{Z:function(){return M}});var D=H(92413),Te=H(59301),ce={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"}}]},name:"check",theme:"outlined"},Be=ce,we=H(7657),$=function(Y,de){return Te.createElement(we.Z,(0,D.Z)({},Y,{ref:de,icon:Be}))},ne=Te.forwardRef($),M=ne},18522:function(Qt,$e,H){"use strict";H.r($e),H.d($e,{default:function(){return TA}});var D=H(59301),Te=H(89070),ce=H(31797),Be=H(45413),we=H(8591),$=H(3113),ne=H(95237),M=H(43604),K=H(43418),Y={flex_box_center:"flex_box_center___uIDcP",flex_space_between:"flex_space_between___l5roZ",flex_box_vertical_center:"flex_box_vertical_center___mj8nW",flex_box_center_end:"flex_box_center_end___v4Eig",flex_box_column:"flex_box_column___SQn0H",bg:"bg___H5S8d",steps:"steps___mrlSw",qrcode:"qrcode___xRSbG"},de=H(955),ve=H(94941),ae=H(15845),Ee=H.n(ae),ge=H(97671),_e=H(19208).lW;var Et=function(r,t){return(Et=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var o in n)n.hasOwnProperty(o)&&(e[o]=n[o])})(r,t)};function Pe(r,t){function e(){this.constructor=r}Et(r,t),r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function be(r,t,e,n){return new(e||(e=Promise))(function(o,i){function a(c){try{u(n.next(c))}catch(l){i(l)}}function s(c){try{u(n.throw(c))}catch(l){i(l)}}function u(c){c.done?o(c.value):new e(function(l){l(c.value)}).then(a,s)}u((n=n.apply(r,t||[])).next())})}function Se(r,t){var e,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(u){return function(c){return function(l){if(e)throw new TypeError("Generator is already executing.");for(;a;)try{if(e=1,n&&(o=2&l[0]?n.return:l[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,l[1])).done)return o;switch(n=0,o&&(l=[2&l[0],o.value]),l[0]){case 0:case 1:o=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,n=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){a=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]0;)n=Math.random()*t|0,e=r[--t],r[t]=r[n],r[n]=e}function Me(r,t,e){return Math.max(r,Math.min(t,e))}function Qe(r){return r%2==0?r:r+1}function Ge(r){for(var t=0,e=0;e=e?o():setTimeout(a,s)}};a()})}function Kt(r,t){for(var e=1,n=-1,o=0;o=0)e*=r[o];else if(r[o]===-1){if(n!==-1)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+o);n=o}else if(r[o]<0)throw Error("Shapes can not be < 0. Found "+r[o]+" at dim "+o);if(n===-1){if(t>0&&t!==e)throw Error("Size("+t+") must match the product of shape "+r);return r}if(e===0)throw Error("Cannot infer the missing size in ["+r+"] when there are 0 elements");if(t%e!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+e);var i=r.slice();return i[n]=t/e,i}function Dt(r,t){var e=t.length;return B((r=r==null?t.map(function(n,o){return o}):[].concat(r)).every(function(n){return n>=-e&&ns)&&r[s]===1&&(e.push(r[s]),n.push(s)),i[a]<=s&&a++}r[s]!==1&&(e.push(r[s]),n.push(s))}return{newShape:e,keptDims:n}}function T(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else{if(r!=="bool")throw new Error("Unknown data type "+r);e=new Uint8Array(t)}return e}function y(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else if(r==="bool")e=new Uint8Array(t);else{if(r!=="string")throw new Error("Unknown data type "+r);e=new Array(t)}return e}function A(r,t){for(var e=0;e=0;--n)e[n]=e[n+1]*r[n+1];return e}function hn(r,t,e){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Rt(r)),e&&A(r,t),function(i,a){return i instanceof Float32Array&&a==="float32"||i instanceof Int32Array&&a==="int32"||i instanceof Uint8Array&&a==="bool"}(r,t))return r;if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool"){for(var n=new Uint8Array(r.length),o=0;o=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+r+"]."})})}function De(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",J().platform.encode(r,t)}function Oe(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",J().platform.decode(r,t)}function Xe(r,t,e){if(t===0)return 0;if(t===1)return r[0];for(var n=r[r.length-1],o=0;o0?p:"")+" "}console.log("%c"+u+" %c"+s+" %c"+c+"D "+f+" %c"+l+" %c"+h+" %c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},r}(),lt=20,bt=3,Gt=7;function Xt(r,t,e,n){var o=dt(t),i=function(c,l,f,h){var d=Re(l),p=h[h.length-1],v=new Array(p).fill(0),g=l.length,m=f==="complex64"?Nt(c):c;if(g>1)for(var w=0;wlt){var E=bt*g,b=Array.from(l.slice(0,E)),C=Array.from(l.slice((m-bt)*g,m*g));return h==="complex64"&&(b=Nt(b),C=Nt(C)),["["+b.map(function(te,ue){return yt(te,p[ue],h)}).join(", ")+", ..., "+C.map(function(te,ue){return yt(te,p[m-bt+ue],h)}).join(", ")+"]"]}return["["+(h==="complex64"?Nt(l):Array.from(l)).map(function(te,ue){return yt(te,p[ue],h)}).join(", ")+"]"]}var S=f.slice(1),N=d.slice(1),O=d[0]*g,F=[];if(m>lt){for(var P=0;P=this.shape[n]){var s="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(s)}n++}for(var u=t[t.length-1],c=0;c0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+t+"'")},r.prototype.runKernelFunc=function(t,e,n,o,i,a,s){var u,c=this;a===void 0&&(a=[]),s===void 0&&(s=[]);var l=[],f=this.isTapeOn();o==null&&(o=this.state.activeScope!=null?this.state.activeScope.name:"");var h,d=function(w){f&&(l=w.map(function(E){return c.keep(c.clone(E))}))},p=this.state.numBytes,v=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var g,m=Vt(o,this.backendName);return h=m!=null?function(){var w=c.backend.numDataIds();g=m.kernelFunc({inputs:e,attrs:i,backend:c.backend});var E=Array.isArray(g)?g:[g];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,w,E);var b=E.map(function(S){var N=S.dataId,O=S.shape,F=S.dtype;return c.makeTensorFromDataId(N,O,F)}),C=b.filter(function(S,N){return s[N]});return d((a||[]).slice().concat(C)),b}:function(){var w=c.backend.numDataIds();g=c.tidy(function(){return t(c.backend,d)});var E=Array.isArray(g)?g:[g];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,w,E),E},this.scopedRun(function(){return c.state.kernelDepth++},function(){return c.state.kernelDepth--},function(){u=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(o,e,function(){return h()}):h()}),f&&this.addTapeNode(o,e,u,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:o,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-v,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(w){return e[w].shape}),outputShapes:u.map(function(w){return w.shape})}),Array.isArray(g)?u:u[0]},r.prototype.makeTensor=function(t,e,n,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;var i=t;n==="string"&&ie(t[0])&&(i=t.map(function(l){return De(l)}));var a=o.write(i,e,n),s=new at(e,n,a,this.nextTensorId());if(this.incRef(s,o),n==="string"){var u=this.state.tensorInfo.get(a),c=G(i);this.state.numBytes+=c-u.bytes,u.bytes=c}return s},r.prototype.makeTensorFromDataId=function(t,e,n,o){var i=new at(e,n=n||"float32",t,this.nextTensorId());return this.incRef(i,o),i},r.prototype.makeVariable=function(t,e,n,o){e===void 0&&(e=!0),n=n||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.asType(o));var i=new ln(t,e,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error("Variable with name "+i.name+" was already registered");return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i},r.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;var o=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(o=t.size*L(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:o,refCount:0}),this.state.numBytes+=o}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof ln||this.track(t)},r.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,t.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?(t.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},r.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},r.prototype.disposeVariable=function(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]},r.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},r.prototype.profile=function(t){return be(this,void 0,void 0,function(){var e,n;return Se(this,function(o){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(i){return i.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},r.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},r.prototype.addTapeNode=function(t,e,n,o,i){var a=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:i},u=zt(t);u!=null&&(o=u.gradFunc),o!=null&&(s.gradient=function(c){return c=c.map(function(l,f){if(l==null){var h=n[f],d=Z(h.size,h.dtype);return a.makeTensor(d,h.shape,h.dtype)}return l}),o(c.length>1?c:c[0],i)}),this.state.activeTape.push(s)},r.prototype.keep=function(t){return t.kept=!0,t},r.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},r.prototype.endTape=function(){this.state.gradientDepth--},r.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},r.prototype.endScope=function(t){for(var e=this,n=fo(t),o=new Set(n.map(function(u){return u.id})),i=0;i0,function(){return"gradients() received an empty list of xs."}),n!=null&&n.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return i.startTape()},function(){return i.endTape()},function(){return i.tidy("forward",t)});B(a instanceof at,function(){return"The result y returned by f() must be a tensor."});var s=function(u,c,l){for(var f={},h={},d=0;d=0;d--)for(p=(S=u[d]).inputs,w=0;w0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var u,c,l={};l[a.id]=n==null?(u=a.shape,c=z(Re(u),"float32"),W.makeTensor(c,u,"float32")):n,function(h,d,p){for(var v=function(m){var w=d[m],E=[];if(w.outputs.forEach(function(N){var O=h[N.id];O!=null?E.push(O):E.push(null)}),w.gradient==null)throw new Error("Cannot compute gradient: gradient function not found for "+w.kernelName+".");var b=w.gradient(E),C=function(N){if(!(N in b))throw new Error("Cannot backprop through input "+N+". Available gradients found: "+Object.keys(b)+".");var O=p(function(){return b[N]()});if(O.dtype!=="float32")throw new Error("Error in gradient for op "+w.kernelName+". The gradient of input "+N+" must have 'float32' dtype, but has '"+O.dtype+"'");var F=w.inputs[N];if(!Ke(O.shape,F.shape))throw new Error("Error in gradient for op "+w.kernelName+". The gradient of input '"+N+"' has shape '"+O.shape+"', which does not match the shape of the input '"+F.shape+"'");if(h[F.id]==null)h[F.id]=O;else{var P=h[F.id];h[F.id]=P.add(O),P.dispose()}};for(var S in w.inputs)C(S)},g=d.length-1;g>=0;g--)v(g)}(l,s,function(h){return i.tidy(h)});var f=e.map(function(h){return l[h.id]});return i.state.gradientDepth===0&&(i.state.activeTape.forEach(function(h){for(var d=0,p=h.saved;de||t>e)throw n="["+r+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]")+".")}function Eu(r,t){return Er(r,t,function(){return r.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ha(r,t,e,n,o,i,a,s){var u=r.getAttribLocation(e,n);return u!==-1&&(We(r,t,function(){return r.bindBuffer(r.ARRAY_BUFFER,o)}),We(r,t,function(){return r.vertexAttribPointer(u,i,r.FLOAT,!1,a,s)}),We(r,t,function(){return r.enableVertexAttribArray(u)}),!0)}function Cu(r,t,e,n){ku(r,n),We(r,t,function(){return r.activeTexture(r.TEXTURE0+n)}),We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)})}function Iu(r,t,e,n){return Er(r,t,function(){return r.getUniformLocation(e,n)},'uniform "'+n+'" not present in program.')}function Su(r,t,e){return r.getUniformLocation(t,e)}function Ru(r,t,e,n,o,i){We(r,t,function(){return Cu(r,t,n,i)}),We(r,t,function(){return r.uniform1i(o,i)})}function vi(r,t,e,n){We(r,t,function(){return r.bindFramebuffer(r.FRAMEBUFFER,n)}),We(r,t,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0)})}function da(r,t,e){We(r,t,function(){return r.bindFramebuffer(r.FRAMEBUFFER,e)}),We(r,t,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0)})}function _o(r){var t=r.checkFramebufferStatus(r.FRAMEBUFFER);if(t!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Bu(r,t))}function Bu(r,t){switch(t){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Er(r,t,e,n){var o=We(r,t,function(){return e()});if(o==null)throw new Error(n);return o}function ku(r,t){var e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+r.TEXTURE0;if(ne)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+e+"]")+".")}function Qo(r,t){return t===void 0&&(t=2),Re(r.slice(0,r.length-t))}function zo(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function gi(r){var t=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(t=[Qo(r)].concat(zo(r))),t}function Tu(r,t){var e;t===void 0&&(t=!1);var n=J().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,(r=r.map(function(c,l){return l>=r.length-2?Qe(r[l]):r[l]})).length===1&&(r=[2,r[0]])),r.length!==2){var o=an(r);r=o.newShape}var i=Re(r);if(r.length<=1&&i<=n)return[1,i];if(r.length===2&&r[0]<=n&&r[1]<=n)return r;if(r.length===3&&r[0]*r[1]<=n&&r[2]<=n)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=n&&r[1]*r[2]<=n)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=n&&r[3]<=n)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=n&&r[1]*r[2]*r[3]<=n)return[r[0],r[1]*r[2]*r[3]];if(t){var a=Qo(r),s=2,u=2;return r.length&&(s=(e=zo(r))[0],u=e[1]),Tt(i=a*(s/2)*(u/2)).map(function(c){return 2*c})}return Tt(i)}function mi(r){return r%2==0}function Uo(r,t){if(Ke(r=r.slice(-2),t=t.slice(-2))||!r.length||!t.length||r[0]===0||r[1]===0||t[0]===0||t[1]===0)return!0;if(r.length!==t.length){var e=r.slice(-1)[0],n=t.slice(-1)[0];if(e===n||mi(e)&&mi(n)&&(r[0]===1||t[0]===1))return!0}return r[1]===t[1]&&mi(r[0])&&mi(t[0])}function Du(r){if(hi==null){var t=cr(r);hi=t.getParameter(t.MAX_TEXTURE_SIZE)}return hi}function Fu(r){if(di==null){var t=cr(r);di=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,di)}function Pu(r){if(r===0)return 0;var t=cr(r);return Hn(t,"EXT_disjoint_timer_query_webgl2")&&r===2?2:Hn(t,"EXT_disjoint_timer_query")?1:0}function Hn(r,t){return r.getExtension(t)!=null}function pa(r){try{if(cr(r)!=null)return!0}catch(t){return!1}return!1}function Nu(r){if(r===0)return!1;var t=cr(r);if(r===1){if(!Hn(t,"OES_texture_float"))return!1}else if(!Hn(t,"EXT_color_buffer_float"))return!1;return va(t)}function Ou(r){if(r===0)return!1;var t=cr(r);if(r!==1){if(Hn(t,"EXT_color_buffer_float"))return va(t);if(Hn(t,"EXT_color_buffer_half_float")){var e=t.getExtension("EXT_color_buffer_half_float");return function(n,o){var i=fa(n,o),a=n.createTexture();n.bindTexture(n.TEXTURE_2D,a),n.texImage2D(n.TEXTURE_2D,0,i.internalFormatHalfFloat,1,1,0,i.textureFormatFloat,i.textureTypeHalfFloat,null);var s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,a,0);var u=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(a),n.deleteFramebuffer(s),u}(t,e)}return!1}return!!Hn(t,"OES_texture_float")&&!!Hn(t,"WEBGL_color_buffer_float")&&va(t)}function va(r){var t=fa(r),e=r.createTexture();r.bindTexture(r.TEXTURE_2D,e),r.texImage2D(r.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var n=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,n),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0);var o=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(e),r.deleteFramebuffer(n),o}function Mu(r){return r===2&&cr(r).fenceSync!=null}var fh=Object.freeze({callAndCheck:We,canBeRepresented:du,getWebGLErrorMessage:pu,getExtensionOrThrow:Wo,createVertexShader:vu,createFragmentShader:gu,createProgram:mu,linkProgram:Au,validateProgram:pi,createStaticVertexBuffer:yu,createStaticIndexBuffer:xu,getNumChannels:function(){return J().getNumber("WEBGL_VERSION")===2?1:4},createTexture:bu,validateTextureSize:wu,createFramebuffer:Eu,bindVertexBufferToProgramAttribute:ha,bindTextureUnit:Cu,unbindTextureUnit:function(r,t,e){ku(r,e),We(r,t,function(){return r.activeTexture(r.TEXTURE0+e)}),We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:Iu,getProgramUniformLocation:Su,bindTextureToProgramUniformSampler:Ru,bindCanvasToFramebuffer:function(r,t){We(r,t,function(){return r.bindFramebuffer(r.FRAMEBUFFER,null)}),We(r,t,function(){return r.viewport(0,0,r.canvas.width,r.canvas.height)}),We(r,t,function(){return r.scissor(0,0,r.canvas.width,r.canvas.height)})},bindColorTextureToFramebuffer:vi,unbindColorTextureFromFramebuffer:da,validateFramebuffer:_o,getFramebufferErrorMessage:Bu,getBatchDim:Qo,getRowsCols:zo,getShapeAs3D:gi,getTextureShapeFromLogicalShape:Tu,isReshapeFree:Uo,getWebGLMaxTextureSize:Du,resetMaxTextureSize:function(){hi=null},resetMaxTexturesInShader:function(){di=null},getMaxTexturesInShader:Fu,getWebGLDisjointQueryTimerVersion:Pu,hasExtension:Hn,isWebGLVersionEnabled:pa,isCapableOfRenderingToFloatTexture:Nu,isDownloadFloatTextureEnabled:Ou,isWebGLFenceEnabled:Mu}),tt=J();function NA(){J().set("PROD",!0)}function OA(){J().set("DEBUG",!0)}function MA(){J().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Lu(r){J().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function LA(){W.disposeVariables()}function WA(){return W}function _A(){return W.memory()}function QA(r){return W.profile(r)}function Le(r,t){return W.tidy(r,t)}function Wn(r){fo(r).forEach(function(t){return t.dispose()})}function hh(r){return W.keep(r)}function zA(r){return W.time(r)}function UA(r){return W.setBackend(r)}function HA(){return W.ready()}function jA(){return W.backendName}function VA(r){W.removeBackend(r)}function GA(r){return W.findBackend(r)}function XA(r){return W.findBackendFactory(r)}function JA(r,t,e){return e===void 0&&(e=1),W.registerBackend(r,t,e)}function KA(){return W.backend}function ZA(r,t){J().setPlatform(r,t)}function Ai(){for(var r=[],t=0;t0,function(){return"Element arr["+s.join("][")+"] should be a primitive, but is an array of "+i.length+" elements"}),B(i.length===a[0],function(){return"Element arr["+s.join("][")+"] should have "+a[0]+" elements, but has "+i.length+" elements"});for(var u=a.slice(1),c=0;c=0&&(o=n),Wu(n,o,t,e),r==null||!I(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){var i=r==null?"null":r.constructor.name;throw new Error("Argument '"+t+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+i+"'")}var a=lr(r,o);I(r)||Array.isArray(r)||(r=[r]);var s=o!=="string"?hn(r,o,J().getBool("DEBUG")):Rt(r,[],!0);return W.makeTensor(s,a,o)}function Ho(r,t,e,n){if(n===void 0&&(n="numeric"),!Array.isArray(r))throw new Error("Argument "+t+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return r.map(function(o,i){return k(o,t+"["+i+"]",e)},n)}function ga(r,t){for(var e=0;e=0&&t0}),tt.registerFlag("WEBGL_VERSION",function(){return pa(2)?2:pa(1)?1:0}),tt.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return tt.get("WEBGL_VERSION")===2}),tt.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),tt.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),tt.registerFlag("WEBGL_PACK",function(){return tt.getBool("HAS_WEBGL")}),tt.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_CLIP",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),tt.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_PACK_REDUCE",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_LAZILY_UNPACK",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_CONV_IM2COL",function(){return tt.getBool("WEBGL_PACK")}),tt.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Du(tt.getNumber("WEBGL_VERSION"))}),tt.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Fu(tt.getNumber("WEBGL_VERSION"))}),tt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var r=tt.getNumber("WEBGL_VERSION");return r===0?0:Pu(r)}),tt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return tt.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(r=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(r)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(r.substr(0,4))));var r}),tt.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Nu(tt.getNumber("WEBGL_VERSION"))}),tt.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!tt.getBool("WEBGL_FORCE_F16_TEXTURES")&&tt.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),tt.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ou(tt.getNumber("WEBGL_VERSION"))}),tt.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Mu(tt.getNumber("WEBGL_VERSION"))}),tt.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return tt.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),dn=Lu;var kn=_({complex_:function(r,t){var e=k(r,"real","complex"),n=k(t,"imag","complex");return Je(e.shape,n.shape,"real and imag shapes, "+e.shape+" and "+n.shape+", must match in call to tf.complex()."),W.runKernelFunc(function(o){return o.complex(e,n)},{$real:e,$imag:n})}}),Zn=_({real_:function(r){var t=k(r,"input","real");return W.runKernelFunc(function(e){return e.real(t)},{$input:t})}}),fr=_({imag_:function(r){var t=k(r,"input","imag");return W.runKernelFunc(function(e){return e.imag(t)},{$input:t})}});function Tn(r,t,e){return Or(r,t,lr(r,e),e)}function Or(r,t,e,n){if(n==null&&(n=ze(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!I(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){Ie(t);var o=Re(t),i=Re(e);B(o===i,function(){return"Based on the provided shape, ["+t+"], the tensor should have "+o+" values but has "+i});for(var a=0;a1)return en([0],n);var o=Z(Math.abs(Math.ceil((t-r)/e)),n);t=1,function(){return"Pass at least one tensor to concat"});var e=Ho(r,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor with dtype `+s.dtype+". ")}),t=Dt(t,e[0].shape)[0];var n=Kr(e.map(function(s){return s.shape}),t);if(Re(n)===0)return Tn([],n);if((e=e.filter(function(s){return s.size>0})).length===1)return e[0];var o=e.map(function(s){return s.shape});Qu(o,t);var i=e,a={axis:t};return W.runKernelFunc(function(s){return s.concat(e,t)},i,function(s){var u=o.map(function(c){return c[t]});return Aa(s,u,t).map(function(c){return function(){return c}})},"Concat",a)}}),mh=_({concat1d_:function(r){return An(r,0)}}),Ah=_({concat2d_:function(r,t){return An(r,t)}}),yh=_({concat3d_:function(r,t){return An(r,t)}}),xh=_({concat4d_:function(r,t){return An(r,t)}}),Aa=_({split_:function(r,t,e){e===void 0&&(e=0);var n,o=k(r,"x","split");return e=Dt(e,o.shape)[0],typeof t=="number"?(B(o.shape[e]%t==0,function(){return"Number of splits must evenly divide the axis."}),n=new Array(t).fill(o.shape[e]/t)):(B(o.shape[e]===t.reduce(function(i,a){return i+a}),function(){return"The sum of sizes must match the size of the axis dimension."}),n=t),W.runKernelFunc(function(i){return i.split(o,n,e)},{$x:o},function(i){return{$x:function(){return An(i,e)}}})}});typeof globalThis!="undefined"||typeof window!="undefined"||typeof H.g!="undefined"&&H.g;function Zr(r,t){return r(t={exports:{}},t.exports),t.exports}var bh=Zr(function(r){(function(t,e,n){function o(s){var u,c=this,l=(u=4022871197,function(f){f=f.toString();for(var h=0;h>>0,u=(d*=u)>>>0,u+=4294967296*(d-=u)}return 23283064365386963e-26*(u>>>0)});c.next=function(){var f=2091639*c.s0+23283064365386963e-26*c.c;return c.s0=c.s1,c.s1=c.s2,c.s2=f-(c.c=0|f)},c.c=1,c.s0=l(" "),c.s1=l(" "),c.s2=l(" "),c.s0-=l(s),c.s0<0&&(c.s0+=1),c.s1-=l(s),c.s1<0&&(c.s1+=1),c.s2-=l(s),c.s2<0&&(c.s2+=1),l=null}function i(s,u){return u.c=s.c,u.s0=s.s0,u.s1=s.s1,u.s2=s.s2,u}function a(s,u){var c=new o(s),l=u&&u.state,f=c.next;return f.int32=function(){return 4294967296*c.next()|0},f.double=function(){return f()+11102230246251565e-32*(2097152*f()|0)},f.quick=f,l&&(typeof l=="object"&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(0,r,!1)}),wh=Zr(function(r){(function(t,e,n){function o(s){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var f=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^f^f>>>8},s===(0|s)?u.x=s:c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var h=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(0,r,!1)}),Eh=Zr(function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var f=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^f^f<<1)|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,s===(0|s)?u.x=s:c+=s;for(var l=0;l>>4),u.next()}function i(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u.v=s.v,u.d=s.d,u}function a(s,u){var c=new o(s),l=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var h=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(0,r,!1)}),Ch=Zr(function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,f=u.x,h=u.i;return c=f[h],l=(c^=c>>>7)^c<<24,l^=(c=f[h+1&7])^c>>>10,l^=(c=f[h+3&7])^c>>>3,l^=(c=f[h+4&7])^c<<7,c=f[h+7&7],l^=(c^=c<<13)^c<<9,f[h]=l,u.i=h+1&7,l},function(c,l){var f,h=[];if(l===(0|l))h[0]=l;else for(l=""+l,f=0;f0;--f)c.next()}(u,s)}function i(s,u){return u.x=s.x.slice(),u.i=s.i,u}function a(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var h=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.x&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(0,r,!1)}),Ih=Zr(function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,f=u.w,h=u.X,d=u.i;return u.w=f=f+1640531527|0,l=h[d+34&127],c=h[d=d+1&127],l^=l<<13,c^=c<<17,l^=l>>>15,c^=c>>>12,l=h[d]=l^c,u.i=d,l+(f^f>>>16)|0},function(c,l){var f,h,d,p,v,g=[],m=128;for(l===(0|l)?(h=l,l=null):(l+="\0",h=0,m=Math.max(m,l.length)),d=0,p=-32;p>>15,h^=h<<4,h^=h>>>13,p>=0&&(v=v+1640531527|0,d=(f=g[127&p]^=h+v)==0?d+1:0);for(d>=128&&(g[127&(l&&l.length||0)]=-1),d=127,p=512;p>0;--p)h=g[d+34&127],f=g[d=d+1&127],h^=h<<13,f^=f<<17,h^=h>>>15,f^=f>>>12,g[d]=h^f;c.w=v,c.X=g,c.i=d}(u,s)}function i(s,u){return u.i=s.i,u.w=s.w,u.X=s.X.slice(),u}function a(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var h=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.X&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(0,r,!1)}),Sh=Zr(function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var f=u.b,h=u.c,d=u.d,p=u.a;return f=f<<25^f>>>7^h,h=h-d|0,d=d<<24^d>>>8^p,p=p-f|0,u.b=f=f<<20^f>>>12^h,u.c=h=h-d|0,u.d=d<<16^h>>>16^p,u.a=p-f|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,s===Math.floor(s)?(u.a=s/4294967296|0,u.b=0|s):c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var h=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&i(l,c),f.state=function(){return i(c,{})}),f}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(0,r,!1)}),qr=Zr(function(r){(function(t,e){var n,o=this,i=256,a=6,s="random",u=e.pow(i,a),c=e.pow(2,52),l=2*c,f=i-1;function h(m,w,E){var b=[],C=v(function O(F,P){var U,Q=[],V=typeof F;if(P&&V=="object")for(U in F)try{Q.push(O(F[U],P-1))}catch(X){}return Q.length?Q:V=="string"?F:F+"\0"}((w=w==1?{entropy:!0}:w||{}).entropy?[m,g(t)]:m==null?function(){try{var O;return n&&(O=n.randomBytes)?O=O(i):(O=new Uint8Array(i),(o.crypto||o.msCrypto).getRandomValues(O)),g(O)}catch(U){var F=o.navigator,P=F&&F.plugins;return[+new Date,o,P,o.screen,g(t)]}}():m,3),b),S=new d(b),N=function(){for(var O=S.g(a),F=u,P=0;O=l;)O/=2,F/=2,P>>>=1;return(O+P)/F};return N.int32=function(){return 0|S.g(4)},N.quick=function(){return S.g(4)/4294967296},N.double=N,v(g(S.S),t),(w.pass||E||function(O,F,P,U){return U&&(U.S&&p(U,S),O.state=function(){return p(S,{})}),P?(e[s]=O,F):O})(N,C,"global"in w?w.global:this==e,w.state)}function d(m){var w,E=m.length,b=this,C=0,S=b.i=b.j=0,N=b.S=[];for(E||(m=[E++]);C=1||s===0);var u=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*i*u,n=this.mean+this.stdDev*a*u,this.truncated&&!this.isValidTruncated(e)||(o=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},r.prototype.convertValue=function(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)},r.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},r}(),Rh=function(){function r(t,e,n,o){this.alpha=t,this.beta=1/e,this.dtype=n;var i=o||Math.random();this.randu=bi(i.toString()),this.randn=new ya(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return r.prototype.nextValue=function(){for(var t,e,n,o,i,a;;){do o=this.randn.nextValue(),a=1+this.c*o;while(a<=0);if(a*=a*a,e=1-.331*(t=o*o)*t,n=.5*t+this.d*(1-a+Math.log(a)),(i=this.randu())=1+t.length,function(){return"input rank is "+n.rank+" but should be > than blockShape.length "+t.length}),B(e.length===t.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+t.length}),B(n.shape[0]%o==0,function(){return"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockShape "+t.join(" * ")+" === "+o}),W.runKernelFunc(function(i){return i.batchToSpaceND(n,t,e)},{$x:n},function(i){return{$x:function(){return i.spaceToBatchND(t,e)}}})}}),Th=_({broadcastTo_:function(r,t){var e=k(r,"broadcastTo","x"),n=e.shape;if(t.some(function(u){return!(u>0)||u%1!=0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.lengthe.rank){for(var o=e.shape.slice();o.length=0;a--)if(e.shape[a]===t[a])i[a]=1;else if(e.shape[a]!==1)throw new Error("broadcastTo(): ["+n+"] cannot be broadcast to ["+t+"].");var s=i.map(function(u,c){return u>1?c:-1}).filter(function(u){return u>=0});return s.length===0?e.clone():W.runKernelFunc(function(u){return u.tile(e,i)},{input:e},function(u){return{input:function(){return u.sum(s,!0)}}})}}),Dh=_({cast_:function(r,t){var e=k(r,"x","cast");if(!R(t))throw new Error("Failed to cast to unknown dtype "+t);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");var n={dtype:t};return W.runKernelFunc(function(o){return o.cast(e,t)},{x:e},function(o){return{x:function(){return o.clone()}}},"Cast",n)}}),Fh=_({clone_:function(r){var t=k(r,"x","clone",null);return W.runKernelFunc(function(){return W.makeTensorFromDataId(t.dataId,t.shape,t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),Ph=_({cumsum_:function(r,t,e,n){t===void 0&&(t=0),e===void 0&&(e=!1),n===void 0&&(n=!1);var o=k(r,"x","cumsum"),i=tr([t|=0],o.rank),a=o;i!=null&&(a=o.transpose(i));var s=nr(1,o.rank)[0],u=W.runKernelFunc(function(c){return c.cumsum(a,s,e,n)},{permutedX:a},function(c){return{permutedX:function(){return c.cumsum(t,e,!n)}}});return i!=null&&(u=u.transpose(i)),u}}),Nh=_({depthToSpace_:function(r,t,e){e===void 0&&(e="NHWC");var n=k(r,"x","depthToSpace"),o=e==="NHWC"?n.shape[1]:n.shape[2],i=e==="NHWC"?n.shape[2]:n.shape[3],a=e==="NHWC"?n.shape[3]:n.shape[1];return B(o*t>=0,function(){return`Negative dimension size caused by overflow when multiplying `+o+" and "+t+` for depthToSpace with input shape `+n.shape}),B(i*t>=0,function(){return`Negative dimension size caused by overflow when multiplying `+i+" and "+t+` for depthToSpace with input shape `+n.shape}),B(a%(t*t)==0,function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+a+" for depthToSpace with input shape "+n.shape}),W.runKernelFunc(function(s){return s.depthToSpace(n,t,e)},{$x:n})}}),qn=_({expandDims_:function(r,t){t===void 0&&(t=0);var e=k(r,"x","expandDims",null);B(t<=e.rank,function(){return"Axis must be <= rank of the tensor"});var n=e.shape.slice();return t<0&&(B(-(e.rank+1)<=t,function(){return"Axis must be in the interval ["+-(e.rank+1)+", "+e.rank+"]"}),t=e.rank+t+1),n.splice(t,0,1),rr(e,n)}}),Hu=_({eye_:function(r,t,e,n){n===void 0&&(n="float32"),t==null&&(t=r);for(var o=ot([r,t],n),i=r<=t?r:t,a=0;a2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);e=e||Math.random();var s=a===1?o.as2D(1,-1):o,u=W.runKernelFunc(function(c){return c.multinomial(s,n,t,e)},{logits2D:s});return a===1?u.as1D():u}}),xa=_({oneHot_:function(r,t,e,n){if(e===void 0&&(e=1),n===void 0&&(n=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var o=k(r,"indices","oneHot","int32"),i=o.shape.concat([t]);return o=o.flatten(),W.runKernelFunc(function(a){return a.oneHot(o,t,e,n)},{$indices:o},function(a){return{$indices:function(){return en(o.shape,"float32")}}}).reshape(i)}}),Yr=_({pad_:function(r,t,e){e===void 0&&(e=0);var n=k(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:t,constantValue:e};return W.runKernelFunc(function(i){return i.pad(n,t,e)},{x:n},function(i){var a=t.map(function(s){return s[0]});return{x:function(){return i.slice(a,n.shape)}}},"PadV2",o)}}),Mh=_({pad1d_:function(r,t,e){return e===void 0&&(e=0),B(t.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),Yr(r,[t],e)}}),Lh=_({pad2d_:function(r,t,e){return e===void 0&&(e=0),B(t.length===2&&t[0].length===2&&t[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Yr(r,t,e)}}),Wh=_({pad3d_:function(r,t,e){return e===void 0&&(e=0),B(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Yr(r,t,e)}}),_h=_({pad4d_:function(r,t,e){return e===void 0&&(e=0),B(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Yr(r,t,e)}}),Qh=_({rand_:function(r,t,e){var n=Re(r),o=null;if(e==null||e==="float32")o=new Float32Array(n);else if(e==="int32")o=new Int32Array(n);else{if(e!=="bool")throw new Error("Unknown data type "+e);o=new Uint8Array(n)}for(var i=0;i=1+t.length,function(){return"input rank "+n.rank+" should be > than [blockShape] "+t.length}),B(e.length===t.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+t.length}),B(n.shape.reduce(function(o,i,a){return a>0&&a<=t.length?o&&(i+e[a-1][0]+e[a-1][1])%t[a-1]==0:o},!0),function(){return"input spatial dimensions "+n.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+t.toString()}),W.runKernelFunc(function(o){return o.spaceToBatchND(n,t,e)},{$x:n},function(o){return{$x:function(){return o.batchToSpaceND(t,e)}}})}}),Gu=_({squeeze_:function(r,t){var e=k(r,"x","squeeze");return rr(e,an(e.shape,t).newShape)}}),jn=_({stack_:function(r,t){t===void 0&&(t=0);var e=Ho(r,"tensors","stack");if(B(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return e[0].expandDims(t);var n=e[0].rank,o=e[0].shape,i=e[0].dtype;B(t<=n,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(s){Je(o,s.shape,"All tensors passed to stack must have matching shapes")}),e.forEach(function(s){B(i===s.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=e.map(function(s){return s.expandDims(t)});return An(a,t)}}),vo=_({tile_:function(r,t){var e=k(r,"x","tile",null);B(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+t+"."});var n=[e],o={reps:t};return W.runKernelFunc(function(i,a){var s=i.tile(e,t);return a([e]),s},{x:e},function(i,a){var s=a[0];return{x:function(){var u=Bt(s);if(s.rank===1)for(var c=0;c=-e.shape.length&&t=2*t+1||o%2==1?a.push(o):i.push(o);n.push.apply(n,i),n.push(0),n.push.apply(n,a)}return n}function Ci(r,t,e,n){n===void 0&&(n=!0);var o=[];n?o.push(r[0]/e):o.push(r[0]*e);for(var i=1;ir.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+r.rank);if(r.size===0)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+r.shape+".");for(var e=t.shape,n=e[e.length-1],o=1,i=0;i1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,i="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+t.shape+", shape: "+r+", sliceDim: "+n+", and batchDim: "+o+".";if(e.rank1?t.shape[n-1]:1,i=e.length,a=1,s=o;s0;)1&r&&t.push(e),r/=2,e++;return t}function Si(r,t,e){for(var n=[],o=0;o0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=n[o];return i<0&&(i+=s),i=Me(0,i,s-1)}function $u(r,t,e,n,o){var i=t[o],a=e[o]||1;(r&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=n[o];return i<0&&(i+=s),i=a>0?Me(0,i,s):Me(-1,i,s-1)}function Ca(r,t,e){for(var n=e.length,o=0;o1){n=o;break}for(o=n+1;o0||e[o]!==r[o])return!1;return!0}function Ia(r,t){for(var e=r.length>0?r[r.length-1]:1,n=0;n0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+i+" variables is trainable."});var a=W.gradients(r,t,null,!0),s=a.value,u=a.grads;B(u.some(function(l){return l!=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()."}),B(s.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return t.forEach(function(l,f){u[f]!=null&&(c[l.name]=u[f])}),o!=null&&o.forEach(function(l){return c[l.name]=null}),{value:s,grads:c}}function Ri(r){return W.customGrad(r)}function Bi(r){if(r.filter(function(t){return t==null}).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.`)}var Cr=_({softmax_:function(r,t){t===void 0&&(t=-1);var e=k(r,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+t);return W.runKernelFunc(function(n,o){var i=n.softmax(e,t);return o([i]),i},{logits:e},function(n,o){var i=o[0],a=n.mul(i);return{logits:function(){return a.sub(a.sum([t],!0).mul(i))}}},"Softmax",{dim:t},[],[!0])}}),Gh=_({logSoftmax_:function(r,t){t===void 0&&(t=-1);var e=k(r,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and axis was "+t);return Ri(function(n,o){var i=n.max(t,!0),a=n.sub(i),s=a.toFloat().sub(a.exp().sum(t,!0).log());return o([s]),{value:s,gradFunc:function(u,c){var l=c[0].exp();return u.sub(u.sum(t,!0).mul(l))}}})(e)}}),ec=function(){function r(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return r.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},r.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},r.prototype.has=function(t){return this.data.has(t)},r.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},r.prototype.numDataIds=function(){return this.dataIdsCount},r}(),tc=function(){function r(){}return r.prototype.time=function(t){return q("time")},r.prototype.read=function(t){return q("read")},r.prototype.readSync=function(t){return q("readSync")},r.prototype.numDataIds=function(){return q("numDataIds")},r.prototype.disposeData=function(t){return q("disposeData")},r.prototype.write=function(t,e,n){return q("write")},r.prototype.move=function(t,e,n,o){return q("move")},r.prototype.memory=function(){return q("memory")},r.prototype.floatPrecision=function(){return q("floatPrecision")},r.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},r.prototype.batchMatMul=function(t,e,n,o){return q("batchMatMul")},r.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,q("fusedBatchMatMul")},r.prototype.slice=function(t,e,n){return q("slice")},r.prototype.stridedSlice=function(t,e,n,o){return q("stridedSlice")},r.prototype.unstack=function(t,e){return q("unstack")},r.prototype.reverse=function(t,e){return q("reverse")},r.prototype.concat=function(t,e){return q("concat")},r.prototype.neg=function(t){return q("neg")},r.prototype.add=function(t,e){return q("add")},r.prototype.addN=function(t){return q("addN")},r.prototype.subtract=function(t,e){return q("subtract")},r.prototype.multiply=function(t,e){return q("multiply")},r.prototype.realDivide=function(t,e){return q("realDivide")},r.prototype.floorDiv=function(t,e){return q("floorDiv")},r.prototype.sum=function(t,e){return q("sum")},r.prototype.prod=function(t,e){return q("prod")},r.prototype.unsortedSegmentSum=function(t,e,n){return q("unsortedSegmentSum")},r.prototype.argMin=function(t,e){return q("argMin")},r.prototype.argMax=function(t,e){return q("argMax")},r.prototype.equal=function(t,e){return q("equal")},r.prototype.notEqual=function(t,e){return q("notEqual")},r.prototype.less=function(t,e){return q("less")},r.prototype.lessEqual=function(t,e){return q("lessEqual")},r.prototype.greater=function(t,e){return q("greater")},r.prototype.greaterEqual=function(t,e){return q("greaterEqual")},r.prototype.logicalNot=function(t){return q("logicalNot")},r.prototype.logicalAnd=function(t,e){return q("logicalAnd")},r.prototype.logicalOr=function(t,e){return q("logicalOr")},r.prototype.where=function(t){return q("where")},r.prototype.select=function(t,e,n){return q("select")},r.prototype.topk=function(t,e,n){return q("topk")},r.prototype.min=function(t,e){return q("min")},r.prototype.minimum=function(t,e){return q("minimum")},r.prototype.mod=function(t,e){return q("mod")},r.prototype.max=function(t,e){return q("max")},r.prototype.maximum=function(t,e){return q("maximum")},r.prototype.all=function(t,e){return q("all")},r.prototype.any=function(t,e){return q("any")},r.prototype.squaredDifference=function(t,e){return q("squaredDifference")},r.prototype.ceil=function(t){return q("ceil")},r.prototype.floor=function(t){return q("floor")},r.prototype.round=function(t){return q("round")},r.prototype.sign=function(t){return q("sign")},r.prototype.isNaN=function(t){return q("isNaN")},r.prototype.isInf=function(t){return q("isInf")},r.prototype.isFinite=function(t){return q("isFinite")},r.prototype.pow=function(t,e){return q("pow")},r.prototype.exp=function(t){return q("exp")},r.prototype.expm1=function(t){return q("expm1")},r.prototype.softmax=function(t,e){return q("softmax")},r.prototype.log=function(t){return q("log")},r.prototype.log1p=function(t){return q("log1p")},r.prototype.sqrt=function(t){return q("sqrt")},r.prototype.rsqrt=function(t){return q("rsqrt")},r.prototype.square=function(t){return q("square")},r.prototype.reciprocal=function(t){return q("reciprocal")},r.prototype.relu=function(t){return q("relu")},r.prototype.relu6=function(t){return q("relu6")},r.prototype.prelu=function(t,e){return q("prelu")},r.prototype.elu=function(t){return q("elu")},r.prototype.eluDer=function(t,e){return q("eluDer")},r.prototype.selu=function(t){return q("selu")},r.prototype.int=function(t){return q("int")},r.prototype.clip=function(t,e,n){return q("clip")},r.prototype.abs=function(t){return q("abs")},r.prototype.complexAbs=function(t){return q("complexAbs")},r.prototype.sigmoid=function(t){return q("sigmoid")},r.prototype.softplus=function(t){return q("softplus")},r.prototype.sin=function(t){return q("sin")},r.prototype.cos=function(t){return q("cos")},r.prototype.tan=function(t){return q("tan")},r.prototype.asin=function(t){return q("asin")},r.prototype.acos=function(t){return q("acos")},r.prototype.atan=function(t){return q("atan")},r.prototype.atan2=function(t,e){return q("atan2")},r.prototype.sinh=function(t){return q("sinh")},r.prototype.cosh=function(t){return q("cosh")},r.prototype.tanh=function(t){return q("tanh")},r.prototype.asinh=function(t){return q("asinh")},r.prototype.acosh=function(t){return q("acosh")},r.prototype.atanh=function(t){return q("atanh")},r.prototype.erf=function(t){return q("erf")},r.prototype.step=function(t,e){return q("step")},r.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,q("fusedConv2d")},r.prototype.conv2d=function(t,e,n){return q("conv2d")},r.prototype.conv2dDerInput=function(t,e,n){return q("conv2dDerInput")},r.prototype.conv2dDerFilter=function(t,e,n){return q("conv2dDerFilter")},r.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,q("fusedDepthwiseConv2D")},r.prototype.depthwiseConv2D=function(t,e,n){return q("depthwiseConv2D")},r.prototype.depthwiseConv2DDerInput=function(t,e,n){return q("depthwiseConv2DDerInput")},r.prototype.depthwiseConv2DDerFilter=function(t,e,n){return q("depthwiseConv2DDerFilter")},r.prototype.conv3d=function(t,e,n){return q("conv3d")},r.prototype.conv3dDerInput=function(t,e,n){return q("conv3dDerInput")},r.prototype.conv3dDerFilter=function(t,e,n){return q("conv3dDerFilter")},r.prototype.maxPool=function(t,e){return q("maxPool")},r.prototype.maxPoolBackprop=function(t,e,n,o){return q("maxPoolBackprop")},r.prototype.avgPool=function(t,e){return q("avgPool")},r.prototype.avgPoolBackprop=function(t,e,n){return q("avgPoolBackprop")},r.prototype.avgPool3d=function(t,e){return q("avgPool3d")},r.prototype.avgPool3dBackprop=function(t,e,n){return q("avgPool3dBackprop")},r.prototype.maxPool3d=function(t,e){return q("maxPool3d")},r.prototype.maxPool3dBackprop=function(t,e,n,o){return q("maxPool3dBackprop")},r.prototype.reshape=function(t,e){return q("reshape")},r.prototype.cast=function(t,e){return q("cast")},r.prototype.tile=function(t,e){return q("tile")},r.prototype.pad=function(t,e,n){return q("pad")},r.prototype.transpose=function(t,e){return q("transpose")},r.prototype.gather=function(t,e,n){return q("gather")},r.prototype.gatherND=function(t,e){return q("gatherND")},r.prototype.scatterND=function(t,e,n){return q("scatterND")},r.prototype.batchToSpaceND=function(t,e,n){return q("batchToSpaceND")},r.prototype.spaceToBatchND=function(t,e,n){return q("spaceToBatchND")},r.prototype.resizeBilinear=function(t,e,n,o){return q("resizeBilinear")},r.prototype.resizeBilinearBackprop=function(t,e,n){return q("resizeBilinearBackprop")},r.prototype.resizeNearestNeighbor=function(t,e,n,o){return q("resizeNearestNeighbor")},r.prototype.resizeNearestNeighborBackprop=function(t,e,n){return q("resizeNearestNeighborBackprop")},r.prototype.batchNormalization=function(t,e,n,o,i,a){return q("batchNormalization")},r.prototype.localResponseNormalization4D=function(t,e,n,o,i){return q("localResponseNormalization4D")},r.prototype.LRNGrad=function(t,e,n,o,i,a,s){return q("LRNGrad")},r.prototype.multinomial=function(t,e,n,o){return q("multinomial")},r.prototype.oneHot=function(t,e,n,o){return q("oneHot")},r.prototype.cumsum=function(t,e,n,o){return q("cumsum")},r.prototype.nonMaxSuppression=function(t,e,n,o,i){return q("nonMaxSuppression")},r.prototype.fft=function(t){return q("fft")},r.prototype.ifft=function(t){return q("ifft")},r.prototype.complex=function(t,e){return q("complex")},r.prototype.real=function(t){return q("real")},r.prototype.imag=function(t){return q("imag")},r.prototype.cropAndResize=function(t,e,n,o,i,a){return q("cropAndResize")},r.prototype.depthToSpace=function(t,e,n){return q("depthToSpace")},r.prototype.split=function(t,e,n){return q("split")},r.prototype.sparseToDense=function(t,e,n,o){return q("sparseToDense")},r.prototype.diag=function(t){return q("diag")},r.prototype.fill=function(t,e,n){return q("fill")},r.prototype.onesLike=function(t){return q("onesLike")},r.prototype.zerosLike=function(t){return q("zerosLike")},r.prototype.linspace=function(t,e,n){return q("linspace")},r.prototype.dispose=function(){return q("dispose")},r}();function q(r){throw new Error("'"+r+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function Ir(r,t){for(var e=r.length,n=[],o=0;o1&&a===1&&n.unshift(i)}return n}function gn(r,t){for(var e=[],n=0;n1)&&e.unshift(i)}return e}function gt(r,t){for(var e=[],n=Math.max(r.length,t.length),o=0;o>>1)]);v>0?f=d+1:(h=d,p=!v)}return p?f:-f-1}(i,a,s||Zh)}(r,t,e),o=n<0?-(n+1):n;r.splice(o,0,t)}function Zh(r,t){return r>t?1:ro}).sort(oc),c=i>0?-.5/i:0,l=[],f=[];l.length0;){var h=u.pop(),d=h.score,p=h.boxIndex,v=h.suppressBeginIndex;if(d=v;--m){var w=qh(r,p,l[m]);if(w>=n){g=!0;break}if(h.score=h.score*Yh(n,c,w),h.score<=o)break}h.suppressBeginIndex=l.length,g||(h.score===d?(l.push(p),f.push(h.score)):h.score>o&&Kh(u,h,oc))}var E=l.length;return s&&(l.fill(0,E),f.fill(0,E)),{selectedIndices:vn(l,"int32"),selectedScores:vn(f,"float32"),numValidOutputs:Fe(E,"int32")}}function qh(r,t,e){var n=r.subarray(4*t,4*t+4),o=r.subarray(4*e,4*e+4),i=Math.min(n[0],n[2]),a=Math.min(n[1],n[3]),s=Math.max(n[0],n[2]),u=Math.max(n[1],n[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),f=Math.max(o[0],o[2]),h=Math.max(o[1],o[3]),d=(s-i)*(u-a),p=(f-c)*(h-l);if(d<=0||p<=0)return 0;var v=Math.max(i,c),g=Math.max(a,l),m=Math.min(s,f),w=Math.min(u,h),E=Math.max(m-v,0)*Math.max(w-g,0);return E/(d+p-E)}function Yh(r,t,e){var n=Math.exp(t*e*e);return e<=r?n:0}function oc(r,t){return r.score-t.score||r.score===t.score&&t.boxIndex-r.boxIndex}function ic(r,t,e){var n=new Array(r.rank).fill(0),o=r.shape.slice();return t.map(function(i){o[e]=i;var a=r.slice(n,o);return n[e]+=i,a})}function ac(r,t){for(var e=new Array(r.rank),n=0;n":"<",u=e?"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 * `+n+`; int bestIndex = inOffset; float bestValue = getA(batch, bestIndex); for (int i = 0; i < `+n+`; i++) { int inIdx = `+u+`; float candidate = getA(batch, inIdx); if (candidate `+s+` bestValue) { bestValue = candidate; bestIndex = inIdx; } } setOutput(float(bestIndex)); } `};function uc(r,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return r+"."+e})}function zn(r,t){return t===1?[r]:uc(r,t)}function Dn(){var r,t,e,n,o,i,a,s,u,c;return J().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",t="in",e="out",n="in",o="texture",i="outputColor",a="out vec4 outputColor;",s=` 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) `,u="",c=` #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))); } `):(r="",t="attribute",e="varying",n="varying",o="texture2D",i="gl_FragColor",a="",s=` #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)); } `,u=` uniform float INFINITY; bool isinf(float val) { return abs(val) == INFINITY; } bvec4 isinf(vec4 val) { return equal(abs(val), vec4(INFINITY)); } `,c=` int round(float value) { return int(floor(value + 0.5)); } ivec4 round(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `),{version:r,attribute:t,varyingVs:e,varyingFs:n,texture2D:o,output:i,defineOutput:a,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function eo(r,t,e){e===void 0&&(e="index");var n=dt(t);return n.map(function(o,i){return"int "+r[i]+" = "+e+" / "+o+"; "+(i===n.length-1?"int "+r[i+1]+" = "+e+" - "+r[i]+" * "+o:"index -= "+r[i]+" * "+o)+";"}).join("")}function Na(r){var t=dt(r).map(function(e){return e.toString()});return` int getFlatIndex(ivec3 coords) { return coords.x * `+t[0]+" + coords.y * "+t[1]+` + coords.z; } `}var cc=` 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; } `;function nd(r,t,e,n){var o=[];r.forEach(function(d){var p=Re(d.shapeInfo.logicalShape);d.shapeInfo.isUniform?o.push("uniform float "+d.name+(p>1?"["+p+"]":"")+";"):(o.push("uniform sampler2D "+d.name+";"),o.push("uniform int offset"+d.name+";"))});var i,a,s=o.join(` `),u=r.map(function(d){return function(p,v,g){g===void 0&&(g=!1);var m="";m+=g?lc(p):Ao(p);var w=p.shapeInfo.logicalShape,E=v.logicalShape;return w.length<=E.length&&(m+=g?function(b,C){var S,N=b.name,O=N.charAt(0).toUpperCase()+N.slice(1),F="get"+O+"AtOutCoords",P=b.shapeInfo.logicalShape.length,U=C.logicalShape.length,Q=Ir(b.shapeInfo.logicalShape,C.logicalShape),V=Yt(U),X=U-P,te=["x","y","z","w","u","v"];S=P===0?"":U<2&&Q.length>=1?"coords = 0;":Q.map(function(ke){return"coords."+te[ke+X]+" = 0;"}).join(` `);var ue="";ue=U<2&&P>0?"coords":b.shapeInfo.logicalShape.map(function(ke,Ne){return"coords."+te[Ne+X]}).join(", ");var se="return outputValue;",oe=Re(b.shapeInfo.logicalShape)===1,he=Re(C.logicalShape)===1;if(P!==1||oe||he){if(oe&&!he)se=U===1?` return vec4(outputValue.x, outputValue.x, 0., 0.); `:` return vec4(outputValue.x); `;else if(Q.length){var pe=P-2,xe=P-1;Q.indexOf(pe)>-1&&Q.indexOf(xe)>-1?se="return vec4(outputValue.x);":Q.indexOf(pe)>-1?se="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":Q.indexOf(xe)>-1&&(se="return vec4(outputValue.xx, outputValue.zz);")}}else se=` return vec4(outputValue.xy, outputValue.xy); `;return` vec4 `+F+`() { `+V+` coords = getOutputCoords(); `+S+` vec4 outputValue = get`+O+"("+ue+`); `+se+` } `}(p,v):function(b,C){var S=b.name,N=S.charAt(0).toUpperCase()+S.slice(1),O="get"+N+"AtOutCoords",F=C.texShape,P=b.shapeInfo.texShape,U=b.shapeInfo.logicalShape.length,Q=C.logicalShape.length;if(!b.shapeInfo.isUniform&&U===Q&&b.shapeInfo.flatOffset==null&&Ke(P,F))return` float `+O+`() { return sampleTexture(`+S+`, resultUV); } `;var V,X=Yt(Q),te=Ir(b.shapeInfo.logicalShape,C.logicalShape),ue=Q-U,se=["x","y","z","w","u","v"];V=U===0?"":Q<2&&te.length>=1?"coords = 0;":te.map(function(he){return"coords."+se[he+ue]+" = 0;"}).join(` `);var oe="";return oe=Q<2&&U>0?"coords":b.shapeInfo.logicalShape.map(function(he,pe){return"coords."+se[pe+ue]}).join(", "),` float `+O+`() { `+X+` coords = getOutputCoords(); `+V+` return get`+N+"("+oe+`); } `}(p,v)),m}(d,t,n)}).join(` `),c=t.texShape,l=Dn(),f=function(d){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return `+d.texture2D+`(textureSampler, uv).r; } `}(l),h=function(d){return d.version+` precision highp float; precision highp int; precision highp sampler2D; `+d.varyingFs+` vec2 resultUV; `+d.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; `+d.defineSpecialNaN+` `+d.defineSpecialInf+` `+d.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); } `+rd+` `+od+` `+id+` `}(l);return t.isPacked?(i=function(d,p){switch(d.length){case 0:return` int getOutputCoords() { return 0; } `;case 1:return function(b,C){var S=[Math.ceil(C[0]/2),Math.ceil(C[1]/2)];return S[0]===1?` int getOutputCoords() { return 2 * int(resultUV.x * `+S[1]+`.0); } `:S[1]===1?` int getOutputCoords() { return 2 * int(resultUV.y * `+S[0]+`.0); } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+S[0]+", "+S[1]+`)); return 2 * (resTexRC.x * `+S[1]+` + resTexRC.y); } `}(0,p);case 2:return function(b,C){var S=[Math.ceil(C[0]/2),Math.ceil(C[1]/2)];if(Ke(b,C))return` ivec2 getOutputCoords() { return 2 * ivec2(resultUV.yx * vec2(`+S[0]+", "+S[1]+`)); } `;var N=Math.ceil(b[1]/2);return` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+S[0]+", "+S[1]+`)); int index = resTexRC.x * `+S[1]+` + resTexRC.y; int r = 2 * (index / `+N+`); int c = imod(index, `+N+`) * 2; return ivec2(r, c); } `}(d,p);case 3:return v=d,g=p,m=[Math.ceil(g[0]/2),Math.ceil(g[1]/2)],w=Math.ceil(v[2]/2),E=w*Math.ceil(v[1]/2),` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+m[0]+", "+m[1]+`)); int index = resTexRC.x * `+m[1]+` + resTexRC.y; int b = index / `+E+`; index -= b * `+E+`; int r = 2 * (index / `+w+`); int c = imod(index, `+w+`) * 2; return ivec3(b, r, c); } `;default:return function(b,C){for(var S=[Math.ceil(C[0]/2),Math.ceil(C[1]/2)],N=Math.ceil(b[b.length-1]/2),O=N*Math.ceil(b[b.length-2]/2),F=O,P="",U="b, r, c",Q=2;Q2,function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only inputs with rank above 2."});var o=r[r.length-1],i=Math.ceil(o/t);this.outputShape=r.slice(0,-1),i>1&&this.outputShape.push(i),n||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,c=u.length,l=Yt(c),f=zn("coords",c);if(i===1){var h=Yt(s=c+1);a=` `+h+" sourceLocR = "+h+"("+f.join()+`, 0); ++`+f[c-1]+`; `+h+" sourceLocG = "+h+"("+f.join()+`, 0); ++`+f[c-2]+`; `+h+" sourceLocA = "+h+"("+f.join()+`, 0); --`+f[c-1]+`; `+h+" sourceLocB = "+h+"("+f.join()+`, 0); --`+f[c-2]+";"}else s=c,a=` `+l+` sourceLocR = coords; ++`+f[c-1]+`; `+l+` sourceLocG = coords; ++`+f[c-2]+`; `+l+` sourceLocA = coords; --`+f[c-1]+`; `+l+` sourceLocB = coords; --`+f[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),p="."+d[s-1],v=d.map(function(O){return"int "+O}),g=zn("sourceLocR",s-1).concat("inIdx.r"),m=zn("sourceLocG",s-1).concat("inIdx.g"),w=zn("sourceLocB",s-1).concat("inIdx.b"),E=zn("sourceLocA",s-1).concat("inIdx.a"),b=e==="max"?"greaterThan":"lessThan",C=n?"":` inIdx = round(vec4(getBestIndicesAChannel(`+g.join()+`), getBestIndicesAChannel(`+m.join()+`), getBestIndicesAChannel(`+w.join()+`), getBestIndicesAChannel(`+E.join()+")));",S=`vec4( getAChannel(`+g.join()+`), hasNextCol ? getAChannel(`+m.join()+`) : 0., hasNextRow ? getAChannel(`+w.join()+`) : 0., hasNextRow && hasNextCol ? getAChannel(`+E.join()+") : 0.)",N=n?"":` float getBestIndicesAChannel(`+v.join()+`) { return getChannel(getBestIndicesA(`+d.join()+`), vec2(`+d.slice(-2).join()+`)); }`;this.userCode=` float getAChannel(`+v.join()+`) { return getChannel(getA(`+d.join()+`), vec2(`+d.slice(-2).join()+`)); } `+N+` void main() { `+l+` coords = getOutputCoords(); bool hasNextCol = `+f[c-1]+" < "+(u[c-1]-1)+`; bool hasNextRow = `+f[c-2]+" < "+(u[c-2]-1)+`; `+a+` ivec4 srcIdx = ivec4(sourceLocR`+p+", sourceLocG"+p+`, sourceLocB`+p+", sourceLocA"+p+") * "+t+`; ivec4 inIdx = srcIdx; vec4 bestIndex = vec4(inIdx); vec4 bestValue = `+S+`; for (int i = 0; i < `+t+`; i++) { inIdx = srcIdx; `+C+` vec4 candidate = `+S+`; bvec4 nan = isnan(candidate); bvec4 replace = bvec4( vec4(`+b+`(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); } `},ud=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,i=r.dilationHeight,a=r.dilationWidth,s=r.effectiveFilterHeight,u=r.effectiveFilterWidth,c=s-1-r.padInfo.top,l=u-1-r.padInfo.left,f=1/(t*e);this.userCode=` const ivec2 pads = ivec2(`+c+", "+l+`); const float avgMultiplier = float(`+f+`); 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 < `+s+`; wR += `+i+`) { float dyR = float(dyRCorner + wR) / `+n+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+u+`; wC+= `+a+`) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); dotProd += dyValue * avgMultiplier; } } setOutput(dotProd); } `},cd=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,i=r.strideHeight,a=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,f=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=l-1-r.padInfo.front,p=f-1-r.padInfo.top,v=h-1-r.padInfo.left,g=1/(t*e*n);this.userCode=` const ivec3 pads = ivec3(`+d+", "+p+", "+v+`); const float avgMultiplier = float(`+g+`); 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 < `+l+`; wD += `+s+`) { float dyD = float(dyDCorner + wD) / `+o+`.0; if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < `+f+`; wR += `+u+`) { float dyR = float(dyRCorner + wR) / `+i+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+h+`; wC += `+c+`) { float dyC = float(dyCCorner + wC) / `+a+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); dotProd += dyValue * avgMultiplier; } } } setOutput(dotProd); } `},ld=function(r,t,e,n,o,i){this.outputShape=[],this.variableNames=["x","mean","variance"],gt(r,t),gt(r,e);var a="0.0";n!=null&&(gt(r,n),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";o!=null&&(gt(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=` void main() { float x = getXAtOutCoords(); float mean = getMeanAtOutCoords(); float variance = getVarianceAtOutCoords(); float offset = `+a+`; float scale = `+s+`; float inv = scale * inversesqrt(variance + float(`+i+`)); setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); } `},fd=function(r,t,e,n,o,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],gt(r,t),gt(r,e);var a="vec4(0.0)";n!=null&&(gt(r,n),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";o!=null&&(gt(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=` void main() { vec4 offset = `+a+`; vec4 scale = `+s+`; vec4 x = getXAtOutCoords(); vec4 mean = getMeanAtOutCoords(); vec4 variance = getVarianceAtOutCoords(); vec4 inv = scale * inversesqrt(variance + vec4(`+i+`)); setOutput((x - mean) * inv + offset); } `},hd="return areal * breal - aimag * bimag;",dd="return areal * bimag + aimag * breal;",fc=function(r,t,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=gt(t,e),this.userCode=` float binaryOpComplex( float areal, float aimag, float breal, float bimag) { `+r+` } void main() { float areal = getARealAtOutCoords(); float aimag = getAImagAtOutCoords(); float breal = getBRealAtOutCoords(); float bimag = getBImagAtOutCoords(); setOutput(binaryOpComplex(areal, aimag, breal, bimag)); } `},Oa="return a + b;",Ma="return a - b;",hc="return a * b;",dc="return (a < 0.) ? b * a : a;",sn=function(r,t,e){this.variableNames=["A","B"],this.outputShape=gt(t,e),this.userCode=` float binaryOperation(float a, float b) { `+r+` } void main() { float a = getAAtOutCoords(); float b = getBAtOutCoords(); setOutput(binaryOperation(a, b)); } `},pc=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `,Sr=function(r,t,e,n){n===void 0&&(n=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=gt(t,e);var o=this.outputShape.length,i="";if(n)if(o===0||Re(this.outputShape)===1)i=` result.y = 0.; result.z = 0.; result.w = 0.; `;else if(i=` `+Yt(o)+` coords = getOutputCoords(); `,o===1)i+=` result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y; result.z = 0.; result.w = 0.; `;else{var a=zn("coords",o);i+=` bool nextRowOutOfBounds = (`+a[o-2]+" + 1) >= "+this.outputShape[o-2]+`; bool nextColOutOfBounds = (`+a[o-1]+" + 1) >= "+this.outputShape[o-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) { `+r+` } void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = binaryOperation(a, b); `+i+` setOutput(result); } `},pd=function(){function r(t){this.variableNames=["A"],this.outputShape=t,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 r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,i){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(i,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r}(),vd=function(){function r(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,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 r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,i){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(i,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r}(),gd=function(r){this.variableNames=["real","imag"],this.outputShape=r,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)) ); } `},md=function(r){this.outputShape=[],this.outputShape=Kr(r,1),this.variableNames=r.map(function(s,u){return"T"+u});var t=new Array(r.length-1);t[0]=r[0][1];for(var e=1;e= "+s[u-1]+`) { return getChannel( getT`+u+"("+Fi(a,c,d)+`), vec2(`+Fi(l,c,d)+`)); }`}var p=s.length,v=s[s.length-1];h+=` return getChannel( getT`+p+"("+Fi(a,c,v)+`), vec2(`+Fi(l,c,v)+"));",this.userCode=` float getValue(`+a.map(function(g){return"int "+g})+`) { `+h+` } void main() { `+o+` coords = getOutputCoords(); vec4 result = vec4(getValue(`+i+`), 0., 0., 0.); `+i[n-1]+" = "+i[n-1]+` + 1; if (`+i[n-1]+" < "+e[n-1]+`) { result.g = getValue(`+i+`); } `+i[n-2]+" = "+i[n-2]+` + 1; if (`+i[n-2]+" < "+e[n-2]+`) { result.a = getValue(`+i+`); } `+i[n-1]+" = "+i[n-1]+` - 1; if (`+i[n-2]+" < "+e[n-2]+` && `+i[n-1]+" < "+e[n-1]+`) { result.b = getValue(`+i+`); } setOutput(result); } `};function Fi(r,t,e){var n=r.indexOf(t);return r.map(function(o,i){return i===n?o+" - "+e:o}).join()}var yd=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,i=r.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 < `+r.batchSize+`; b++) { for (int yR = 0; yR < `+r.outHeight+`; yR++) { int xR = wR + yR * `+t+" - "+n+`; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int yC = 0; yC < `+r.outWidth+`; yC++) { int xC = wC + yC * `+e+" - "+o+`; if (xC < 0 || xC >= `+r.inWidth+`) { continue; } if (`+i+`) { 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); } `},xd=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,i=r.dataFormat==="channelsLast",a=t-1-r.padInfo.top,s=e-1-r.padInfo.left,u=i?1:2,c=i?2:3,l=i?3:1;this.userCode=` const ivec2 pads = ivec2(`+a+", "+s+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[`+l+`]; ivec2 dyCorner = ivec2(coords[`+u+"], coords["+c+`]) - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < `+t+`; wR++) { float dyR = float(dyRCorner + wR) / `+n+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+t+` - 1 - wR; for (int wC = 0; wC < `+e+`; wC++) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+e+` - 1 - wC; for (int d2 = 0; d2 < `+r.outChannels+`; d2++) { if (`+i+`) { 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); } `},bd=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.padInfo.front,i=r.padInfo.top,a=r.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 < `+r.batchSize+`; b++) { for (int yF = 0; yF < `+r.outDepth+`; yF++) { int xF = wF + yF * `+t+" - "+o+`; if (xF < 0 || xF >= `+r.inDepth+`) { continue; } for (int yR = 0; yR < `+r.outHeight+`; yR++) { int xR = wR + yR * `+e+" - "+i+`; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int yC = 0; yC < `+r.outWidth+`; yC++) { int xC = wC + yC * `+n+" - "+a+`; if (xC < 0 || xC >= `+r.inWidth+`) { continue; } float dyValue = getDy(b, yF, yR, yC, d2); float xValue = getX(b, xF, xR, xC, d1); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `},wd=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,i=r.strideHeight,a=r.strideWidth,s=t-1-r.padInfo.front,u=e-1-r.padInfo.top,c=n-1-r.padInfo.left;this.userCode=` const ivec3 pads = ivec3(`+s+", "+u+", "+c+`); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyFCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; float dotProd = 0.0; for (int wF = 0; wF < `+t+`; wF++) { float dyF = float(dyFCorner + wF) / `+o+`.0; if (dyF < 0.0 || dyF >= `+r.outDepth+`.0 || fract(dyF) > 0.0) { continue; } int idyF = int(dyF); int wFPerm = `+t+` - 1 - wF; for (int wR = 0; wR < `+e+`; wR++) { float dyR = float(dyRCorner + wR) / `+i+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+e+` - 1 - wR; for (int wC = 0; wC < `+n+`; wC++) { float dyC = float(dyCCorner + wC) / `+a+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+n+` - 1 - wC; for (int d2 = 0; d2 < `+r.outChannels+`; d2++) { float xValue = getDy(batch, idyF, idyR, idyC, d2); float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `},Ed=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,i=r.outChannels/r.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 * `+i+` + dm; float dotProd = 0.0; // TO DO: Vec4 over the batch size for (int b = 0; b < `+r.batchSize+`; b++) { for (int yR = 0; yR < `+r.outHeight+`; yR++) { int xR = wR + yR * `+t+" - "+n+`; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int yC = 0; yC < `+r.outWidth+`; yC++) { int xC = wC + yC * `+e+" - "+o+`; if (xC < 0 || xC >= `+r.inWidth+`) { continue; } float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } } } setOutput(dotProd); } `},Cd=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,i=t-1-r.padInfo.top,a=e-1-r.padInfo.left,s=r.outChannels/r.inChannels;this.userCode=` const ivec2 pads = ivec2(`+i+", "+a+`); 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 < `+t+`; wR++) { float dyR = float(dyRCorner + wR) / `+n+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+t+` - 1 - wR; for (int wC = 0; wC < `+e+`; wC++) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+e+` - 1 - wC; // TO DO: Vec4 over the channelMul for (int dm = 0; dm < `+s+`; dm++) { int d2 = d1 * `+s+` + dm; float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, dm); dotProd += xValue * wValue; } } } setOutput(dotProd); } `},vc=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.padInfo.top,i=r.padInfo.left,a=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterHeight,f=r.filterWidth,h=4*Math.floor(r.inChannels/4),d=r.inChannels%4,p=r.dataFormat==="channelsLast",v=p?1:2,g=p?2:3,m=p?3:1,w="",E="";e&&(w=n?`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); `+e+` }`:` float activation(float x) { `+e+` } `,E="result = activation(result);");var b=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+w+` const ivec2 strides = ivec2(`+a+", "+s+`); const ivec2 pads = ivec2(`+o+", "+i+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d2 = coords[`+m+`]; ivec2 xRCCorner = ivec2(coords[`+v+"], coords["+g+`]) * 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 < `+l+`; wR++) { int xR = xRCorner + wR * `+u+`; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+f+`; wC++) { int xC = xCCorner + wC * `+c+`; if (xC < 0 || xC >= `+r.inWidth+`) { continue; } for (int d1 = 0; d1 < `+h+`; 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 (`+p+`) { 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 (`+(d===1)+`) { if (`+p+`) { dotProd += getX(batch, xR, xC, `+h+`) * getW(wR, wC, `+h+`, d2); } else { dotProd += getX(batch, `+h+`, xR, xC) * getW(wR, wC, `+h+`, d2); } } else if (`+(d===2)+`) { vec2 wValues = vec2( getW(wR, wC, `+h+`, d2), getW(wR, wC, `+h+` + 1, d2) ); if (`+p+`) { vec2 xValues = vec2( getX(batch, xR, xC, `+h+`), getX(batch, xR, xC, `+h+` + 1) ); dotProd += dot(xValues, wValues); } else { vec2 xValues = vec2( getX(batch, `+h+`, xR, xC), getX(batch, `+h+` + 1, xR, xC) ); dotProd += dot(xValues, wValues); } } else if (`+(d===3)+`) { vec3 wValues = vec3( getW(wR, wC, `+h+`, d2), getW(wR, wC, `+h+` + 1, d2), getW(wR, wC, `+h+` + 2, d2) ); if (`+p+`) { vec3 xValues = vec3( getX(batch, xR, xC, `+h+`), getX(batch, xR, xC, `+h+` + 1), getX(batch, xR, xC, `+h+` + 2) ); dotProd += dot(xValues, wValues); } else { vec3 xValues = vec3( getX(batch, `+h+`, xR, xC), getX(batch, `+h+` + 1, xR, xC), getX(batch, `+h+` + 2, xR, xC) ); dotProd += dot(xValues, wValues); } } } } float result = dotProd; `+b+` `+E+` setOutput(result); } `},Id=function(r){this.variableNames=["x","W"],this.outputShape=r.outShape;var t=r.padInfo.front,e=r.padInfo.top,n=r.padInfo.left,o=r.strideDepth,i=r.strideHeight,a=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterDepth,f=r.filterHeight,h=r.filterWidth,d=4*Math.floor(r.inChannels/4),p=r.inChannels%4;this.userCode=` const ivec3 strides = ivec3(`+o+", "+i+", "+a+`); const ivec3 pads = ivec3(`+t+", "+e+", "+n+`); 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 < `+l+`; wF++) { int xF = xFCorner + wF * `+s+`; if (xF < 0 || xF >= `+r.inDepth+`) { continue; } for (int wR = 0; wR < `+f+`; wR++) { int xR = xRCorner + wR * `+u+`; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+h+`; wC++) { int xC = xCCorner + wC * `+c+`; if (xC < 0 || xC >= `+r.inWidth+`) { continue; } for (int d1 = 0; d1 < `+d+`; 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 (`+(p===1)+`) { dotProd += getX(batch, xF, xR, xC, `+d+`) * getW(wF, wR, wC, `+d+`, d2); } else if (`+(p===2)+`) { vec2 xValues = vec2( getX(batch, xF, xR, xC, `+d+`), getX(batch, xF, xR, xC, `+d+` + 1) ); vec2 wValues = vec2( getW(wF, wR, wC, `+d+`, d2), getW(wF, wR, wC, `+d+` + 1, d2) ); dotProd += dot(xValues, wValues); } else if (`+(p===3)+`) { vec3 xValues = vec3( getX(batch, xF, xR, xC, `+d+`), getX(batch, xF, xR, xC, `+d+` + 1), getX(batch, xF, xR, xC, `+d+` + 2) ); vec3 wValues = vec3( getW(wF, wR, wC, `+d+`, d2), getW(wF, wR, wC, `+d+` + 1, d2), getW(wF, wR, wC, `+d+` + 2, d2) ); dotProd += dot(xValues, wValues); } } } } setOutput(dotProd); } `},gc=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.inHeight,i=r.inWidth,a=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,f=r.dilationWidth,h=r.filterHeight,d=r.filterWidth,p=r.outChannels/r.inChannels,v="",g="";e&&(v=n?`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); `+e+` }`:` float activation(float x) { `+e+` } `,g="result = activation(result);");var m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+v+` const ivec2 strides = ivec2(`+u+", "+c+`); const ivec2 pads = ivec2(`+a+", "+s+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; ivec2 xRCCorner = coords.yz * strides - pads; int d2 = coords.w; int d1 = d2 / `+p+`; int q = d2 - d1 * `+p+`; 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 < `+h+`; wR++) { int xR = xRCorner + wR * `+l+`; if (xR < 0 || xR >= `+o+`) { continue; } for (int wC = 0; wC < `+d+`; wC++) { int xC = xCCorner + wC * `+f+`; if (xC < 0 || xC >= `+i+`) { continue; } float xVal = getX(batch, xR, xC, d1); float wVal = getW(wR, wC, d1, q); dotProd += xVal * wVal; } } float result = dotProd; `+m+` `+g+` setOutput(result); } `},mc=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.outShape;for(var o=r.inHeight,i=r.inWidth,a=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,f=r.dilationWidth,h=r.filterHeight,d=r.filterWidth,p=d,v="int xR; int xC; int xCOffset;",g=0;g= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+i+`) { xTexelR`+g+"C"+m+` = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if(xCOffset + 1 >= `+i+`) { xTexelR`+g+"C"+m+`.zw = vec2(0.); } } else { xTexelR`+g+"C"+m+` = vec4(0.); } xCOffset = xC + 1 - 2; if(xR >= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+i+`) { vec4 previous = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if(xCOffset + 1 >= `+i+`) { previous.zw = vec2(0.); } xR`+g+"C"+m+" = vec4(previous.zw, xTexelR"+g+"C"+m+`.xy); } else { xR`+g+"C"+m+" = vec4(0, 0, xTexelR"+g+"C"+m+`.xy); } `:` if(xR >= 0 && xR < `+o+" && xC >= 0 && xC < "+i+`) { xTexelR`+g+"C"+m+` = getX(batch, xR, xC, d1); } else { xTexelR`+g+"C"+m+` = vec4(0.); } xR`+g+"C"+m+" = xTexelR"+g+"C"+m+`; `,m+1= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+i+`) { xTexelR`+g+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1); } `,f>1&&(v+=` xCOffset -= 2; if(xR >= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+i+`) { xTexelR`+g+"C"+m+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+g+"C"+m+` = vec4(0.); } `),v+=` xR`+g+"C"+(m+1)+` = vec4( xTexelR`+g+"C"+m+".zw, xTexelR"+g+"C"+(m+2)+`.xy); `):v+=` xCOffset = xC + `+E+`; if(xR >= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+i+`) { xTexelR`+g+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1); } xR`+g+"C"+(m+1)+" = xTexelR"+g+"C"+(m+2)+`; `}}else m= 0 && xR < `+o+`) { `,s%2==1?(v+=` xCOffset = xC + 1 - `+c+`; if(xCOffset >= 0 && xCOffset < `+i+`) { xTexelR`+g+"C"+m+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+g+"C"+m+` = vec4(0.); } if(xC + 1 >= 0 && xC + 1 < `+i+`) { xTexelR`+g+"C"+(m+2)+` = getX(batch, xR, xC + 1, d1); } else { xTexelR`+g+"C"+(m+2)+` = vec4(0.); } xR`+g+"C"+m+` = vec4( xTexelR`+g+"C"+m+".zw, xTexelR"+g+"C"+(m+2)+`.zw); `,m+1= 0 && xCOffset < `+i+`) { final = getX(batch, xR, xCOffset, d1); } xR`+g+"C"+(m+1)+" = vec4(xTexelR"+g+"C"+(m+2)+`.xy, final.xy); `)):(v+=` if(xC >= 0 && xC < `+i+`) { xTexelR`+g+"C"+m+` = getX(batch, xR, xC, d1); } else { xTexelR`+g+"C"+m+` = vec4(0.); } xCOffset = xC + `+c+`; if(xCOffset >= 0 && xCOffset < `+i+`) { xTexelR`+g+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+g+"C"+(m+2)+` = vec4(0.); } xR`+g+"C"+m+` = vec4( xTexelR`+g+"C"+m+".xy, xTexelR"+g+"C"+(m+2)+`.xy); `,m+11?[""+(a-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],m=g[0],w=g[1],E=g[2],b=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],C=b[0],S=b[1],N=b[2];this.userCode=` const float height_ratio = float(`+m+`); const float width_ratio = float(`+C+`); 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 >= `+i+`) { return; } float height_scale = `+w+`; float width_scale = `+S+`; float in_y = `+E+`; if( in_y < 0.0 || in_y > `+p+` ) { setOutput(float(`+o+`)); return; } float in_x = `+N+`; if( in_x < 0.0 || in_x > `+v+` ) { setOutput(float(`+o+`)); return; } vec2 sourceFracIndexCR = vec2(in_x,in_y); if(`+h+` == 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); } } `},Rd=function(r,t,e){this.variableNames=["x"],this.outputShape=r;var n=r.length,o=r[r.length-1],i=e?"<":">";this.userCode=` int getIndex(int i) { `+(e?"return "+o+" -i - 1;":"return i;")+` } void main() { `+Yt(n)+` coords = getOutputCoords(); int end = `+Ac(n,"coords")+`; float val = 0.0; for (int i = `+o+` - 1; i >= 0; i -= 1) { int idx = getIndex(i); if (idx `+i+` end) { continue; } if (idx == end && `+t+`) { continue; } `+Ac(n,"coords")+` = idx; val += getX(`+function(a,s){if(a===1)return""+s;if(a===2)return s+".x, "+s+".y";if(a===3)return s+".x, "+s+".y, "+s+".z";if(a===4)return s+".x, "+s+".y, "+s+".z, "+s+".w";throw Error("Cumulative sum for rank "+a+" is not yet supported")}(n,"coords")+`); } setOutput(val); } `};function Ac(r,t){if(r===1)return""+t;if(r===2)return t+".y";if(r===3)return t+".z";if(r===4)return t+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}var Bd=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=er.DENSE;var t=Mo(r),e=Dn();this.outputShape=r,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+eo(["r","c","d"],r)+` return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+t[0]+", "+t[1]+`)); int index = 4 * (resTexRC.x * `+t[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); } `+e.output+` = result; } `},kd=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=er.DENSE;var t=Mo(r),e=Dn();this.outputShape=r,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+eo(["r","c","d"],r)+` return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+t[0]+", "+t[1]+`)); int index = 4 * (resTexRC.x * `+t[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)); } `+e.output+` = result; } `},Td=function(){function r(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,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 / `+e+`; int offset_h = imod(h, `+e+`); int in_w = w / `+e+`; int offset_w = imod(w, `+e+`); int offset_d = (offset_h * `+e+` + offset_w) * `+this.getOutputDepthSize()+`; int in_d = d + offset_d; float result = `+this.getInputSamplingString()+`; setOutput(result); } `}return r.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},r.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},r.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},r.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},r.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},r}(),Dd=function(r){this.variableNames=["X"],this.outputShape=[r,r],this.userCode=` void main() { ivec2 coords = getOutputCoords(); float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; setOutput(val); } `},Fd=function(r){this.variableNames=["A"],this.outTexUsage=wn.DOWNLOAD;var t=Dn();this.outputShape=r,this.userCode=` `+cc+` void main() { float x = getAAtOutCoords(); `+t.output+` = encode_float(x); } `},Pd=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=wn.DOWNLOAD;var t=Dn();this.outputShape=r,this.userCode=` `+cc+` void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); `+t.output+` = encode_float(x); } `},Nd=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"];var n=Dn(),o=t[0],i=t[1];this.outputShape=r;var a="result";e&&(a="floor(result * 255. + 0.5)"),this.userCode=` `+Na(r)+` void main() { ivec3 coords = getOutputCoords(); int flatIndex = getFlatIndex(coords); int offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); int r = flatIndex / `+i+`; int c = imod(flatIndex, `+i+`); vec2 uv = (vec2(c, r) + halfCR) / vec2(`+i+".0, "+o+`.0); vec4 values = `+n.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]; } `+n.output+" = vec4("+a+`, 0., 0., 0.); } `},Od=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var n=Dn(),o=t[0],i=t[1];this.outputShape=r;var a="",s="result";e&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;a+=` localCoords = coords; if(localCoords[2] + `+c+" < "+r[2]+`) { localCoords[2] += `+c+`; if(localCoords[1] + `+u+" < "+r[1]+`) { localCoords[1] += `+u+`; flatIndex = getFlatIndex(localCoords); offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); r = flatIndex / `+i+`; c = imod(flatIndex, `+i+`); uv = (vec2(c, r) + halfCR) / vec2(`+i+".0, "+o+`.0); values = `+n.texture2D+`(A, uv); if(offset == 0) { result[`+l+`] = values[0]; } else if(offset == 1) { result[`+l+`] = values[1]; } else if(offset == 2) { result[`+l+`] = values[2]; } else { result[`+l+`] = values[3]; } } } `}this.userCode=` `+Na(r)+` void main() { ivec3 coords = getOutputCoords(); vec4 result = vec4(0.); int flatIndex, r, c, offset; ivec3 localCoords; vec2 uv; vec4 values; `+a+` `+n.output+" = "+s+`; } `},Md="return real * expR - imag * expI;",Ld="return real * expI + imag * expR;",yc=function(r,t,e){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var o=e?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,i=e?n+".0":"1.0";this.userCode=` const float exponentMultiplier = `+o+`; float unaryOpComplex(float real, float expR, float imag, float expI) { `+r+` } float mulMatDFT(int batch, int index) { float indexRatio = float(index) / float(`+n+`); float exponentMultiplierTimesIndexRatio = exponentMultiplier * indexRatio; float result = 0.0; for (int i = 0; i < `+n+`; 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) / `+i+`; } return result; } void main() { ivec2 coords = getOutputCoords(); setOutput(mulMatDFT(coords[0], coords[1])); } `},Wd=function(){function r(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=` uniform float value; void main() { // Input can be obtained from uniform value. setOutput(value); } `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.valueLoc==null&&(e.valueLoc=n.getUniformLocationNoThrow(o,"value")),n.gl.uniform1f(e.valueLoc,t)}},r}(),_d=function(r,t,e){this.variableNames=["A","indices"];var n=r.slice();n[e]=t,this.outputShape=n,this.rank=n.length;var o=Yt(this.rank),i=function(a,s){var u=a.length;if(u>4)throw Error("Gather for rank "+u+" is not yet supported");if(u===1)return"int(getIndices(resRC))";for(var c=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],f=0;f1?"strides[j]":"strides";this.userCode=` `+n+" strides = "+n+"("+this.strides+`); void main() { `+o+` coords = getOutputCoords(); int flattenIndex = 0; for (int j = 0; j < `+this.sliceDim+`; j++) { int index = round(getIndices(coords[0], j)); flattenIndex += index * `+i+`; } setOutput(getX(flattenIndex, coords[1])); } `};function xc(r,t){var e=Dn();return vu(r,t,e.version+` precision highp float; `+e.attribute+` vec3 clipSpacePos; `+e.attribute+` vec2 uv; `+e.varyingVs+` vec2 resultUV; void main() { gl_Position = vec4(clipSpacePos, 1); resultUV = uv; }`)}function bc(r,t){return yu(r,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function wc(r,t){return xu(r,t,new Uint16Array([0,1,2,2,1,3]))}function Jo(r,t,e,n,o,i,a){wu(e,n);var s=bu(r,t),u=r.TEXTURE_2D;return We(r,t,function(){return r.bindTexture(u,s)}),We(r,t,function(){return r.texParameteri(u,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)}),We(r,t,function(){return r.texParameteri(u,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}),We(r,t,function(){return r.texParameteri(u,r.TEXTURE_MIN_FILTER,r.NEAREST)}),We(r,t,function(){return r.texParameteri(u,r.TEXTURE_MAG_FILTER,r.NEAREST)}),We(r,t,function(){return r.texImage2D(u,0,o,e,n,0,i,a,null)}),We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)}),s}function Ec(r,t,e,n,o){var i=fi(e,n);return Jo(r,t,i[0],i[1],o.internalFormatFloat,o.textureFormatFloat,r.FLOAT)}function Cc(r,t,e,n,o){var i=fi(e,n);return Jo(r,t,i[0],i[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Ic(r,t,e,n,o){var i=fi(e,n);return Jo(r,t,i[0],i[1],r.RGBA,r.RGBA,r.UNSIGNED_BYTE)}function Sc(r,t,e,n,o){var i=Lo(e,n);return Jo(r,t,i[0],i[1],o.internalFormatPackedFloat,r.RGBA,r.FLOAT)}function Rc(r,t,e,n,o){var i=Lo(e,n);return Jo(r,t,i[0],i[1],o.internalFormatPackedHalfFloat,r.RGBA,o.textureTypeHalfFloat)}function Bc(r,t,e,n){return We(r,t,function(){return r.bindBuffer(r.ARRAY_BUFFER,n)}),ha(r,t,e,"clipSpacePos",n,3,20,0)&&ha(r,t,e,"uv",n,2,20,12)}function kc(r,t,e,n,o,i,a){var s,u,c;We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)}),i instanceof Uint8Array?(s=new Uint8Array(n*o*4),u=r.UNSIGNED_BYTE,c=r.RGBA):(s=new Float32Array(n*o*4),u=r.FLOAT,c=a.internalFormatPackedFloat),s.set(i),We(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,c,n,o,0,r.RGBA,u,s)}),We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function Tc(r,t,e,n){We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)}),n.data instanceof Uint8Array?We(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,n.width,n.height,0,r.RGBA,r.UNSIGNED_BYTE,n.data)}):We(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,n)}),We(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function Dc(r,t,e,n,o){var i=r.createBuffer();We(r,t,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,i)});var a=16*e*n;return We(r,t,function(){return r.bufferData(r.PIXEL_PACK_BUFFER,a,r.STREAM_READ)}),We(r,t,function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,0)}),We(r,t,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,null)}),i}function Fc(r,t,e){var n=r,o=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function Pc(r,t,e,n,o){var i=fi(e,n),a=i[0],s=i[1],u=new Uint8Array(e*n*4);return We(r,t,function(){return r.readPixels(0,0,a,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Nc(r,t,e,n,o,i,a,s){var u=r,c=new Float32Array(function(l,f){var h=Lo(l,f);return h[0]*h[1]*4}(i,a));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function Oc(r,t,e,n){var o=new Float32Array(e*n*4);return We(r,t,function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,o)}),o}var zd=Object.freeze({createVertexShader:xc,createVertexBuffer:bc,createIndexBuffer:wc,createFloat32MatrixTexture:Ec,createFloat16MatrixTexture:Cc,createUnsignedBytesMatrixTexture:Ic,createPackedMatrixTexture:Sc,createFloat16PackedMatrixTexture:Rc,bindVertexProgramAttributeStreams:Bc,uploadDenseMatrixToTexture:kc,uploadPixelDataToTexture:Tc,createBufferFromOutputTexture:Dc,downloadFloat32MatrixFromBuffer:Fc,downloadByteEncodedFloatMatrixFromOutputTexture:Pc,downloadPackedMatrixFromBuffer:Nc,downloadMatrixFromPackedOutputTexture:Oc}),Mc=function(){function r(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=J().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,li(e,t)):this.gl=cr(e);var n="WEBGL_color_buffer_float";if(J().getNumber("WEBGL_VERSION")===1){if(this.textureFloatExtension=Wo(this.gl,this.debug,"OES_texture_float"),Hn(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=Wo(this.gl,this.debug,"OES_texture_half_float");else if(J().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Hn(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=Wo(this.gl,this.debug,"EXT_color_buffer_half_float");else if(J().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Hn(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Hn(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=bc(this.gl,this.debug),this.indexBuffer=wc(this.gl,this.debug),this.framebuffer=Eu(this.gl,this.debug),this.textureConfig=fa(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(r.prototype,"debug",{get:function(){return J().getBool("DEBUG")},enumerable:!0,configurable:!0}),r.prototype.dispose=function(){var t=this;if(!this.disposed){this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;We(e,this.debug,function(){return e.finish()}),We(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),We(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),We(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),We(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),We(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},r.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Ec(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Cc(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Ic(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Tc(this.gl,this.debug,t,e)},r.prototype.uploadDenseMatrixToTexture=function(t,e,n,o){this.throwIfDisposed(),kc(this.gl,this.debug,t,e,n,o,this.textureConfig)},r.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Rc(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Sc(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(da(this.gl,this.debug,this.framebuffer),this.outputTexture=null),We(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},r.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,function(){return Pc(o.gl,o.debug,e,n,o.textureConfig)})},r.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,o,i,a){return Nc(this.gl,t,0,0,0,i,a,this.textureConfig)},r.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Fc(this.gl,t,e)},r.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var o=Dc(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),o},r.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},r.prototype.createFence=function(t){var e,n,o=this;if(J().getBool("WEBGL_FENCE_API_ENABLED")){var i=t,a=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var s=i.clientWaitSync(a,0,0);return s===i.ALREADY_SIGNALED||s===i.CONDITION_SATISFIED},e=a}else J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return o.isQueryAvailable(e,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},r.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,function(){return Oc(o.gl,o.debug,e,n)})},r.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=gu(e,this.debug,t),o=xc(e,this.debug),i=mu(e,this.debug);return We(e,this.debug,function(){return e.attachShader(i,o)}),We(e,this.debug,function(){return e.attachShader(i,n)}),Au(e,this.debug,i),this.debug&&pi(e,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=Bc(e,this.debug,this.program,this.vertexBuffer)),i},r.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&We(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},r.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&pi(this.gl,this.debug,this.program),We(this.gl,this.debug,function(){return e.gl.useProgram(t)})},r.prototype.getUniformLocation=function(t,e,n){return n===void 0&&(n=!0),this.throwIfDisposed(),n?Iu(this.gl,this.debug,t,e):Su(this.gl,t,e)},r.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),We(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},r.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},r.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),Ru(this.gl,this.debug,this.program,t,e,n)},r.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},r.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var o=Lo(e,n),i=o[0],a=o[1];this.setOutputMatrixTextureDriver(t,i,a)},r.prototype.setOutputMatrixWriteRegion=function(t,e,n,o){this.setOutputMatrixWriteRegionDriver(n,t,o,e)},r.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},r.prototype.debugValidate=function(){this.program!=null&&pi(this.gl,this.debug,this.program),_o(this.gl)},r.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),We(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},r.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),We(this.gl,this.debug,function(){return t.gl.finish()})},r.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Wo(this.gl,this.debug,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},r.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},r.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},r.prototype.beginQuery=function(){if(J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var o=this.getQueryTimerExtensionWebGL1(),i=o.createQueryEXT();return o.beginQueryEXT(o.TIME_ELAPSED_EXT,i),i},r.prototype.endQuery=function(){if(J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")!==2){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},r.prototype.waitForQueryAndGetTime=function(t){return be(this,void 0,void 0,function(){var e=this;return Se(this,function(n){switch(n.label){case 0:return[4,jt(function(){return e.disposed||e.isQueryAvailable(t,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},r.prototype.getQueryTime=function(t,e){if(e===0)return null;if(e===2){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var o=this.getQueryTimerExtensionWebGL1();return o.getQueryObjectEXT(t,o.QUERY_RESULT_EXT)/1e6},r.prototype.isQueryAvailable=function(t,e){if(e===0)return!0;if(e===2){var n=this.gl,o=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(o=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,o.QUERY_RESULT_AVAILABLE_EXT),this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),i&&!this.disjoint},r.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},r.prototype.pollItems=function(){for(var t=function(n){for(var o=0;o1||jt(function(){return n.pollItems(),n.itemsToPoll.length===0})},r.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),vi(this.gl,this.debug,t,this.framebuffer),this.debug&&_o(this.gl)},r.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(vi(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&_o(this.gl)):da(this.gl,this.debug,this.framebuffer)},r.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},r.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var o=this.gl;vi(o,this.debug,t,this.framebuffer),this.debug&&_o(o),this.outputTexture=t,We(o,this.debug,function(){return o.viewport(0,0,e,n)}),We(o,this.debug,function(){return o.scissor(0,0,e,n)})},r.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,o){var i=this;this.throwIfDisposed(),We(this.gl,this.debug,function(){return i.gl.scissor(t,e,n,o)})},r.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},r.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},r}();function Lc(r,t){if(r.length!==t.length)throw Error("Binary was compiled with "+r.length+" inputs, but was executed with "+t.length+" inputs");r.forEach(function(e,n){var o=e.logicalShape,i=t[n],a=i.shape;if(!Ke(o,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+o+" and "+a+" must match");if(!e.isUniform||!i.isUniform){var s=e.texShape,u=i.isUniform?null:i.texData.texShape;if(!Ke(s,u))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+u+" must match")}})}var Ud=function(r,t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var n=e.filterWidth,o=e.inChannels,i=e.strideWidth,a=e.strideHeight,s=e.padInfo,u=e.outWidth,c=e.dilationWidth,l=e.dilationHeight,f=e.dataFormat,h=s.left,d=s.top,p=o*n,v=Dn(),g=f==="channelsLast",m=g?0:1,w=g?1:2,E="",b=0;b<=1;b++)for(var C=0;C<=1;C++)E+=` blockIndex = rc.y + `+C+`; pos = rc.x + `+b+`; if(blockIndex < `+r[1]+" && pos < "+r[0]+`) { offsetY = int(blockIndex / (`+u+")) * "+a+" - "+d+`; d0 = offsetY + `+l+" * (pos / "+p+`); if(d0 < `+t[m]+` && d0 >= 0) { offsetX = int(mod(float(blockIndex), `+u+".) * "+i+". - "+h+`.); d1 = offsetX + `+c+" * (int(mod(float(pos), "+p+".) / "+o+`.)); if(d1 < `+t[w]+` && d1 >= 0) { ch = int(mod(float(pos), `+o+`.)); if (`+g+`) { innerDims = vec2(d1, ch); result[`+(2*b+C)+`] = getChannel( getA(d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[`+(2*b+C)+`] = 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; `+E+` `+v.output+` = result; } `},Hd=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[];var i,a=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";i=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 = -`+a+"; j <= "+a+`; j++) { int idx = d + j; if (idx >= 0 && idx <= `+s+`) { float z = getX(b, r, c, idx); sum += z * z; } } float val = x * `+i+`; setOutput(val); } `},jd=function(r,t,e,n,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=r,this.depth=r[3],this.depthRadius=t,this.bias=e,this.alpha=n,this.beta=o,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 - `+t+`))); int depthEnd = int(min(float(`+this.depth+`), float(d + `+t+` + 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(`+n+") * norm + float("+e+`); 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(`+n+`) * float(`+o+`) * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) / norm; if (k == d) { dyi += pow(norm, -1.0 * `+o+`); } if (k == coords[3]) { dyi *= getDy(b, r, c, d); result += dyi; } } else { break; } } } setOutput(result); } `},Vd=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var i,a=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";i=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 - `+a+`; 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 = - `+a+"; j <= "+a+`; j++) { ivec2 idx = depth + j; bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+s+`)); 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 * `+i+`; setOutput(result); } `},Gd=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideHeight,e=r.strideWidth,n=r.dilationHeight,o=r.effectiveFilterHeight,i=r.effectiveFilterWidth,a=o-1-r.padInfo.top,s=i-1-r.padInfo.left,u=o*i-1;this.userCode=` const ivec2 pads = ivec2(`+a+", "+s+`); 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 < `+o+`; wR += `+n+`) { float dyR = float(dyRCorner + wR) / `+t+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+i+`; wC++) { float dyC = float(dyCCorner + wC) / `+e+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); int maxPosValue = `+u+` - int(getMaxPos(b, idyR, idyC, d)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wR * `+i+` + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } setOutput(dotProd); } `},Xd=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.dilationDepth,i=r.dilationHeight,a=r.dilationWidth,s=r.effectiveFilterDepth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,l=s-1-r.padInfo.front,f=u-1-r.padInfo.top,h=c-1-r.padInfo.left,d=s*u*c-1;this.userCode=` const ivec3 pads = ivec3(`+l+", "+f+", "+h+`); 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 < `+s+`; wD += `+o+`) { float dyD = float(dyDCorner + wD) / `+t+`.0; if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < `+u+`; wR += `+i+`) { float dyR = float(dyRCorner + wR) / `+e+`.0; if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+c+`; wC += `+a+`) { float dyC = float(dyCCorner + wC) / `+n+`.0; if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); int maxPosValue = `+d+` - int(getMaxPos(batch, idyD, idyR, idyC, ch)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wD * `+u+" * "+c+` + wR * `+c+` + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } } setOutput(dotProd); } `},La=function(r,t,e,n,o,i,a){e===void 0&&(e=!1),n===void 0&&(n=!1),o===void 0&&(o=!1),i===void 0&&(i=null),a===void 0&&(a=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=e?r[1]:r[2],u=Math.ceil(s/2),c=e?"i * 2, rc.y":"rc.y, i * 2",l=n?"rc.z, i * 2":"i * 2, rc.z",f=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",p="";i&&(d=a?`vec4 activation(vec4 a) { vec4 b = getPreluActivationWeightsAtOutCoords(); `+i+` }`:`vec4 activation(vec4 x) { `+i+` }`,p="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+d+` const float sharedDimension = `+u+`.0; vec4 dot2x2ARowBCol(ivec3 rc) { vec4 result = vec4(0); for (int i = 0; i < `+u+`; i++) { vec4 a = getMatrixA(rc.x, `+c+`); vec4 b = getMatrixB(rc.x, `+l+`); // These swizzled products need to be separately added. // See: https://github.com/tensorflow/tfjs/issues/1735 result += (`+f[0]+" * "+h[0]+`); result += (`+f[1]+" * "+h[1]+`); } return result; } void main() { ivec3 rc = getOutputCoords(); vec4 result = dot2x2ARowBCol(rc); `+v+` `+p+` setOutput(result); } `},Jd=function(){function r(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],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 < `+(e-1)+`; i++) { cdf += getProbs(batch, i); if (r < cdf) { setOutput(float(i)); return; } } // If no other event happened, last event happened. setOutput(float(`+(e-1)+`)); } `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.seedLoc==null&&(e.seedLoc=n.getUniformLocation(o,"seed")),n.gl.uniform1f(e.seedLoc,t)}},r}(),Kd=function(r,t,e,n){this.variableNames=["indices"],this.outputShape=[r,t],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int index = round(getIndices(coords.x)); setOutput(mix(float(`+n+"), float("+e+`), float(index == coords.y))); } `},Zd=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=r;var t=r.length;if(t===0)this.userCode=` void main() { setOutput(vec4(getA(), 0., 0., 0.)); } `;else{var e=zn("rc",t),n=Yt(t),o=function(s,u,c){if(s===1)return"rc > "+u[0];for(var l="",f=s-2;f= "+u[f],f= `+u+`; bool rEdge = rp1 >= `+c+`; `}(t,r[r.length-1],r[r.length-2],e),a=function(s,u){var c=s.length,l=function(f,h){for(var d=[],p=0;p<=1;p++)for(var v=0;v<=1;v++){for(var g=(p===0?"r":"rp1")+", "+(v===0?"c":"cp1"),m=2;m= `+s[0]+` ? 0. : getA(rc + 1), 0, 0`:"getA("+l[0]+`), cEdge ? 0. : getA(`+l[1]+`), rEdge ? 0. : getA(`+l[2]+`), rEdge || cEdge ? 0. : getA(`+l[3]+")"}(r,e);this.userCode=` void main() { `+n+` rc = getOutputCoords(); if(`+o+`) { setOutput(vec4(0)); } else { `+i+` setOutput(vec4(`+a+`)); } } `}},qd=function(r,t,e){this.variableNames=["x"],this.outputShape=t.map(function(u,c){return u[0]+r[c]+u[1]});var n=r.length,o=Yt(n),i=t.map(function(u){return u[0]}).join(","),a=t.map(function(u,c){return u[0]+r[c]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=n!==1?` `+o+" start = "+o+"("+i+`); `+o+" end = "+o+"("+a+`); void main() { `+o+` outC = getOutputCoords(); if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { setOutput(float(`+e+`)); } else { `+o+` coords = outC - start; setOutput(getX(`+s+`)); } } `:` int start = `+i+`; int end = `+a+`; void main() { int outC = getOutputCoords(); if (outC < start || outC >= end) { setOutput(float(`+e+`)); } else { setOutput(getX(outC - start)); } } `},Yd=function(r,t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(function(g,m){return g[0]+r[m]+g[1]});for(var n=r.length,o=Yt(n),i=t.map(function(g){return g[0]}).join(","),a=t.map(function(g,m){return g[0]+r[m]}).join(","),s=zn("rc",n),u=zn("source",n),c=s[n-1]+" < "+this.outputShape[n-1],l=n===1?"source":"vec2("+u.slice(-2).join()+")",f=[o+" rc = outputLoc;",s[n-1]+` += 1; if(`+c+`) { `,n===1?"":`} rc = outputLoc; `+s[n-2]+` += 1; if(`+s[n-2]+" < "+this.outputShape[n-2]+") {",n===1?"":" "+s[n-1]+` += 1; if(`+c+") {"],h=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",p=0,v=n===1?2:4;p= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+c+`; wC += `+s+`) { int xC = xCCorner + wC; if (xC < 0 || xC >= `+r.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 >= currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = wR * `+c+` + wC; } } } setOutput(float(minMaxPosition)); } `;else{var p=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(p="avgValue / count");var v=4*Math.floor(n/4),g=n%4,m=` if (`+h+`) { avgValue += dot(values, ones); } else { minMaxValue = max(values, minMaxValue); } `;this.userCode=` const ivec2 strides = ivec2(`+o+", "+i+`); const ivec2 pads = ivec2(`+l+", "+f+`); const float initializationValue = `+d+`; 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 >= `+r.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(`+d+`); float avgValue = 0.0; count = 0.0; for (int wR = 0; wR < `+u+`; wR += `+a+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+v+`; wC += 4) { int xC = xCCorner + wC * `+s+`; vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), getValue(batch, xR, xC + 2 * `+s+`, d), getValue(batch, xR, xC + 3 * `+s+`, d) ); `+m+` } int xC = xCCorner + `+v+`; if (`+(g===1)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), initializationValue, initializationValue, initializationValue ); `+m+` } else if (`+(g===2)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), initializationValue, initializationValue ); `+m+` } else if (`+(g===3)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), getValue(batch, xR, xC + 2 * `+s+`, d), initializationValue ); `+m+` } } setOutput(`+p+`); } `}},_a=function(r,t,e){if(this.variableNames=["x"],t==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var n=r.filterWidth,o=r.strideDepth,i=r.strideHeight,a=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,f=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=r.padInfo.front,p=r.padInfo.top,v=r.padInfo.left;this.outputShape=r.outShape;var g=t==="avg",m="0.0";if(g||(m="-1.0 / 1e-20"),e)this.userCode=` const ivec3 strides = ivec3(`+o+", "+i+", "+a+`); const ivec3 pads = ivec3(`+d+", "+p+", "+v+`); 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 < `+l+`; wD += `+s+`) { int xD = xDCorner + wD; if (xD < 0 || xD >= `+r.inDepth+`) { continue; } for (int wR = 0; wR < `+f+`; wR += `+u+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+h+`; wC += `+c+`) { int xC = xCCorner + wC; if (xC < 0 || xC >= `+r.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 >= currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = wD * `+f+" * "+h+` + wR * `+h+` + wC;; } } } } setOutput(float(minMaxPosition)); } `;else{var w=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(w="avgValue / count");var E=4*Math.floor(n/4),b=n%4,C=` if (`+g+`) { avgValue += dot(values, ones); } else { minMaxValue = max(values, minMaxValue); } `;this.userCode=` const ivec3 strides = ivec3(`+o+", "+i+", "+a+`); const ivec3 pads = ivec3(`+d+", "+p+", "+v+`); const float initializationValue = `+m+`; 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 >= `+r.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(`+m+`); float avgValue = 0.0; count = 0.0; for (int wD = 0; wD < `+l+`; wD += `+s+`) { int xD = xDCorner + wD; if (xD < 0 || xD >= `+r.inDepth+`) { continue; } for (int wR = 0; wR < `+f+`; wR += `+u+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+r.inHeight+`) { continue; } for (int wC = 0; wC < `+E+`; wC += 4) { int xC = xCCorner + wC * `+c+`; vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+c+`, ch), getValue(batch, xD, xR, xC + 2 * `+c+`, ch), getValue(batch, xD, xR, xC + 3 * `+c+`, ch) ); `+C+` } int xC = xCCorner + `+E+`; if (`+(b===1)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); `+C+` } else if (`+(b===2)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+c+`, ch), initializationValue, initializationValue ); `+C+` } else if (`+(b===3)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+c+`, ch), getValue(batch, xD, xR, xC + 2 * `+c+`, ch), initializationValue ); `+C+` } } setOutput(`+w+`); } } `}},$d=function(r,t){this.variableNames=["x"];var e=r.windowSize,n=r.batchSize,o=r.inSize,i=Math.ceil(o/e);this.outputShape=[n,i];var a="0.0",s="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",s="min"):t==="max"&&(a="-1.0 / 1e-20",s="max");var u=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");var c=4*Math.floor(e/4),l=e%4,f=` if (`+(t==="sum")+`) { sumValue += dot(values, ones); } else if (`+(t==="prod")+`) { vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); prodValue *= tmp[0] * tmp[1]; } else { minMaxValue = `+s+`(values, minMaxValue); } `,h="vec4";t==="all"?(a="1.0",f=` bool reducedAllValue = all(values); float floatedReducedAllValue = float(reducedAllValue); allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); `,h="bvec4"):t==="any"&&(a="0.0",f=` bool reducedAnyValue = any(values); float floatedReducedAnyValue = float(reducedAnyValue); anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); `,h="bvec4");var d="";o%e>0&&(d=` if (inIdx < 0 || inIdx >= `+o+`) { return initializationValue; } `),this.userCode=` const float initializationValue = `+a+`; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { `+d+` return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * `+e+`; vec4 minMaxValue = vec4(`+a+`); float prodValue = 1.0; float sumValue = 0.0; float allValue = 1.0; float anyValue = 0.0; for (int i = 0; i < `+c+`; i += 4) { int inIdx = inOffset + i; `+h+" values = "+h+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); `+f+` } int inIdx = inOffset + `+c+`; if (`+(l===1)+`) { `+h+" values = "+h+`( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); `+f+` } else if (`+(l===2)+`) { `+h+" values = "+h+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); `+f+` } else if (`+(l===3)+`) { `+h+" values = "+h+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); `+f+` } setOutput(`+u+`); } `},ep=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var e="",n=0;n<4;n++){var o="thisRC = rc;";n%2==1&&(o+="thisRC.z += 1;"),n>1&&(o+="thisRC.y += 1;"),e+=` `+o+` `+(n>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[`+n+`] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); `+(n>0?"}":"")+` `}this.userCode=` ivec3 inputCoordsFromReshapedOutCoords(int index) { `+eo(["r","c","d"],t)+` return ivec3(r, c, d); } `+Na(r)+` void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.); ivec3 thisRC; int rows = `+r[1]+`; int cols = `+r[2]+`; `+e+` setOutput(result); } `},tp=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],i=n[2],a=r.shape,s=a[1],u=a[2],c=[e&&s>1?o-1:o,e&&u>1?i-1:i],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],f=c[0]/l[0],h=c[1]/l[1],d=1/f,p=1/h,v=2*Math.ceil(d)+2,g=2*Math.ceil(p)+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(`+f+`); const float widthScale = float(`+h+`); const float invHeightScale = float(`+d+`); const float invWidthScale = float(`+p+`); const int winHeight = int(`+v+`); const int winWidth = int(`+g+`); // 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 >= `+s+`) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= `+u+`) { continue; } float dxR = float(dyR) * heightScale; int topDxRIndex = int(floor(dxR)); int bottomDxRIndex = int(min(ceil(dxR), `+(o-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), `+(i-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); } `},np=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],i=r[1],a=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?i-1:i,n&&e>1?a-1:a],c=[n&&t>1?t-1:t,n&&e>1?e-1:e];this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/c[0]+`, `+u[1]/c[1]+`); const vec2 inputShapeRC = vec2(`+i+".0, "+a+`.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); } `},rp=function(r,t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=r[0],i=r[1],a=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?i-1:i,n&&e>1?a-1:a],c=[n&&t>1?t-1:t,n&&e>1?e-1:e];this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( `+u[0]/c[0]+`, `+u[1]/c[1]+`, `+u[1]/c[1]+`); const vec3 inputShapeRC = vec3(`+i+".0, "+a+`.0, `+a+`.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 < `+(s-1)+`; bool hasNextRow = coords.z < `+(e-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); } `},op=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],i=n[2],a=r.shape,s=a[1],u=a[2],c=[e&&s>1?o-1:o,e&&u>1?i-1:i],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],f=c[0]/l[0],h=c[1]/l[1],d=1/f,p=1/h,v=2*Math.ceil(d)+2,g=2*Math.ceil(p)+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(`+f+`); const float widthScale = float(`+h+`); const float invHeightScale = float(`+d+`); const float invWidthScale = float(`+p+`); const int winHeight = int(`+v+`); const int winWidth = int(`+g+`); // 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 >= `+s+`) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= `+u+`) { continue; } float sourceFracRow = float(`+c[0]+`) * (float(dyR) / float(`+l[0]+`)); float sourceFracCol = float(`+c[1]+`) * (float(dyC) / float(`+l[1]+`)); int sourceNearestRow = int(min( float(int(`+o+`) - 1), `+e+` ? float(round(sourceFracRow)) : float(floor(sourceFracRow)))); int sourceNearestCol = int(min( float(int(`+i+`) - 1), `+e+` ? float(round(sourceFracCol)) : float(floor(sourceFracCol)))); if (r == sourceNearestRow && c == sourceNearestCol) { accumulator += getDy(b, dyR, dyC, d); } } } // End loop over dy setOutput(accumulator); } `},ip=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],i=r[1],a=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?i-1:i,n&&e>1?a-1:a],c=[n&&t>1?t-1:t,n&&e>1?e-1:e],l=n?"0.5":"0.0";this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/c[0]+`, `+u[1]/c[1]+`); const vec2 inputShapeRC = vec2(`+i+".0, "+a+`.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 + `+l+`))); float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutput(newValue); } `},ap=function(r,t){this.variableNames=["x"];var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=r,e!==1){var n=r.map(function(i,a){return function(s){return t.indexOf(s)!==-1&&r[s]!==1?r[s]+" - coords["+s+"] - 1":"coords["+s+"]"}(a)}).join(","),o=Yt(e);this.userCode=` void main() { `+o+` coords = getOutputCoords(); setOutput(getX(`+n+`)); } `}else this.userCode=` void main() { int coord = getOutputCoords(); setOutput(getX(`+r[0]+` - coord - 1)); } `},sp=function(r,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");this.outputShape=r;var n=zn("rc",e),o=n[e-1]+" + 1 < "+this.outputShape[e-1],i=n[e-2]+" + 1 < "+this.outputShape[e-2],a=Yt(e);function s(u){var c=r.map(function(l,f){return function(h,d){return t.indexOf(h)!==-1&&r[h]!==1?r[h]+" - "+d[h]+" - 1":""+d[h]}(f,u)});return"getChannel(getX("+c.join(",")+"), vec2("+c.slice(-2).join(",")+"))"}this.userCode=e===1?` void main(){ int rc = getOutputCoords(); vec4 result = vec4(0.); result.r = getChannel(getX(`+r[0]+` - rc - 1), `+r[0]+` - rc - 1); if(`+o+`){ result.g = getChannel(getX(`+r[0]+` - (rc + 1) - 1), `+r[0]+` - (rc + 1) - 1); } setOutput(result); } `:` void main() { `+a+` rc = getOutputCoords(); vec4 result = vec4(0.); result.r = `+function(u){return s(u)}(n.slice())+`; if(`+o+`){ result.g = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",s(u)}(n.slice())+`; } if(`+i+`) { result.b = `+function(u){return u[e-2]="("+u[e-2]+" + 1)",s(u)}(n.slice())+`; if(`+o+`) { result.a = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",u[e-2]="("+u[e-2]+" + 1)",s(u)}(n.slice())+`; } } setOutput(result); } `},Wc=function(r,t,e,n,o,i,a){a===void 0&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=Yt(o.length),u=Yt(i.length),c="";e===1?c="i":e===2&&(c="i, j");var l="getIndices("+c+")",f="";n===1?f="i":n===2&&(f="i, coords[1]");var h="getUpdates("+f+")",d=t>1?"strides[j]":"strides";this.userCode=` `+s+" strides = "+s+"("+o+`); void main() { `+u+` coords = getOutputCoords(); float sum = 0.0; bool found = false; for (int i = 0; i < `+r+`; i++) { int flattenedIndex = 0; for (int j = 0; j < `+t+`; j++) { int index = round(`+l+`); flattenedIndex += index * `+d+`; } if (flattenedIndex == coords[0]) { sum += `+h+`; found = true; } } setOutput(mix(getDefaultValue(), sum, float(found))); } `},up=function(r,t){this.variableNames=["x","segmentIds"];var e=r.windowSize,n=r.batchSize,o=r.inSize,i=r.numSegments,a=i*Math.ceil(o/e);this.outputShape=[n,a];var s=4*Math.floor(e/4),u=e%4,c=` sumValue += dot(values, segFilter); `,l="";o%e>0&&(l=` if (inIdx < 0 || inIdx >= `+o+`) { return initializationValue; } `);var f="";o%e>0&&(f=` if (inIdx < 0 || inIdx >= `+o+`) { return -1.0; } `),this.userCode=` const float initializationValue = 0.0; float getValue(int batch, int inIdx) { `+l+` return getX(batch, inIdx); } float getSegmentIdAtIndex(int inIdx) { `+f+` return getSegmentIds(inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = int(floor(float(outIdx) / float( `+i+")) * float("+e+`)); int currentSeg = int(mod(float(outIdx), float(`+i+`))); float sumValue = 0.0; for (int i = 0; i < `+s+`; 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 ); `+c+` } int inIdx = inOffset + `+s+`; if (`+(u===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 ); `+c+` } else if (`+(u===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 ); `+c+` } else if (`+(u===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 ); `+c+` } setOutput(sumValue); } `},cp=function(r,t,e){var n,o;if(this.variableNames=["c","a","b"],this.outputShape=t,e>4)throw Error("Where for rank "+e+" is not yet supported");if(e===1)o="resRC",n="resRC";else{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u= 1.0) { setOutput(getA(`+o+`)); } else { setOutput(getB(`+o+`)); } } `},lp=function(){function r(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Yt(this.rank),o="uniform int start["+this.rank+"];",i=function(a){if(a===1)return"sourceLoc";if(a<=6)return Qa.slice(0,a).map(function(s){return"sourceLoc."+s}).join(",");throw Error("Slicing for rank "+a+" is not yet supported")}(this.rank);e=` `+n+` sourceLoc; `+n+` coords = getOutputCoords(); `+t.map(function(a,s){return"sourceLoc."+Qa[s]+" = start["+s+"] + coords."+Qa[s]+";"}).join(` `)+` `,this.userCode=` `+o+` void main() { `+e+` setOutput(getSource(`+i+`)); } `}return r.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r}(),Qa=["x","y","z","w","u","v"],fp=function(){function r(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Yt(this.rank),n=zn("coords",this.rank),o=zn("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":"vec2("+o.slice(-2).join()+")",a="getChannel(getSource("+o.join()+"), "+i+")",s=` result.x = `+a+`; if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) { ++`+o[this.rank-1]+`; result.y = `+a+`; --`+o[this.rank-1]+`; } `,u=this.rank===1?"":` --`+n[this.rank-1]+`; if (++`+n[this.rank-2]+" < "+t[this.rank-2]+`) { ++`+o[this.rank-2]+`; result.z = `+a+`; if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) { ++`+o[this.rank-1]+`; result.w = `+a+`; } } `,c=this.rank<=4?`sourceLoc = coords + `+e+"("+t.map(function(l,f){return"start["+f+"]"}).join()+");":t.map(function(l,f){return o[f]+" = "+n[f]+" + start["+f+"];"}).join(` `);this.userCode=` uniform int start[`+this.rank+`]; void main() { `+e+` coords = getOutputCoords(); `+e+` sourceLoc; `+c+` vec4 result = vec4(0.); `+s+` `+u+` setOutput(result); } `}return r.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r}(),hp=function(r,t,e){this.variableNames=["x"],this.outputShape=e;var n=e.length,o=Yt(e.length),i=Yt(e.length),a="";if(n===1)a="coords * strides + begin";else{var s=0;a=e.map(function(u,c){return s++,e.length===1?"coords * strides["+c+"] + begin["+c+"]":"coords["+(s-1)+"] * strides["+c+"] + begin["+c+"]"}).join(",")}this.userCode=` `+o+" begin = "+o+"("+r+`); `+o+" strides = "+o+"("+t+`); void main() { `+i+` coords = getOutputCoords(); setOutput(getX(`+a+`)); } `},dp=function(){function r(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return r.prototype.acquireTexture=function(t,e,n){var o,i=_c(e,n),a=Qc(t,i,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var s=this.freeTextures[a].shift();return this.usedTextures[a].push(s),s}return this.numUsedTextures++,this.log(),i===Rn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Rn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Rn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Rn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Rn.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(o),o},r.prototype.releaseTexture=function(t,e,n,o){if(this.freeTextures!=null){var i=Qc(e,_c(n,o),o);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[i],s=a.indexOf(t);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(s,1),this.log()}},r.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},r.prototype.getNumUsedTextures=function(){return this.numUsedTextures},r.prototype.getNumFreeTextures=function(){return this.numFreeTextures},r.prototype.dispose=function(){var t=this;if(this.freeTextures!=null){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(n){t.gpgpu.deleteMatrixTexture(n)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(o){t.gpgpu.deleteMatrixTexture(o)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},r}();function _c(r,t){if(r===wn.UPLOAD)return Rn.PACKED_2X2_FLOAT32;if(r===wn.RENDER||r==null)return function(e){return J().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Rn.PACKED_2X2_FLOAT32:Rn.UNPACKED_FLOAT32:e?Rn.PACKED_2X2_FLOAT16:Rn.UNPACKED_FLOAT16}(t);if(r===wn.DOWNLOAD||r===wn.PIXELS)return Rn.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+r)}function Qc(r,t,e){return r[0]+"_"+r[1]+"_"+t+"_"+e}var pp=function(r,t){this.variableNames=["A"];for(var e=new Array(r.length),n=0;n5)throw Error("Tile for rank "+s+" is not yet supported");if(s===1)return"imod(resRC, "+a[0]+")";for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],c=[],l=0;l6)throw Error("Transpose for rank "+s+" is not yet supported");for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],c=new Array(s),l=0;l6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=Yt(this.rank),i=uc("rc",this.rank),a=new Array(this.rank);for(n=0;n= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,Vc="return -x;",Gc="return ceil(x);",Xc="return floor(x);",Jc="return exp(x);",Kc="return exp(x) - 1.0;",yp=or+` return sin(x); `,xp=or+` return cos(x); `,bp=or+` if (abs(x) > 1.) { return NAN; } return asin(x); `,wp=or+` if (abs(x) > 1.) { return NAN; } return acos(x); `,Ep=or+` return atan(x); `,Cp=or+"return log(x + sqrt(x * x + 1.0));",Ip=or+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,Sp=or+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Pi="return x;",Rp="return x;",Zc=` 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; `,qc=` 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; `,Yc=` 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; `,Ko=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.userCode=` vec4 unaryOperation(vec4 x) { `+t+` } void main() { vec4 x = getAAtOutCoords(); vec4 y = unaryOperation(x); setOutput(y); } `},Bp=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=r;var t=r.length,e=zn("rc",t),n=Yt(t),o=function(s,u){if(s===1)return"rc";for(var c="",l=0;l0?[4,Promise.all(a)]:[3,2];case 1:return c=l.sent(),u.kernelMs=Ge(c),u.getExtraProfileInfo=function(){return c.map(function(f,h){return{name:s[h],ms:f}}).map(function(f){return f.name+": "+f.ms}).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},l.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:ee(),endMs:null}},t.prototype.endTimer=function(e){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=ee(),e)},t.prototype.getQueryTime=function(e){return be(this,void 0,void 0,function(){var n;return Se(this,function(o){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]})})},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var n=this.texData.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var n=this.texData.get(e),o=n.texture,i=n.dtype,a=n.texShape,s=n.usage,u=n.isPacked,c=n.slice,l=c&&c.origDataId||e,f=this.dataRefCount.get(l);f>1?this.dataRefCount.set(l,f-1):(this.dataRefCount.delete(l),o!=null&&(this.numBytesInGPU-=this.computeBytes(a,i),this.textureManager.releaseTexture(o,a,s,u)));var h=this.texData.get(e);h.texture=null,h.texShape=null,h.isPacked=!1,h.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return J().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=W.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,n){var o=this;return n===void 0&&(n=128),this.getCPUBackend()!=null&&e.every(function(i){return o.texData.get(i.dataId).texture==null&&i.sizeJ().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(e.length/2),s=this.concat(e.slice(0,a),n),u=this.concat(e.slice(a),n);return this.concat([s,u],n)}if(J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var c=new Ad(e.map(function(d){return d.shape}),n);return this.compileAndRun(c,e)}var l=Kr(e.map(function(d){return d.shape}),n),f=e.map(function(d){return d.as2D(-1,Re(d.shape.slice(n)))}),h=new md(f.map(function(d){return d.shape}));return this.compileAndRun(h,f).reshape(l)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Vc,e.dtype);var n=new ht(e.shape,Vc);return this.compileAndRun(n,[e])},t.prototype.batchMatMul=function(e,n,o,i){var a=o?e.shape[2]:e.shape[1],s=i?n.shape[1]:n.shape[2],u=o?e.shape[1]:e.shape[2],c=e.shape[0];if((a===1||s===1)&&u>1e3){o&&(e=e.transpose([0,2,1])),i&&(n=n.transpose([0,2,1]));var l=s===1?e:e.as3D(c,u,1),f=s===1?2:1,h=s===1?n.as3D(c,1,u):n;return this.multiply(l,h).sum(f,!0)}var d=Lt(e.dtype,n.dtype),p=new La(e.shape,[c,a,s],o,i);return this.compileAndRun(p,[e,n],d)},t.prototype.fusedBatchMatMul=function(e){var n=e.a,o=e.b,i=e.transposeA,a=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=i?n.shape[2]:n.shape[1],f=a?o.shape[1]:o.shape[2],h=n.shape[0],d=Lt(n.dtype,o.dtype),p=s!=null,v=c!=null,g=u?Oi(u,!0):null,m=new La(n.shape,[h,l,f],i,a,p,g,v),w=[n,o];return s&&w.push(s),c&&w.push(c),this.compileAndRun(m,w,d)},t.prototype.multiply=function(e,n){if(e.dtype==="complex64"){var o=this.texData.get(e.dataId),i=this.texData.get(n.dataId),a=new fc(hd,e.shape,n.shape),s=new fc(dd,e.shape,n.shape),u=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag),this.makeComplexComponentTensorInfo(n,i.complexTensors.real),this.makeComplexComponentTensorInfo(n,i.complexTensors.imag)],c=this.compileAndRun(a,u),l=this.compileAndRun(s,u),f=this.complex(c,l);return c.dispose(),l.dispose(),f}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,hc,e.dtype);var h=new sn(hc,e.shape,n.shape);return this.compileAndRun(h,[e,n],e.dtype)},t.prototype.batchNormalization=function(e,n,o,i,a,s){var u=[e,n,o],c=null;s!=null&&(c=s.shape,u.push(s));var l=null;if(a!=null&&(l=a.shape,u.push(a)),J().getBool("WEBGL_PACK_NORMALIZATION")){var f=new fd(e.shape,n.shape,o.shape,c,l,i);return this.compileAndRun(f,u)}var h=new ld(e.shape,n.shape,o.shape,c,l,i);return this.compileAndRun(h,u)},t.prototype.localResponseNormalization4D=function(e,n,o,i,a){var s=J().getBool("WEBGL_PACK_NORMALIZATION")?new Vd(e.shape,n,o,i,a):new Hd(e.shape,n,o,i,a);return this.compileAndRun(s,[e])},t.prototype.LRNGrad=function(e,n,o,i,a,s,u){var c=new jd(n.shape,i,a,s,u);return this.compileAndRun(c,[n,o,e])},t.prototype.tile=function(e,n){if(e.dtype==="string"){var o=this.readSync(e.dataId).map(function(a){return Oe(a)});return ac(ot(e.shape,e.dtype,o),n)}var i=new pp(e.shape,n);return this.compileAndRun(i,[e])},t.prototype.pad=function(e,n,o){var i=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Yd(e.shape,n,o):new qd(e.shape,n,o);return this.compileAndRun(i,[e])},t.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var o=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new gp(e.shape,n):new vp(e.shape,n);return this.compileAndRun(o,[e])},t.prototype.gather=function(e,n,o){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.gather(e,n,o);var i=new _d(e.shape,n.size,o);return this.compileAndRun(i,[e,n])},t.prototype.batchToSpaceND=function(e,n,o){B(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var i=n.reduce(function(f,h){return f*h}),a=wi(e.shape,n,i),s=Ei(a.length,n.length),u=Ci(e.shape,n,i),c=Xu(o,n.length),l=Ju(u,o,n.length);return e.reshape(a).transpose(s).reshape(u).slice(c,l)},t.prototype.spaceToBatchND=function(e,n,o){B(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var i=n.reduce(function(h,d){return h*d}),a=[[0,0]];a.push.apply(a,o);for(var s=1+n.length;sd||p===h?v=!0:p=Ft(h,p+1);return p}(u,a),l=new up({windowSize:c,inSize:u,batchSize:s,numSegments:a},n),f=this.compileAndRun(l,[e,o],i);return f.shape[1]===a?f:(o=xi(0,a).tile([u/c]),this.segOpCompute(f,n,o,i,a))},t.prototype.argMinMaxReduce=function(e,n,o){var i=[n];if(_n("arg"+o.charAt(0).toUpperCase()+o.slice(1),i,e.rank),!J().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var a=Bn(e.shape,i),s=a[0],u=Re(a[1]),c=e.as2D(-1,u);return this.argReduce(c,o).reshape(s)}return this.argReducePacked(e,o)},t.prototype.argMin=function(e,n){return this.argMinMaxReduce(e,n,"min")},t.prototype.argMax=function(e,n){return this.argMinMaxReduce(e,n,"max")},t.prototype.cumsum=function(e,n,o,i){if(n!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+n);var a=new Rd(e.shape,o,i);return this.compileAndRun(a,[e])},t.prototype.equal=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(equal(a, b)); `,"bool");var o=new sn("return float(a == b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.notEqual=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(notEqual(a, b)); `,"bool");var o=new sn("return float(a != b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(lessThan(a, b)); `,"bool");var o=new sn("return float(a < b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.lessEqual=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(lessThanEqual(a, b)); `,"bool");var o=new sn("return float(a <= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(greaterThan(a, b)); `,"bool");var o=new sn("return float(a > b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greaterEqual=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4(greaterThanEqual(a, b)); `,"bool");var o=new sn("return float(a >= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalNot=function(e){var n=new ht(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(n,[e])},t.prototype.logicalAnd=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,"bool");var o=new sn("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalOr=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,"bool");var o=new sn("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.select=function(e,n,o){var i=new cp(e.rank,n.shape,n.rank);return this.compileAndRun(i,[e,n,o],Lt(n.dtype,o.dtype))},t.prototype.where=function(e){Ai("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var n=e.dataSync();return Pa(e.shape,n)},t.prototype.topk=function(e,n,o){return sc(e.dataSync(),e.shape,e.dtype,n)},t.prototype.min=function(e,n){_n("min",n,e.rank);var o=Bn(e.shape,n),i=o[0],a=Re(o[1]),s=e.as2D(-1,a);return this.reduce(s,"min",s.dtype).reshape(i)},t.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` vec4 result = vec4(min(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,n.shape):new sn(` if (isnan(a)) return a; if (isnan(b)) return b; return min(a, b); `,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.mod=function(e,n){var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); 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; return result; `,e.shape,n.shape):new sn(`if (b == 0.0) return NAN; return mod(a, b);`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.max=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,n);_n("max",n,e.rank);var o=Bn(e.shape,n),i=o[0],a=Re(o[1]),s=e.as2D(-1,a);return this.reduce(s,"max",s.dtype).reshape(i)},t.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` vec4 result = vec4(max(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,n.shape):new sn(` if (isnan(a)) return a; if (isnan(b)) return b; return max(a, b); `,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.all=function(e,n){_n("all",n,e.rank);var o=Bn(e.shape,n),i=o[0],a=Re(o[1]),s=e.as2D(-1,a);return this.reduce(s,"all",s.dtype).reshape(i)},t.prototype.any=function(e,n){_n("any",n,e.rank);var o=Bn(e.shape,n),i=o[0],a=Re(o[1]),s=e.as2D(-1,a);return this.reduce(s,"any",s.dtype).reshape(i)},t.prototype.realDivide=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` // 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; `,"float32",!0);var o=new sn(` if (a == b) { return 1.0; }; return a / b;`,e.shape,n.shape);return this.compileAndRun(o,[e,n],"float32")},t.prototype.floorDiv=function(e,n){if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` 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); `,"int32");var o=new sn(` 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; } `,e.shape,n.shape);return this.compileAndRun(o,[e,n],"int32")},t.prototype.add=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,Oa);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var o=Lt(e.dtype,n.dtype);if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Oa,o);var i=new sn(Oa,e.shape,n.shape);return this.compileAndRun(i,[e,n],o)},t.prototype.packedUnaryOp=function(e,n,o){var i=new Ko(e.shape,n);return this.compileAndRun(i,[e],o)},t.prototype.packedBinaryOp=function(e,n,o,i,a){a===void 0&&(a=!1);var s=new Sr(o,e.shape,n.shape,a);return this.compileAndRun(s,[e,n],i)},t.prototype.complexSeparableBinaryOp=function(e,n,o){var i=this,a=this.texData.get(e.dataId),s=this.texData.get(n.dataId),u=[[a.complexTensors.real,s.complexTensors.real],[a.complexTensors.imag,s.complexTensors.imag]].map(function(h){var d=h[0],p=h[1],v=i.makeComplexComponentTensorInfo(e,d),g=i.makeComplexComponentTensorInfo(n,p),m=new sn(o,e.shape,n.shape);return i.compileAndRun(m,[v,g],Lt(d.dtype,p.dtype))}),c=u[0],l=u[1],f=this.complex(c,l);return c.dispose(),l.dispose(),f},t.prototype.makeComplexComponentTensorInfo=function(e,n){return{dataId:n.dataId,dtype:n.dtype,shape:e.shape}},t.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>J().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),o=this.addN(e.slice(0,n)),i=this.addN(e.slice(n));return this.addN([o,i])}var a=e.map(function(c){return c.dtype}).reduce(function(c,l){return Lt(c,l)}),s=e.map(function(c){return c.shape}),u=J().getBool("WEBGL_PACK")?new ed(e[0].shape,s):new $h(e[0].shape,s);return this.compileAndRun(u,e,a)},t.prototype.subtract=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,Ma);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var o=Lt(e.dtype,n.dtype);if(J().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Ma,e.dtype);var i=new sn(Ma,e.shape,n.shape);return this.compileAndRun(i,[e,n],o)},t.prototype.pow=function(e,n){var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` // 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)); 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; return result; `,e.shape,n.shape):new sn(` 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); `,e.shape,n.shape),i=Lt(e.dtype,n.dtype);return this.compileAndRun(o,[e,n],i)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Gc,e.dtype);var n=new ht(e.shape,Gc);return this.compileAndRun(n,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Xc,e.dtype);var n=new ht(e.shape,Xc);return this.compileAndRun(n,[e])},t.prototype.sign=function(e){var n=new ht(e.shape,` if (isnan(x)) { return 0.0; } return sign(x); `);return this.compileAndRun(n,[e])},t.prototype.isNaN=function(e){var n=new ht(e.shape,"return float(isnan(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isInf=function(e){var n=new ht(e.shape,"return float(isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isFinite=function(e){var n=new ht(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.round=function(e){var n=new ht(e.shape,` // 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; } } `);return this.compileAndRun(n,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Jc,e.dtype);var n=new ht(e.shape,Jc);return this.compileAndRun(n,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Kc,e.dtype);var n=new ht(e.shape,Kc);return this.compileAndRun(n,[e])},t.prototype.softmax=function(e,n){var o=Dt([n],e.shape),i=this.max(e,o),a=Mn(i.shape,o),s=this.subtract(e,i.reshape(a)),u=this.exp(s),c=this.sum(u,o).reshape(a);return this.realDivide(u,c)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,` 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; `,e.dtype);var n=new ht(e.shape,`if (x < 0.0) return NAN; return log(x);`);return this.compileAndRun(n,[e])},t.prototype.log1p=function(e){var n=new ht(e.shape,"return log(1.0 + x);");return this.compileAndRun(n,[e])},t.prototype.sqrt=function(e){var n=new ht(e.shape,"return sqrt(x);");return this.compileAndRun(n,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var n=new ht(e.shape,"return inversesqrt(x);");return this.compileAndRun(n,[e])},t.prototype.reciprocal=function(e){var n=new ht(e.shape,"return 1.0 / x;");return this.compileAndRun(n,[e])},t.prototype.relu=function(e){var n;return n=J().getBool("WEBGL_PACK")?new Ko(e.shape,Zc):new ht(e.shape,Uc),this.compileAndRun(n,[e])},t.prototype.relu6=function(e){var n;return n=J().getBool("WEBGL_PACK")?new Ko(e.shape,qc):new ht(e.shape,Hc),this.compileAndRun(n,[e])},t.prototype.prelu=function(e,n){var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(pc,e.shape,n.shape):new sn(dc,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.elu=function(e){if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Yc,e.dtype);var n=new ht(e.shape,jc);return this.compileAndRun(n,[e])},t.prototype.eluDer=function(e,n){var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,e.shape,n.shape):new sn("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.selu=function(e){var n=new ht(e.shape,Ap);return this.compileAndRun(n,[e])},t.prototype.int=function(e){var n=new ht(e.shape,"return float(int(x));");return this.compileAndRun(n,[e],"int32")},t.prototype.clip=function(e,n,o){var i,a=(i=J().getBool("WEBGL_PACK_CLIP")?new vd(e.shape):new pd(e.shape)).getCustomSetupFunc(n,o);return this.compileAndRun(i,[e],null,a)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,zc,e.dtype);var n=new ht(e.shape,zc);return this.compileAndRun(n,[e])},t.prototype.complexAbs=function(e){var n=this.texData.get(e.dataId),o=new gd(e.shape),i=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)];return this.compileAndRun(o,i)},t.prototype.sigmoid=function(e){var n=new ht(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(n,[e])},t.prototype.softplus=function(e){var n=new ht(e.shape,` 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; `);return this.compileAndRun(n,[e])},t.prototype.sin=function(e){var n=new ht(e.shape,yp);return this.compileAndRun(n,[e])},t.prototype.cos=function(e){var n=new ht(e.shape,xp);return this.compileAndRun(n,[e])},t.prototype.tan=function(e){var n=new ht(e.shape,"return tan(x);");return this.compileAndRun(n,[e])},t.prototype.asin=function(e){var n=new ht(e.shape,bp);return this.compileAndRun(n,[e])},t.prototype.acos=function(e){var n=new ht(e.shape,wp);return this.compileAndRun(n,[e])},t.prototype.atan=function(e){var n=new ht(e.shape,Ep);return this.compileAndRun(n,[e])},t.prototype.atan2=function(e,n){var o=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Sr(` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,n.shape):new sn(` if (isnan(a)) return a; if (isnan(b)) return b; return atan(a, b); `,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.sinh=function(e){var n=new ht(e.shape,` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `);return this.compileAndRun(n,[e])},t.prototype.cosh=function(e){var n=new ht(e.shape,` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `);return this.compileAndRun(n,[e])},t.prototype.tanh=function(e){var n=new ht(e.shape,` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `);return this.compileAndRun(n,[e])},t.prototype.asinh=function(e){var n=new ht(e.shape,Cp);return this.compileAndRun(n,[e])},t.prototype.acosh=function(e){var n=new ht(e.shape,Ip);return this.compileAndRun(n,[e])},t.prototype.atanh=function(e){var n=new ht(e.shape,Sp);return this.compileAndRun(n,[e])},t.prototype.erf=function(e){var n=new ht(e.shape,` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = 0.3275911; float a1 = 0.254829592; float a2 = -0.284496736; float a3 = 1.421413741; float a4 = -1.453152027; float a5 = 1.061405429; 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)); `);return this.compileAndRun(n,[e])},t.prototype.step=function(e,n){var o=new ht(e.shape,function(i){return i===void 0&&(i=0),or+` return x > 0.0 ? 1.0 : float(`+i+`); `}(n));return this.compileAndRun(o,[e])},t.prototype.conv2dByMatMul=function(e,n,o,i,a,s){var u=e.shape,c=this.texData.get(e.dataId),l=o.inChannels,f=u[0]*u[1]*u[2],h=o.outChannels,d=o.dataFormat==="channelsLast",p=(f===1||h===1)&&l>1e3,v=u[2]%2!=0&&!!c.isPacked;if(p||!J().getBool("WEBGL_LAZILY_UNPACK")||!J().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){var g=d?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],m=this.reshape(e,[1,g,o.inChannels]),w=this.reshape(n,[1,o.inChannels,o.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:w,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:s}),o.outShape)}var E=d?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),b={dataId:e.dataId,shape:[1,E,o.inChannels],dtype:e.dtype},C=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,B(Uo(c.shape,b.shape),function(){return"packed reshape "+c.shape+" to "+b.shape+" isn't free"});var S=this.reshape(n,[1,o.inChannels,o.outChannels]),N=this.fusedBatchMatMul({a:b,b:S,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:s}),O=this.texData.get(N.dataId);return B(O.isPacked,function(){return"batchMatMul result is expected to be packed"}),c.shape=C,O.shape=o.outShape,W.makeTensorFromDataId(N.dataId,o.outShape,N.dtype)},t.prototype.conv2dWithIm2Row=function(e,n,o,i,a,s){var u=o.filterWidth,c=o.filterHeight,l=o.inChannels,f=o.outWidth,h=o.outHeight,d=o.dataFormat==="channelsLast",p=u*c*l,v=h*f,g=[p,v],m=e.squeeze([0]),w=n.reshape([1,p,-1]),E=new Ud(g,m.shape,o),b=this.compileAndRun(E,[m]).reshape([1,g[0],g[1]]),C=i!=null,S=s!=null,N=a?Oi(a,!0):null,O=new La(b.shape,[1,v,o.outChannels],!0,!1,C,N,S),F=[b,w];i&&F.push(i),S&&F.push(s);var P=this.compileAndRun(O,F);return d?P.reshape([1,h,f,o.outChannels]):P.reshape([1,o.outChannels,h,f])},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,i=e.convInfo,a=e.bias,s=e.activation,u=e.preluActivationWeights;if(i.filterHeight===1&&i.filterWidth===1&&i.dilationHeight===1&&i.dilationWidth===1&&i.strideHeight===1&&i.strideWidth===1&&(i.padInfo.type==="SAME"||i.padInfo.type==="VALID"))return this.conv2dByMatMul(n,o,i,a,s,u);if(J().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)return this.conv2dWithIm2Row(n,o,i,a,s,u);var c=a!=null,l=u!=null,f=s?Oi(s,!1):null,h=new vc(i,c,f,l),d=[n,o];return a&&d.push(a),u&&d.push(u),this.compileAndRun(h,d)},t.prototype.conv2d=function(e,n,o){if(o.filterHeight===1&&o.filterWidth===1&&o.dilationHeight===1&&o.dilationWidth===1&&o.strideHeight===1&&o.strideWidth===1&&(o.padInfo.type==="SAME"||o.padInfo.type==="VALID"))return this.conv2dByMatMul(e,n,o);if(J().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,n,o);var i=new vc(o);return this.compileAndRun(i,[e,n])},t.prototype.conv2dDerInput=function(e,n,o){var i=new xd(o);return this.compileAndRun(i,[e,n])},t.prototype.conv2dDerFilter=function(e,n,o){var i=new yd(o);return this.compileAndRun(i,[e,n])},t.prototype.fusedDepthwiseConv2D=function(e){var n,o=e.input,i=e.filter,a=e.convInfo,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=J().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels==1,f=u?Oi(u,l):null,h=[o,i],d=s!=null,p=c!=null;return d&&h.push(s),p&&h.push(c),l?(n=new mc(a,d,f,p),this.compileAndRun(n,h)):(n=new gc(a,d,f,p),this.compileAndRun(n,h))},t.prototype.depthwiseConv2D=function(e,n,o){var i;return J().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1?(i=new mc(o),this.compileAndRun(i,[e,n])):(i=new gc(o),this.compileAndRun(i,[e,n]))},t.prototype.depthwiseConv2DDerInput=function(e,n,o){var i=new Cd(o);return this.compileAndRun(i,[e,n])},t.prototype.depthwiseConv2DDerFilter=function(e,n,o){var i=new Ed(o);return this.compileAndRun(i,[e,n])},t.prototype.conv3d=function(e,n,o){var i=new Id(o);return this.compileAndRun(i,[e,n])},t.prototype.conv3dDerInput=function(e,n,o){var i=new wd(o);return this.compileAndRun(i,[e,n])},t.prototype.conv3dDerFilter=function(e,n,o){var i=new bd(o);return this.compileAndRun(i,[e,n])},t.prototype.maxPool=function(e,n){var o=new Wa(n,"max",!1);return this.compileAndRun(o,[e])},t.prototype.avgPool=function(e,n){var o=new Wa(n,"avg",!1);return this.compileAndRun(o,[e],"float32")},t.prototype.maxPoolBackprop=function(e,n,o,i){var a=new Wa(i,"max",!0),s=this.compileAndRun(a,[n]),u=new Gd(i),c=this.compileAndRun(u,[e,s],n.dtype);return s.dispose(),c},t.prototype.avgPoolBackprop=function(e,n,o){var i=new ud(o);return this.compileAndRun(i,[e],n.dtype)},t.prototype.cast=function(e,n){return Ba(e,n,this)},t.prototype.unstack=function(e,n){for(var o=e.shape[n],i=new Array(e.rank-1),a=0,s=0;s1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+n});var i=e.shape[0],a=o==="NHWC"?e.shape[1]:e.shape[2],s=o==="NHWC"?e.shape[2]:e.shape[3],u=o==="NHWC"?e.shape[3]:e.shape[1],c=a*n,l=s*n,f=u/(n*n),h=new Td(o==="NHWC"?[i,c,l,f]:[i,f,c,l],n,o);return this.compileAndRun(h,[e])},t.prototype.split=function(e,n,o){return ic(e,n,o)},t.prototype.scatterND=function(e,n,o){var i=jo(0,e,o),a=i.sliceRank,s=i.numUpdates,u=i.sliceSize,c=i.strides,l=i.outputSize,f=[l/u,u],h=e.reshape([s,a]),d=n.reshape([s,u]);if(l===0)return Di(Tn([]),o);var p=Fe(0),v=new Wc(s,a,h.rank,d.rank,c,f);return this.compileAndRun(v,[d,h,p]).reshape(o)},t.prototype.sparseToDense=function(e,n,o,i){var a=jo(0,e,o),s=a.sliceRank,u=a.numUpdates,c=a.strides,l=a.outputSize,f=new Wc(u,s,e.rank,n.rank,c,[l,1],!1);return this.compileAndRun(f,[n,e,i]).reshape(o)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,n){var o=this.texData.get(e.dataId),i=new yc(Md,e.shape,n),a=new yc(Ld,e.shape,n),s=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag)],u=this.compileAndRun(i,s),c=this.compileAndRun(a,s),l=this.complex(u,c).as2D(e.shape[0],e.shape[1]);return u.dispose(),c.dispose(),l},t.prototype.gatherND=function(e,n){var o=n.shape,i=o[o.length-1],a=ba(e,n),s=a[0],u=a[1],c=a[2],l=a[3],f=n.reshape([u,i]),h=e.reshape([e.size/c,c]),d=new Qd(i,l,[u,c]);return this.compileAndRun(d,[h,f]).reshape(s)},t.prototype.fill=function(e,n,o){if((o=o||ze(n))==="string"){var i=y(o,Re(e));return i.fill(n),W.makeTensor(i,e,o,this)}var a=new Wd(e,n),s=a.getCustomSetupFunc(n);return this.compileAndRun(a,[],o,s)},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},t.prototype.linspace=function(e,n,o){return ka(e,n,o)},t.prototype.makeTensorInfo=function(e,n){var o=this.write(null,e,n);return this.texData.get(o).usage=null,{dataId:o,shape:e,dtype:n}},t.prototype.makeOutput=function(e,n){var o=this.makeTensorInfo(e,n).dataId;return W.makeTensorFromDataId(o,e,n,this)},t.prototype.unpackTensor=function(e){var n=new Bp(e.shape);return this.runWebGLProgram(n,[e],e.dtype)},t.prototype.packTensor=function(e){var n=new Zd(e.shape);return this.runWebGLProgram(n,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,n){var o=[Qo(e.shape)].concat(zo(e.shape)),i={dtype:e.dtype,shape:o,dataId:e.dataId},a=[Qo(n)].concat(zo(n)),s=new ep(a,o),u=this.runWebGLProgram(s,[i],e.dtype,null,!0);return{dataId:u.dataId,shape:n,dtype:u.dtype}},t.prototype.decode=function(e){var n,o=this.texData.get(e),i=o.isPacked,a=o.shape,s=o.dtype,u=gi(a);return n=i?new kd(u):new Bd(u),{dtype:s,shape:a,dataId:this.runWebGLProgram(n,[{shape:u,dtype:s,dataId:e}],s,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,n,o,i,a){var s=this;a===void 0&&(a=!1);var u=this.makeTensorInfo(e.outputShape,o),c=this.texData.get(u.dataId);if(e.packedOutput&&(c.isPacked=!0),e.outPackingScheme===er.DENSE){var l=Mo(e.outputShape);c.texShape=l.map(function(E){return 2*E})}if(e.outTexUsage!=null&&(c.usage=e.outTexUsage),Re(u.shape)===0)return c.values=T(u.dtype,0),u;var f=[],h=n.map(function(E){if(E.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var b=s.texData.get(E.dataId);if(b.texture==null){if(!e.packedInputs&&Re(E.shape)<=J().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:E.shape,texData:null,isUniform:!0,uniformValues:b.values};e.packedInputs&&(b.isPacked=!0,b.shape=E.shape)}else if(!!b.isPacked!=!!e.packedInputs)E=b.isPacked?s.unpackTensor(E):s.packTensor(E),f.push(E),b=s.texData.get(E.dataId);else if(b.isPacked&&!Uo(b.shape,E.shape)){var C=E,S=E.shape;E.shape=b.shape,E=s.packedReshape(E,S),f.push(E),b=s.texData.get(E.dataId),C.shape=S}return s.uploadToGPU(E.dataId),{shape:E.shape,texData:b,isUniform:!1}});this.uploadToGPU(u.dataId);var d,p={shape:u.shape,texData:c,isUniform:!1},v=function(E,b,C){var S="";b.concat(C).forEach(function(F){var P=F.texData!=null&&F.texData.slice!=null&&F.texData.slice.flatOffset>0,U=F.isUniform?"uniform":F.texData.texShape;S+=F.shape+"_"+U+"_"+P});var N=E.userCode,O=E.constructor.name;return O+="_"+S+"_"+N}(e,h,p),g=this.getAndSaveBinary(v,function(){return function(E,b,C,S){var N=b.userCode,O=C.map(function(oe,he){var pe={logicalShape:oe.shape,texShape:oe.isUniform?null:oe.texData.texShape,isUniform:oe.isUniform,isPacked:!oe.isUniform&&oe.texData.isPacked,flatOffset:null};return oe.texData!=null&&oe.texData.slice!=null&&oe.texData.slice.flatOffset>0&&(pe.flatOffset=oe.texData.slice.flatOffset),{name:b.variableNames[he],shapeInfo:pe}}),F=O.map(function(oe){return oe.shapeInfo}),P={logicalShape:S.shape,texShape:S.texData.texShape,isUniform:!1,isPacked:S.texData.isPacked,flatOffset:null},U=nd(O,P,N,b.packedInputs),Q=E.createProgram(U),V=null,X=E.getUniformLocation(Q,"NAN",!1);J().getNumber("WEBGL_VERSION")===1&&(V=E.getUniformLocation(Q,"INFINITY",!1));for(var te={},ue=0;ue0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var n,o=this.texData.get(e),i=o.shape,a=o.dtype,s=o.values,u=o.texture,c=o.usage,l=o.isPacked;if(u==null){var f,h=this.activeTimers!=null;h&&(f=ee());var d=o.texShape;if(d==null&&(d=Tu(i,l),o.texShape=d),s!=null){var p=gi(i),v=void 0,g=d[1],m=d[0],w=s instanceof Uint8Array;l?(g=(n=Lo(d[0],d[1]))[0],m=n[1],v=new Od(p,[m,g],w)):v=new Nd(p,[m,g],w);var E=this.makeTensorInfo([m,g],a);this.texData.get(E.dataId).usage=w?wn.PIXELS:wn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(E.dataId),g,m,s);var b=this.runWebGLProgram(v,[E],a,null,!0),C=this.texData.get(b.dataId);o.texture=C.texture,o.texShape=C.texShape,o.isPacked=C.isPacked,o.usage=C.usage,this.disposeData(E.dataId),this.texData.delete(b.dataId),o.values=null,h&&(this.uploadWaitMs+=ee()-f)}else{var S=this.acquireTexture(d,c,a,l);o.texture=S}}},t.prototype.convertAndCacheOnCPU=function(e,n){var o=this.texData.get(e),i=o.dtype;return this.releaseGPUData(e),n!=null&&(o.values=function(a,s){if(s==="float32"||s==="complex64")return a;if(s==="int32"||s==="bool"){for(var u=s==="int32"?new Int32Array(a.length):new Uint8Array(a.length),c=0;c1024*this.numMBBeforeWarning*1024){var a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+a+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,n,i)},t.prototype.computeBytes=function(e,n){return e[0]*e[1]*L(n)},t}(tc);wr()&&W.registerBackend("webgl",function(){return new $c},2);var Tp=_({square_:function(r){var t=k(r,"x","square"),e=[t];return W.runKernelFunc(function(n,o){return o([t]),n.square(t)},{x:t},null,"Square",{},e,[])}}),Zo="SquaredDifference",el=_({squaredDifference_:function(r,t){var e,n=k(r,"a","squaredDifference"),o=k(t,"b","squaredDifference");e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape);var i={a:n,b:o},a=[n,o];return W.runKernelFunc(function(s,u){var c=s.squaredDifference(n,o);return u([n,o]),c},i,function(s,u){var c=u[0],l=u[1],f=Fe(2);return{a:function(){return s.mul(c.sub(l).mul(f))},b:function(){return s.mul(l.sub(c).mul(f))}}},Zo,{},a,[])}}),Dp=_({abs_:function(r){var t=k(r,"x","abs");return t.dtype==="complex64"?W.runKernelFunc(function(e){return e.complexAbs(t)},{$x:t}):W.runKernelFunc(function(e,n){var o=e.abs(t);return n([t]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return e.mul(o.toFloat().step(-1))}}},"Abs")}}),Fp=_({acos_:function(r){var t=k(r,"x","acos");return W.runKernelFunc(function(e,n){var o=e.acos(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(Fe(1).sub(o.toFloat().square()).sqrt()).neg()}}})}}),Pp=_({acosh_:function(r){var t=k(r,"x","acosh");return W.runKernelFunc(function(e,n){var o=e.acosh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(o.toFloat().square().sub(1).sqrt())}}})}}),Np=_({asin_:function(r){var t=k(r,"x","asin");return W.runKernelFunc(function(e,n){var o=e.asin(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(Fe(1).sub(o.toFloat().square()).sqrt())}}})}}),Op=_({asinh_:function(r){var t=k(r,"x","asinh");return W.runKernelFunc(function(e,n){var o=e.asinh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(Fe(1).add(o.toFloat().square()).sqrt())}}})}}),Mp=_({atan_:function(r){var t=k(r,"x","atan");return W.runKernelFunc(function(e,n){var o=e.atan(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.toFloat().square().add(1))}}})}}),Lp=_({atanh_:function(r){var t=k(r,"x","atanh");return W.runKernelFunc(function(e,n){var o=e.atanh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(Fe(1).sub(o.toFloat().square()))}}})}}),Wp=_({ceil_:function(r){var t=k(r,"x","ceil");return W.runKernelFunc(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),Ha=_({clipByValue_:function(r,t,e){var n=k(r,"x","clipByValue");B(t<=e,function(){return"Error in clip: min ("+t+") must be less than or equal to max ("+e+")."});var o=[n],i={min:t,max:e};return W.runKernelFunc(function(a,s){var u=a.clip(n,t,e);return s([n]),u},{x:n},function(a,s){var u=s[0];return{x:function(){return a.where(u.greaterEqual(t).logicalAnd(u.lessEqual(e)),Bt(a))}}},"ClipByValue",i,o)}}),_p=_({cos_:function(r){var t=k(r,"x","cos"),e=[t];return W.runKernelFunc(function(n,o){var i=n.cos(t);return o([t]),i},{x:t},function(n,o){var i=o[0];return{x:function(){return i.toFloat().sin().neg().mul(n)}}},"Cos",{},e)}}),Qp=_({cosh_:function(r){var t=k(r,"x","cosh");return W.runKernelFunc(function(e,n){var o=e.cosh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return o.toFloat().sinh().mulStrict(e)}}})}}),zp=_({erf_:function(r){var t=k(r,"x","erf");return B(t.dtype==="int32"||t.dtype==="float32",function(){return"Input dtype must be `int32` or `float32`."}),t.dtype==="int32"&&(t=t.toFloat()),W.runKernelFunc(function(e,n){var o=e.erf(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),ja=_({exp_:function(r){var t=k(r,"x","exp");return W.runKernelFunc(function(e,n){var o=e.exp(t);return n([o]),o},{x:t},function(e,n){return{x:function(){return e.mulStrict(n[0])}}},"Exp",{},[],[!0])}}),Up=_({expm1_:function(r){var t=k(r,"x","expm1");return W.runKernelFunc(function(e,n){var o=e.expm1(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.exp())}}})}}),Hp=_({floor_:function(r){var t=k(r,"x","floor");return W.runKernelFunc(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),jp=_({log_:function(r){var t=k(r,"x","log"),e=[t];return W.runKernelFunc(function(n,o){var i=n.log(t);return o([t]),i},{x:t},function(n,o){var i=o[0];return{x:function(){return n.div(i.toFloat())}}},"Log",{},e)}}),Vp=_({log1p_:function(r){var t=k(r,"x","log1p");return W.runKernelFunc(function(e,n){var o=e.log1p(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.add(1))}}})}}),Gp=_({logSigmoid_:function(r){var t=k(r,"x","logSigmoid");return W.runKernelFunc(function(e,n){var o=e.softplus(t.neg()).neg();return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.neg().sigmoid())}}})}}),Mi=_({neg_:function(r){var t=k(r,"x","neg"),e=[t];return W.runKernelFunc(function(n){return n.neg(t)},{x:t},function(n){return{x:function(){return n.neg()}}},"Neg",{},e)}}),Xp=_({reciprocal_:function(r){var t=k(r,"x","reciprocal");return W.runKernelFunc(function(e,n){var o=e.reciprocal(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.square().neg())}}})}}),Jp=_({round_:function(r){var t=k(r,"x","round");return W.runKernelFunc(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),tl=_({rsqrt_:function(r){var t=k(r,"x","rsqrt"),e=[t];return W.runKernelFunc(function(n,o){var i=n.rsqrt(t);return o([t]),i},{x:t},function(n,o){var i=o[0];return{x:function(){return n.div(i.pow(1.5).mul(2)).neg()}}},"Rsqrt",{},e)}}),nl=_({sigmoid_:function(r){var t=k(r,"x","sigmoid");return W.runKernelFunc(function(e,n){var o=e.sigmoid(t);return n([o]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return e.mul(o.mul(Fe(1).sub(o)))}}},"Sigmoid")}}),Kp=_({sign_:function(r){var t=k(r,"x","sign");return W.runKernelFunc(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),Zp=_({isNaN_:function(r){var t=k(r,"x","isNaN");return W.runKernelFunc(function(e){return e.isNaN(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),qp=_({isInf_:function(r){var t=k(r,"x","isInf");return W.runKernelFunc(function(e){return e.isInf(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),Yp=_({isFinite_:function(r){var t=k(r,"x","isFinite");return W.runKernelFunc(function(e){return e.isFinite(t)},{$x:t},function(e){return{$x:function(){return Bt(e)}}})}}),$p=_({sin_:function(r){var t=k(r,"x","sin"),e=[t];return W.runKernelFunc(function(n,o){var i=n.sin(t);return o([t]),i},{x:t},function(n,o){var i=o[0];return{x:function(){return i.toFloat().cos().mul(n)}}},"Sin",{},e)}}),ev=_({sinh_:function(r){var t=k(r,"x","sinh");return W.runKernelFunc(function(e,n){var o=e.sinh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return o.toFloat().cosh().mulStrict(e)}}})}}),tv=_({softplus_:function(r){var t=k(r,"x","softplus");return W.runKernelFunc(function(e,n){var o=e.softplus(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.sigmoid())}}})}}),nv=_({sqrt_:function(r){var t=k(r,"x","sqrt");return W.runKernelFunc(function(e,n){var o=e.sqrt(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.toFloat().sqrt().mul(2))}}})}}),rv=_({step_:function(r,t){t===void 0&&(t=0);var e=k(r,"x","step");return W.runKernelFunc(function(n){return n.step(e,t)},{$x:e},function(n){return{$x:function(){return Bt(n)}}})}}),ov=_({tan_:function(r){var t=k(r,"x","tan");return W.runKernelFunc(function(e,n){var o=e.tan(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.cos().square())}}})}}),iv=_({tanh_:function(r){var t=k(r,"x","tanh");return W.runKernelFunc(function(e,n){var o=e.tanh(t);return n([o]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return Fe(1).sub(o.square()).mulStrict(e)}}},"Tanh",{},null,[!0])}});function rl(r,t,e,n,o,i){var a,s,u=k(r,"x","batchNorm"),c=k(t,"mean","batchNorm"),l=k(e,"variance","batchNorm");return o!=null&&(a=k(o,"scale","batchNorm")),n!=null&&(s=k(n,"offset","batchNorm")),B(u.rank===2,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),B(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),B(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),a!=null&&B(a.rank===2||a.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."}),s!=null&&B(s.rank===2||s.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),qo(u,c,l,s,a,i)}function ol(r,t,e,n,o,i){var a,s,u=k(r,"x","batchNorm"),c=k(t,"mean","batchNorm"),l=k(e,"variance","batchNorm");return o!=null&&(a=k(o,"scale","batchNorm")),n!=null&&(s=k(n,"offset","batchNorm")),B(u.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),B(c.rank===3||c.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),B(l.rank===3||l.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),a!=null&&B(a.rank===3||a.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."}),s!=null&&B(s.rank===3||s.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),qo(u,c,l,s,a,i)}function il(r,t,e,n,o,i){var a,s,u=k(r,"x","batchNorm"),c=k(t,"mean","batchNorm"),l=k(e,"variance","batchNorm");return o!=null&&(a=k(o,"scale","batchNorm")),n!=null&&(s=k(n,"offset","batchNorm")),B(u.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),B(c.rank===4||c.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),B(l.rank===4||l.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),a!=null&&B(a.rank===4||a.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."}),s!=null&&B(s.rank===4||s.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),qo(u,c,l,s,a,i)}function qo(r,t,e,n,o,i){i==null&&(i=.001);var a,s,u,c=k(r,"x","batchNorm"),l=k(t,"mean","batchNorm"),f=k(e,"variance","batchNorm");o!=null&&(a=k(o,"scale","batchNorm")),n!=null&&(s=k(n,"offset","batchNorm")),B(l.rank===f.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),B(s==null||l.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),B(a==null||l.rank===a.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=c.rank===0||c.rank===1?c.as4D(1,1,1,c.size):c.rank===2?c.as4D(1,1,c.shape[0],c.shape[1]):c.rank===3?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var h=[c,l,f,a];return W.runKernelFunc(function(d,p){var v=d.batchNormalization(u,Li(l),Li(f),i,Li(a),Li(s));return p([c,l,f,a]),v},{x:c,mean:l,variance:f,scale:a,offset:s},function(d,p){var v=p,g=v[0],m=v[1],w=v[2],E=v[3],b=E==null?Fe(1):E,C=gn(m.shape,u.shape),S=[];if(m.rank===1){for(var N=0;N0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=a,u=gn(o.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(o.shape)}}},"Add")}}),vv=_({addN_:function(r){B(Array.isArray(r),function(){return"The argument passed to tf.addN() must be a list of tensors"}),B(r.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+r.length});var t=r.map(function(o,i){return k(o,"tensors"+i,"addN")}),e=t[0];t.forEach(function(o){if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(o){if(!Ke(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var n=t;return W.runKernelFunc(function(o){return o.addN(t)},n,function(o){var i={};return t.forEach(function(a,s){i[s]=function(){return o.clone()}}),i},"AddN")}}),gv=_({addStrict_:function(r,t){var e=k(r,"a","addStrict"),n=k(t,"b","addStrict");return Je(e.shape,n.shape,"Error in addStrict: "),e.add(n)}}),mv=_({atan2_:function(r,t){var e,n=k(r,"a","atan2"),o=k(t,"b","atan2");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a,s){var u=a.atan2(n,o);return s([n,o]),u},{$a:n,$b:o},function(a,s){var u=s[0],c=s[1];return{$a:function(){var l=mt(u.square(),c.square()),f=a.mul(c.div(l)),h=gn(u.shape,i);return h.length>0&&(f=f.sum(h)),f.reshape(u.shape)},$b:function(){var l=mt(u.square(),c.square()),f=Mi(a.mul(u.div(l))),h=gn(c.shape,i);return h.length>0&&(f=f.sum(h)),f.reshape(c.shape)}}})}}),ir=_({div_:function(r,t){var e,n=k(r,"a","div"),o=k(t,"b","div");if(e=vt(n,o),n=e[0],o=e[1],n.dtype==="int32"&&o.dtype==="int32")return cl(n,o);var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a,s){var u=a.realDivide(n,o);return s([n,o]),u},{a:n,b:o},function(a,s){var u=s[0],c=s[1];return{a:function(){var l=a.div(c.toFloat()),f=gn(u.shape,i);return f.length>0?l.sum(f).reshape(u.shape):l},b:function(){var l=a.mul(u.toFloat()),f=gn(c.shape,i);f.length>0&&(l=l.sum(f).reshape(c.shape));var h=c.square();return l.div(h.toFloat()).neg()}}},"Div")}}),Av=_({divNoNan_:function(r,t){var e,n=k(r,"a","div"),o=k(t,"b","div");n=(e=vt(n,o))[0],o=e[1];var i=ir(n,o),a=Bt(i),s=o.equal(a);return no(s,a,i)}}),yv=_({divStrict_:function(r,t){var e=k(r,"a","div"),n=k(t,"b","div");return Je(e.shape,n.shape,"Error in divideStrict: "),e.div(n)}}),cl=_({floorDiv_:function(r,t){var e,n=k(r,"a","floorDiv"),o=k(t,"b","floorDiv");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a,s){var u=a.floorDiv(n,o);return s([n,o]),u},{a:n,b:o},function(a,s){var u=s[0],c=s[1];return{a:function(){var l=a.div(c.toFloat()),f=gn(u.shape,i);return f.length>0?l.sum(f).reshape(u.shape):l},b:function(){var l=a.mul(u.toFloat()),f=gn(c.shape,i);f.length>0&&(l=l.sum(f).reshape(c.shape));var h=c.square();return l.div(h.toFloat()).neg()}}},"FloorDiv")}}),Va=_({maximum_:function(r,t){var e,n=k(r,"a","maximum"),o=k(t,"b","maximum");return e=vt(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),gt(n.shape,o.shape),W.runKernelFunc(function(i,a){var s=i.maximum(n,o);return a([n,o]),s},{a:n,b:o},function(i,a){var s=a[0],u=a[1];return{a:function(){return i.mul(s.greaterEqual(u).toFloat())},b:function(){return i.mul(s.less(u).toFloat())}}},"Maximum")}}),xv=_({maximumStrict_:function(r,t){var e=k(r,"a","maximumStrict"),n=k(t,"b","maximumStrict");return Je(e.shape,n.shape,"Error in maximumStrict: "),e.maximum(n)}}),ll=_({minimum_:function(r,t){var e,n=k(r,"a","minimum"),o=k(t,"b","minimum");return e=vt(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),gt(n.shape,o.shape),W.runKernelFunc(function(i,a){var s=i.minimum(n,o);return a([n,o]),s},{a:n,b:o},function(i,a){var s=a[0],u=a[1];return{a:function(){return i.mul(s.lessEqual(u).toFloat())},b:function(){return i.mul(s.greater(u).toFloat())}}},"Minimum")}}),bv=_({minimumStrict_:function(r,t){var e=k(r,"a","minimumStrict"),n=k(t,"b","minimumStrict");return Je(e.shape,n.shape,"Error in minimumStrict: "),e.minimum(n)}}),wv=_({mod_:function(r,t){var e,n=k(r,"a","mod"),o=k(t,"b","mod");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a,s){var u=a.mod(n,o);return s([n,o]),u},{$a:n,$b:o},function(a,s){var u=s[0],c=s[1];return{$a:function(){var l=gn(u.shape,i);return l.length>0?a.sum(l).reshape(u.shape):a},$b:function(){var l=a.mul(u.div(c).floor().neg()),f=gn(c.shape,i);return f.length>0?l.sum(f).reshape(c.shape):l}}})}}),Ev=_({modStrict_:function(r,t){var e=k(r,"a","modStrict"),n=k(t,"b","modStrict");return Je(e.shape,n.shape,"Error in modStrict: "),e.mod(n)}}),Fn=_({mul_:function(r,t){var e,n=k(r,"a","mul"),o=k(t,"b","mul");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a,s){var u=a.multiply(n,o);return s([n,o]),u},{a:n,b:o},function(a,s){var u=s[0],c=s[1];return{a:function(){var l=a.mul(c.toFloat()),f=gn(u.shape,i);return f.length>0?l.sum(f).reshape(u.shape):l},b:function(){var l=a.mul(u.toFloat()),f=gn(c.shape,i);return f.length>0?l.sum(f).reshape(c.shape):l}}},"Mul")}}),Cv=_({mulStrict_:function(r,t){var e=k(r,"a","mul"),n=k(t,"b","mul");return Je(e.shape,n.shape,"Error in multiplyStrict: "),e.mul(n)}}),Qi=_({pow_:function(r,t){var e,n=k(r,"base","pow"),o=k(t,"exp","pow");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape),a=[n,o];return W.runKernelFunc(function(s,u){var c=s.pow(n,o);return u([n,o,c]),c},{a:n,b:o},function(s,u){var c=u[0],l=u[1],f=u[2];return{a:function(){var h=l.toFloat(),d=s.mul(h.mul(c.pow(h.sub(Fe(1))))),p=gn(c.shape,i);return p.length>0&&(d=d.sum(p)),d.reshape(c.shape)},b:function(){var h=c.greater(0),d=c.log().where(h,Bt(c)),p=s.mul(f.mul(d)),v=gn(l.shape,i);return v.length>0&&(p=p.sum(v)),p.reshape(l.shape)}}},"Pow",{},a,[!0])}}),Iv=_({powStrict_:function(r,t){return Je(r.shape,t.shape,"Error in powStrict: "),r.pow(t)}}),Sv=_({squaredDifferenceStrict_:function(r,t){var e=k(r,"a","squaredDifferenceStrict"),n=k(t,"b","squaredDifferenceStrict");return Je(e.shape,n.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(n)}}),xn=_({sub_:function(r,t){var e,n=k(r,"a","sub"),o=k(t,"b","sub");e=vt(n,o),n=e[0],o=e[1];var i=gt(n.shape,o.shape);return W.runKernelFunc(function(a){return a.subtract(n,o)},{a:n,b:o},function(a){return{a:function(){var s=a,u=gn(n.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=a,u=gn(o.shape,i);return u.length>0&&(s=s.sum(u)),s.neg().reshape(o.shape)}}},"Sub")}}),Rv=_({subStrict_:function(r,t){var e=k(r,"a","subStrict"),n=k(t,"b","subStrict");return Je(e.shape,n.shape,"Error in subStrict: "),e.sub(n)}}),fl=_({equal_:function(r,t){var e,n=k(r,"a","equal"),o=k(t,"b","equal");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i){return i.equal(n,o)},{$a:n,$b:o})}}),Bv=_({equalStrict_:function(r,t){var e=k(r,"a","equalStrict"),n=k(t,"b","equalStrict");return Je(e.shape,n.shape,"Error in equalStrict: "),e.equal(n)}}),kv=_({greater_:function(r,t){var e,n=k(r,"a","greater"),o=k(t,"b","greater");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i){return i.greater(n,o)},{a:n,b:o},null,"Greater")}}),hl=_({greaterEqual_:function(r,t){var e,n=k(r,"a","greaterEqual"),o=k(t,"b","greaterEqual");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i,a){var s=i.greaterEqual(n,o);return a([n,o]),s},{a:n,b:o},function(i,a){var s=a[0],u=a[1];return{a:function(){return Bt(s)},b:function(){return Bt(u)}}},"GreaterEqual")}}),Tv=_({greaterEqualStrict_:function(r,t){var e=k(r,"a","greaterEqualStrict"),n=k(t,"b","greaterEqualStrict");return Je(e.shape,n.shape,"Error in greaterEqualStrict: "),e.greaterEqual(n)}}),Dv=_({greaterStrict_:function(r,t){var e=k(r,"a","greaterStrict"),n=k(t,"b","greaterStrict");return Je(e.shape,n.shape,"Error in greaterStrict: "),e.greater(n)}}),Fv=_({less_:function(r,t){var e,n=k(r,"a","less"),o=k(t,"b","less");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i){return i.less(n,o)},{a:n,b:o},null,"Less")}}),Pv=_({lessEqual_:function(r,t){var e,n=k(r,"a","lessEqual"),o=k(t,"b","lessEqual");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i,a){var s=i.lessEqual(n,o);return a([n,o]),s},{a:n,b:o},null,"LessEqual")}}),Nv=_({lessEqualStrict_:function(r,t){var e=k(r,"a","lessEqualStrict"),n=k(t,"b","lessEqualStrict");return Je(e.shape,n.shape,"Error in lessEqualStrict: "),e.lessEqual(n)}}),Ov=_({lessStrict_:function(r,t){var e=k(r,"a","lessStrict"),n=k(t,"b","lessStrict");return Je(e.shape,n.shape,"Error in lessStrict: "),e.less(n)}}),Mv=_({notEqual_:function(r,t){var e,n=k(r,"a","notEqual"),o=k(t,"b","notEqual");return e=vt(n,o),n=e[0],o=e[1],gt(n.shape,o.shape),W.runKernelFunc(function(i){return i.notEqual(n,o)},{a:n,b:o},null,"NotEqual")}}),Lv=_({notEqualStrict_:function(r,t){var e=k(r,"a","notEqualStrict"),n=k(t,"b","notEqualStrict");return Je(e.shape,n.shape,"Error in notEqualStrict: "),e.notEqual(n)}});function dl(r,t){for(var e=[],n=r;n0,function(){return"mask cannot be scalar"}),Je(s.slice(i,i+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,c=i;c=2&&a.rank>=2&&i.rank===a.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+i.rank+" and "+a.rank+"."}),B(Ke(f,h),function(){return"Error in matMul: outer dimensions ("+f+") and ("+h+") of Tensors with shapes "+i.shape+" and "+a.shape+" must match."}),B(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+i.shape+" and "+a.shape+" and transposeA="+e+" and transposeB="+n+" must match."});var v=i.shape.slice(0,-2).concat([c,l]),g=e?i.as3D(d,s,c):i.as3D(d,c,s),m=n?a.as3D(p,l,u):a.as3D(p,u,l),w={transposeA:e,transposeB:n};return W.runKernelFunc(function(E,b){var C=E.batchMatMul(g,m,e,n);return b([g,m]),C},{a:g,b:m},function(E,b){var C=b,S=C[0],N=C[1];return e||n?!e&&n?{a:function(){return E.matMul(N,!1,!1)},b:function(){return E.matMul(S,!0,!1)}}:e&&!n?{a:function(){return N.matMul(E,!1,!0)},b:function(){return S.matMul(E,!1,!1)}}:{a:function(){return N.matMul(E,!0,!0)},b:function(){return E.matMul(S,!0,!0)}}:{a:function(){return E.matMul(N,!1,!0)},b:function(){return S.matMul(E,!0,!1)}}},"BatchMatMul",w).reshape(v)}}),Hv=_({dot_:function(r,t){var e=k(r,"t1","dot"),n=k(t,"t2","dot");B(!(e.rank!==1&&e.rank!==2||n.rank!==1&&n.rank!==2),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+n.rank+"."});var o=e.rank===1?e.size:e.shape[1],i=n.rank===1?n.size:n.shape[0];return B(o===i,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+i+"."}),e.rank===1&&n.rank===1?e.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():e.rank===1&&n.rank===2?e.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():e.rank===2&&n.rank===1?e.matMul(n.as2D(-1,1)).as1D():e.matMul(n.as2D(n.shape[0],n.shape[1]))}}),jv=_({outerProduct_:function(r,t){var e=k(r,"v1","outerProduct"),n=k(t,"v2","outerProduct");return B(e.rank===1&&n.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+n.rank+"."}),e.as2D(-1,1).matMul(n.as2D(1,-1))}}),Yo=_({reverse_:function(r,t){var e=k(r,"x","reverse");if(e.rank===0)return e.clone();var n=Dt(t,e.shape);return W.runKernelFunc(function(o){return o.reverse(e,n)},{$x:e},function(o){return{$x:function(){return o.reverse(n)}}}).reshapeAs(e)}}),Vv=_({reverse1d_:function(r){var t=k(r,"x","reverse");return B(t.rank===1,function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."}),Yo(t,0)}}),Gv=_({reverse2d_:function(r,t){var e=k(r,"x","reverse");return B(e.rank===2,function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."}),Yo(e,t)}}),Xv=_({reverse3d_:function(r,t){var e=k(r,"x","reverse");return B(e.rank===3,function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."}),Yo(e,t)}}),Jv=_({reverse4d_:function(r,t){var e=k(r,"x","reverse");return B(e.rank===4,function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."}),Yo(e,t)}});function bl(r,t,e,n,o,i){var a=k(r,"x","maxPool"),s=a,u=!1;a.rank===3&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),n==null&&(n=[1,1]),B(s.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),B(Ln(e,n),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"}),i!=null&&B(Ue(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var c=go(s.shape,t,e,n,o,i);if(c.filterWidth===1&&c.filterHeight===1&&Ke(c.inShape,c.outShape))return a.clone();var l=[s],f=W.runKernelFunc(function(h,d){var p=h.maxPool(s,c);return d([s,p]),p},{x:s},function(h,d){var p=d[0],v=d[1];return{x:function(){return function(g,m,w,E,b,C,S,N){var O=k(g,"dy","maxPoolBackprop"),F=k(m,"input","maxPoolBackprop"),P=k(w,"output","maxPoolBackprop");B(F.rank===O.rank,function(){return"Rank of input ("+F.rank+") does not match rank of dy ("+O.rank+")"}),C==null&&(C=[1,1]),B(Ln(b,C),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+b+" and dilations '"+C+"'"}),B(O.rank===4,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+O.rank+"."}),B(F.rank===4,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+F.rank+"."}),N!=null&&B(Ue(S),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+N+" but got pad "+S+"."});var U=go(F.shape,E,b,C,S,N);return W.runKernelFunc(function(Q){return Q.maxPoolBackprop(O,F,P,U)},{$dy:O,$input:F})}(h,p,v,t,e,n,o)}}},"MaxPool",c,l);return u?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}function wl(r,t,e,n,o,i){var a=k(r,"x","avgPool","float32");n==null&&(n=[1,1]),B(Ln(e,n),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"});var s=a,u=!1;a.rank===3&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),B(s.rank===4,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),i!=null&&B(Ue(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var c=go(s.shape,t,e,n,o,i);if(c.filterWidth===1&&c.filterHeight===1&&Ke(c.inShape,c.outShape))return a.clone();var l=W.runKernelFunc(function(f){return f.avgPool(s,c)},{x:s},function(f){return{x:function(){return function(h,d,p,v,g,m){var w=k(h,"dy","avgPoolBackprop"),E=k(d,"input","avgPoolBackprop");B(E.rank===w.rank,function(){return"Rank of input ("+E.rank+") does not match rank of dy ("+w.rank+")"}),g==null&&(g=[1,1]),B(Ln(v,g),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+v+" and dilations '"+g+"'"});var b=E,C=w,S=!1;E.rank===3&&(S=!0,b=E.as4D(1,E.shape[0],E.shape[1],E.shape[2]),C=w.as4D(1,w.shape[0],w.shape[1],w.shape[2])),B(C.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+C.rank+"."}),B(b.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+b.rank+"."});var N=go(b.shape,p,v,g,m),O=W.runKernelFunc(function(F){return F.avgPoolBackprop(C,b,N)},{dy4D:C,input4D:b});return S?O.as3D(O.shape[1],O.shape[2],O.shape[3]):O}(f,s,t,e,n,o)}}},"AvgPool",c);return l=l.cast(a.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var En=_({maxPool_:function(r,t,e,n,o){return bl(r,t,e,1,n,o)}}),$o=_({avgPool_:function(r,t,e,n,o){return wl(r,t,e,1,n,o)}}),Kv=_({pool_:function(r,t,e,n,o,i){o==null&&(o=[1,1]),i==null&&(i=1),n===0&&(n="valid");var a=k(r,"x","maxPool"),s=a,u=!1;a.rank===3&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),B(Ln(i,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"});var c,l=go(s.shape,t,i,o,n),f=[l.dilationHeight,l.dilationWidth];c=n==="same"?function(b,C){var S=b.map(function(F,P){return F+(F-1)*(C[P]-1)}).map(function(F){return F-1}),N=S.map(function(F){return Math.floor(F/2)}),O=S.map(function(F,P){return F-N[P]});return S.map(function(F,P){return[N[P],O[P]]})}([l.filterHeight,l.filterWidth],f):[[0,0],[0,0]];var h=f[0]===1&&f[1]===1,d=function(b,C,S){var N=S.map(function(X){return X[0]}),O=S.map(function(X){return X[1]}),F=b.concat(N,O),P=C.map(function(X,te){return(X-F[te]%X)%X}),U=O.map(function(X,te){return X+P[te]}),Q=C.map(function(X,te){return[N[te],U[te]]}),V=C.map(function(X,te){return[0,P[te]]});return[Q,V]}([l.inHeight,l.inWidth],f,c),p=d[0],v=d[1],g=h?n:"valid",m=h?s:Vu(s,f,p),w=(e==="avg"?function(){return wl(m,t,i,1,g)}:function(){return bl(m,t,i,1,g)})(),E=h?w:Uu(w,f,v);return u?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),Zv=_({maxPool3d_:function(r,t,e,n,o,i,a){i===void 0&&(i="NDHWC");var s=k(r,"x","maxPool3d"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),a==null&&(a=[1,1,1]),B(u.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),B(i==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+i}),B(Ln(e,a),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+a+"'"}),o!=null&&B(Ue(n),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."});var l=Vo(u.shape,t,e,a,n,o,i),f=W.runKernelFunc(function(h,d){var p=h.maxPool3d(u,l);return d([u,p]),p},{x:u},function(h,d){var p=d[0],v=d[1];return{x:function(){return function(g,m,w,E,b,C,S,N){var O=k(g,"dy","maxPool3dBackprop"),F=k(m,"input","maxPool3dBackprop"),P=k(w,"output","maxPool3dBackprop"),U=O,Q=F,V=P,X=!1;F.rank===4&&(X=!0,U=O.as5D(1,O.shape[0],O.shape[1],O.shape[2],O.shape[3]),Q=F.as5D(1,F.shape[0],F.shape[1],F.shape[2],F.shape[3]),V=P.as5D(1,P.shape[0],P.shape[1],P.shape[2],P.shape[3])),B(U.rank===5,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+U.rank+"."}),B(Q.rank===5,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+Q.rank+"."}),B(V.rank===5,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+V.rank+"."}),C==null&&(C=[1,1,1]),B(Ln(b,C),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+b+" and dilations '"+C+"'"}),N!=null&&B(Ue(S),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+N+" but got pad "+S+"."});var te=Vo(Q.shape,E,b,C,S,N),ue=W.runKernelFunc(function(se){return se.maxPool3dBackprop(U,Q,V,te)},{dy5D:U,input5D:Q});return X?ue.as4D(ue.shape[1],ue.shape[2],ue.shape[3],ue.shape[4]):ue}(h,p,v,t,e,a,n,o)}}});return c?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}}),qv=_({avgPool3d_:function(r,t,e,n,o,i,a){i===void 0&&(i="NDHWC");var s=k(r,"x","avgPool3d","float32"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),a==null&&(a=[1,1,1]),B(u.rank===5,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),B(i==="NDHWC",function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+i}),B(Ln(e,a),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+a+"'"}),o!=null&&B(Ue(n),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."});var l=Vo(u.shape,t,e,a,n,o,i),f=W.runKernelFunc(function(h){return h.avgPool3d(u,l)},{x:u},function(h){return{x:function(){return function(d,p,v,g,m,w,E){var b=k(d,"dy","avgPool3dBackprop"),C=k(p,"input","avgPool3dBackprop"),S=b,N=C,O=!1;C.rank===4&&(O=!0,S=b.as5D(1,b.shape[0],b.shape[1],b.shape[2],b.shape[3]),N=C.as5D(1,C.shape[0],C.shape[1],C.shape[2],C.shape[3])),B(S.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+S.rank+"."}),B(N.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+N.rank+"."}),m==null&&(m=[1,1,1]),B(Ln(g,m),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+g+" and dilations '"+m+"'"}),E!=null&&B(Ue(w),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+E+" but got pad "+w+"."});var F=Vo(N.shape,v,g,m,w,E),P=W.runKernelFunc(function(U){return U.avgPool3dBackprop(S,N,F)},{dy5D:S,input5D:N});return O?P.as4D(P.shape[1],P.shape[2],P.shape[3],P.shape[4]):P}(h,u,t,e,a,n,o)}}});return f=f.cast(u.dtype),c?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}}),dr=_({slice_:function(r,t,e){var n,o,i=k(r,"x","slice");if(i.rank===0)throw new Error("Slicing scalar is not possible");(n=typeof t=="number"?[t].concat(new Array(i.rank-1).fill(0)):t.length=0?u:(B(u===-1,function(){return"Negative size values should be exactly -1 but got "+u+" for the slice() size at index "+c+"."}),i.shape[c]-n[c])}),qu(i,n,o);var a=i.shape,s={begin:n,size:o};return W.runKernelFunc(function(u){return u.slice(i,n,o)},{x:i},function(u){for(var c=[],l=0;l0&&(c=c.sum(l)),c.reshape(s.shape)}}},"Prelu")}}),nn=_({relu_:function(r){var t=k(r,"x","relu");return t.dtype==="bool"?t.toInt():W.runKernelFunc(function(e,n){var o=e.relu(t);return n([t]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return e.mulStrict(o.step().toFloat())}}},"Relu")}}),Bl=_({relu6_:function(r){var t=k(r,"x","relu6");return t.dtype==="bool"?t.toInt():W.runKernelFunc(function(e,n){var o=e.relu6(t);return n([t]),o},{x:t},function(e,n){var o=n[0],i=o.lessEqual(6).mul(o.step());return{x:function(){return e.mulStrict(i.toFloat())}}},"Relu6")}}),fg=_({selu_:function(r){var t=k(r,"x","selu");return W.runKernelFunc(function(e,n){var o=e.selu(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){var i=o.greater(Fe(0)),a=Fe(za),s=Fe(Ua),u=e.mul(s),c=e.mul(a).mul(o.toFloat().exp());return no(i,u,c)}}})}}),Wr=_({transpose_:function(r,t){var e=k(r,"x","transpose");if(t==null&&(t=e.shape.map(function(o,i){return i}).reverse()),B(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of perm "+t+"."}),t.forEach(function(o){B(o>=0&&oo)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+t);var i=W.runKernelFunc(function(a){return a.topk(n,t,e)},{$x:n});return{values:i[0],indices:i[1]}}}),Ag=_({scatterND_:function(r,t,e){var n=k(r,"indices","scatterND","int32"),o=k(t,"updates","scatterND");return Zu(o,n,e),W.runKernelFunc(function(i){return i.scatterND(n,o,e)},{indices:n,updates:o},null,"ScatterNd",{shape:e})}}),Za=_({fft_:function(r){B(r.dtype==="complex64",function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+r.dtype+"."});var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return W.runKernelFunc(function(o){return o.fft(n)},{input:r}).reshape(r.shape)}}),ji=_({ifft_:function(r){B(r.dtype==="complex64",function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+r.dtype+"."});var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return W.runKernelFunc(function(o){return o.ifft(n)},{input:r}).reshape(r.shape)}}),qa=_({rfft_:function(r,t){B(r.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+r.dtype});var e,n=r.shape[r.shape.length-1],o=r.size/n;if(t!=null&&tn){var s=r.shape.map(function(m){return m});s[r.shape.length-1]=t-n,e=r.concat(en(s),r.shape.length-1),n=t}else e=r;var u=e.zerosLike(),c=kn(e,u).as2D(o,n),l=Za(c),f=Math.floor(n/2)+1,h=Zn(l),d=fr(l),p=h.split([f,n-f],h.shape.length-1),v=d.split([f,n-f],d.shape.length-1),g=e.shape.slice();return g[e.shape.length-1]=f,kn(p[0],v[0]).reshape(g)}}),Tl=_({irfft_:function(r){var t=r.shape[r.shape.length-1],e=r.size/t;if(t<=2){var n=r.as2D(e,t),o=ji(n);return Zn(o)}var i=[e,2*(t-1)],a=Zn(r).as2D(e,t),s=fr(r).as2D(e,t),u=a.slice([0,1],[e,t-2]).reverse(1),c=s.slice([0,1],[e,t-2]).reverse(1).mul(Fe(-1)),l=a.concat(u,1),f=s.concat(c,1);return n=kn(l,f).as2D(i[0],i[1]),o=ji(n),Zn(o)}}),yg=Object.freeze({fft:Za,ifft:ji,rfft:qa,irfft:Tl}),xg=_({sparseToDense_:function(r,t,e,n){n===void 0&&(n=0);var o=k(r,"sparseIndices","sparseToDense","int32"),i=k(t,"sparseValues","sparseToDense"),a=k(n,"defaultValue","sparseToDense",i.dtype);return function(s,u,c,l){if(s.dtype!=="int32")throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(s.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var f=s.rank>0?s.shape[0]:1,h=s.rank>1?s.shape[1]:1;if(c.length!==h)throw new Error("outputShape has incorrect number of elements:, "+c.length+", should be: "+h+".");var d=u.size;if(u.rank!==0&&(u.rank!==1||d!==f))throw new Error("sparseValues has incorrect shape "+u.shape+", should be [] or ["+f+"]");if(u.dtype!==l.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,i,e,a),W.runKernelFunc(function(s){return s.sparseToDense(o,i,e,a)},{$sparseIndices:o,$sparseValues:i,$defaultValue:a})}}),bg=_({gatherND_:function(r,t){var e=k(t,"indices","gatherND","int32"),n=k(r,"x","gatherND");return W.runKernelFunc(function(o){return o.gatherND(n,e)},{x:n,indices:e},null,"GatherNd")}}),wg=_({diag_:function(r){var t=k(r,"x","diag").flatten(),e=r.shape.concat(r.shape);return W.runKernelFunc(function(n){return n.diag(t)},{$x:t}).reshape(e)}}),Eg=_({dropout_:function(r,t,e,n){var o=k(r,"x","dropout");if(B(o.dtype==="float32",function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),B(t>=0&&t<1,function(){return"rate must be a float in the range [0, 1), but got "+t+"."}),t===0)return r instanceof at?o.clone():o;var i=function(u,c){if(c==null)return u.shape.slice();if(Ke(u.shape,c))return c;if(u.shape.length===c.length){for(var l=[],f=0;f1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank}),B(n.rank-1===o.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+o.rank}),Je(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=n.shape[n.shape.length-1],B(e>0&&e<=i,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+e}),[4,n.data()];case 1:return a=m.sent(),[4,o.data()];case 2:for(s=m.sent(),u=[a.length/i,i],l=u[1],f=T("bool",c=u[0]),h=0;h1?s.div(Fe(a)):s}if(e===Pn.SUM_BY_NONZERO_WEIGHTS){if(o==null)return i.sum().div(Fe(n.size));var u=o.mul(po(n.shape)).notEqual(Fe(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+e)}}),Rg=_({cosineDistance_:function(r,t,e,n,o){o===void 0&&(o=Pn.SUM_BY_NONZERO_WEIGHTS);var i=k(r,"labels","cosineDistance"),a=k(t,"predictions","cosineDistance"),s=null;n!=null&&(s=k(n,"weights","cosineDistance")),Je(i.shape,a.shape,"Error in cosineDistance: ");var u=Fe(1).sub(i.mul(a).sum(e,!0));return Rr(u,s,o)}}),Bg=_({hingeLoss_:function(r,t,e,n){n===void 0&&(n=Pn.SUM_BY_NONZERO_WEIGHTS);var o=k(r,"labels","hingeLoss"),i=k(t,"predictions","hingeLoss"),a=null;e!=null&&(a=k(e,"weights","hingeLoss")),Je(o.shape,i.shape,"Error in hingeLoss: ");var s=Fe(1);o=Fe(2).mul(o).sub(s);var u=s.sub(o.mul(i)).relu();return Rr(u,a,n)}}),kg=_({huberLoss_:function(r,t,e,n,o){n===void 0&&(n=1),o===void 0&&(o=Pn.SUM_BY_NONZERO_WEIGHTS);var i=k(r,"labels","huberLoss"),a=k(t,"predictions","huberLoss"),s=null;e!=null&&(s=k(e,"weights","huberLoss")),Je(i.shape,a.shape,"Error in huberLoss: ");var u=Fe(n),c=a.sub(i).abs(),l=ll(c,u),f=c.sub(l),h=Fe(.5).mul(l.square()).add(u.mul(f));return Rr(h,s,o)}}),Tg=_({logLoss_:function(r,t,e,n,o){n===void 0&&(n=1e-7),o===void 0&&(o=Pn.SUM_BY_NONZERO_WEIGHTS);var i=k(r,"labels","logLoss"),a=k(t,"predictions","logLoss"),s=null;e!=null&&(s=k(e,"weights","logLoss")),Je(i.shape,a.shape,"Error in logLoss: ");var u=Fe(1),c=Fe(n),l=i.mul(a.add(c).log()).neg().sub(u.sub(i).mul(u.sub(a).add(c).log()));return Rr(l,s,o)}}),Dg=_({meanSquaredError_:function(r,t,e,n){n===void 0&&(n=Pn.SUM_BY_NONZERO_WEIGHTS);var o=k(r,"labels","meanSquaredError"),i=k(t,"predictions","meanSquaredError"),a=null;e!=null&&(a=k(e,"weights","meanSquaredError")),Je(o.shape,i.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(i);return Rr(s,a,n)}}),Fg=_({sigmoidCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Pn.SUM_BY_NONZERO_WEIGHTS);var i=k(r,"multiClassLabels","sigmoidCrossEntropy"),a=k(t,"logits","sigmoidCrossEntropy"),s=null;if(e!=null&&(s=k(e,"weights","sigmoidCrossEntropy")),Je(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),n>0){var u=Fe(n),c=Fe(1),l=Fe(.5);i=i.mul(c.sub(u)).add(l.mul(u))}var f=function(h,d){var p=k(h,"labels","sigmoidCrossEntropyWithLogits"),v=k(d,"logits","sigmoidCrossEntropyWithLogits");Je(p.shape,v.shape,"Error in sigmoidCrossEntropyWithLogits: ");var g=v.relu(),m=v.mul(p),w=v.abs().neg().exp().log1p();return g.sub(m).add(w)}(i,a);return Rr(f,s,o)}}),Pg=_({softmaxCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Pn.SUM_BY_NONZERO_WEIGHTS);var i=k(r,"onehotLabels","softmaxCrossEntropy"),a=k(t,"logits","softmaxCrossEntropy"),s=null;if(e!=null&&(s=k(e,"weights","softmaxCrossEntropy")),Je(i.shape,a.shape,"Error in softmaxCrossEntropy: "),n>0){var u=Fe(n),c=Fe(1),l=Fe(i.shape[1]);i=i.mul(c.sub(u)).add(u.div(l))}var f=function(h,d,p){if(p===void 0&&(p=-1),p===-1&&(p=d.rank-1),p!==d.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+d.rank+" and dim was "+p);return Ri(function(v,g,m){var w=g.logSumExp([p],!0),E=g.toFloat().sub(w);return m([v,E]),{value:E.mul(v).neg().sum([p]),gradFunc:function(b,C){var S=C[0],N=C[1],O=Mn(b.shape,[p]);return[b.reshape(O).mul(S.toFloat().sub(N.exp())),b.reshape(O).mul(N.exp().sub(S.toFloat()))]}}})(h,d)}(i,a);return Rr(f,s,o)}}),Ng=Object.freeze({get Reduction(){return Pn},absoluteDifference:Sg,computeWeightedLoss:Rr,cosineDistance:Rg,hingeLoss:Bg,huberLoss:kg,logLoss:Tg,meanSquaredError:Dg,sigmoidCrossEntropy:Fg,softmaxCrossEntropy:Pg});function Nl(r,t){return t===void 0&&(t=!1),W.tidy(function(){if(r.shape.length!==2)throw new Error("qr2d() requires a 2D Tensor, but got a "+r.shape.length+"D Tensor.");for(var e=r.shape[0],n=r.shape[1],o=Hu(e),i=r.clone(),a=Mr([[1]],[1,1]),s=a.clone(),u=e>=n?n:e,c=function(f){var h,d=i,p=s,v=o;h=W.tidy(function(){var g=i.slice([f,f],[e-f,1]),m=g.norm(),w=i.slice([f,f],[1,1]),E=Mr([[-1]]).where(w.greater(0),Mr([[1]])),b=w.sub(E.mul(m)),C=g.div(b);s=C.shape[0]===1?a.clone():a.concat(C.slice([1,0],[C.shape[0]-1,C.shape[1]]),0);var S=E.matMul(b).div(m).neg(),N=i.slice([f,0],[e-f,n]),O=S.mul(s);if(f===0)i=N.sub(O.matMul(s.transpose().matMul(N)));else{var F=N.sub(O.matMul(s.transpose().matMul(N)));i=i.slice([0,0],[f,n]).concat(F,0)}var P=o.slice([0,f],[e,o.shape[1]-f]);if(f===0)o=P.sub(P.matMul(s).matMul(O.transpose()));else{var U=P.sub(P.matMul(s).matMul(O.transpose()));o=o.slice([0,0],[e,f]).concat(U,1)}return[s,i,o]}),s=h[0],i=h[1],o=h[2],Wn([d,p,v])},l=0;ln&&(o=o.slice([0,0],[e,n]),i=i.slice([0,0],[n,n])),[o,i]})}var Og=_({bandPart_:function(r,t,e){if(t%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+t+".");if(e%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+e+".");var n=k(r,"a","bandPart");if(n.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+n.rank+".");var o=n.shape,i=n.shape.slice(-2),a=i[0],s=i[1];if(!(t<=a))throw new Error("bandPart(): numLower ("+t+") must not be greater than the number of rows ("+a+").");if(!(e<=s))throw new Error("bandPart(): numUpper ("+e+") must not be greater than the number of columns ("+s+").");t<0&&(t=a),e<0&&(e=s);var u=xi(0,a,1,"int32").reshape([-1,1]),c=xi(0,s,1,"int32"),l=xn(u,c),f=_i(l.lessEqual(Fe(+t,"int32")),l.greaterEqual(Fe(-e,"int32"))),h=en([a,s],n.dtype);return jn(yn(n.reshape([-1,a,s])).map(function(d){return no(f,d,h)})).reshape(o)}}),Mg=_({gramSchmidt_:function(r){var t;if(Array.isArray(r)){t=!1,B(r!=null&&r.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=r[0].shape[0],n=function(u){B(r[u].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+r[u].shape[0]+" vs. "+e+")"})},o=1;o0)for(var l=0;l= 2, but got rank "+r.rank);if(r.rank===2)return Nl(r,t);var e=r.shape.slice(0,r.shape.length-2).reduce(function(a,s){return a*s}),n=yn(r.reshape([e,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],i=[];return n.forEach(function(a){var s=Nl(a,t),u=s[0],c=s[1];o.push(u),i.push(c)}),[jn(o,0).reshape(r.shape),jn(i,0).reshape(r.shape)]}}),Wg=Object.freeze({bandPart:Og,gramSchmidt:Mg,qr:Lg});function Vi(r,t,e,n,o,i){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),i==null&&(i=0);var a=r.shape[0];return e=Math.min(e,a),B(0<=n&&n<=1,function(){return"iouThreshold must be in [0, 1], but was '"+n+"'"}),B(r.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+r.rank+"'"}),B(r.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+r.shape[1]}),B(t.rank===1,function(){return"scores must be a 1D tensor"}),B(t.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+t.shape[0]}),B(0<=i&&i<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+i+"'"}),{maxOutputSize:e,iouThreshold:n,scoreThreshold:o,softNmsSigma:i}}var _g=_({resizeBilinear_:function(r,t,e){e===void 0&&(e=!1);var n=k(r,"images","resizeBilinear");B(n.rank===3||n.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."}),B(t.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."});var o=n,i=!1;n.rank===3&&(i=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var a=t[0],s=t[1],u=W.runKernelFunc(function(c,l){return l([o]),c.resizeBilinear(o,a,s,e)},{x:o},function(c,l){return{x:function(){return W.runKernelFunc(function(f){return f.resizeBilinearBackprop(c,l[0],e)},{})}}},"ResizeBilinear",{alignCorners:e,newHeight:a,newWidth:s});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Qg=_({resizeNearestNeighbor_:function(r,t,e){e===void 0&&(e=!1);var n=k(r,"images","resizeNearestNeighbor");B(n.rank===3||n.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."}),B(t.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."}),B(n.dtype==="float32"||n.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var o=n,i=!1;n.rank===3&&(i=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var a=t[0],s=t[1],u=W.runKernelFunc(function(c,l){return l([o]),c.resizeNearestNeighbor(o,a,s,e)},{batchImages:o},function(c,l){return{batchImages:function(){return W.runKernelFunc(function(f){return f.resizeNearestNeighborBackprop(c,l[0],e)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),zg=_({nonMaxSuppression_:function(r,t,e,n,o){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY);var i=k(r,"boxes","nonMaxSuppression"),a=k(t,"scores","nonMaxSuppression"),s=Vi(i,a,e,n,o);e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:e,iouThreshold:n,scoreThreshold:o};return W.runKernelFunc(function(c){return c.nonMaxSuppression(i,a,e,n,o)},{boxes:i,scores:a},null,"NonMaxSuppressionV3",u)}}),Ug=function(r,t,e,n,o){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),be(this,void 0,void 0,function(){var i,a,s,u,c,l,f;return Se(this,function(h){switch(h.label){case 0:return i=k(r,"boxes","nonMaxSuppressionAsync"),a=k(t,"scores","nonMaxSuppressionAsync"),s=Vi(i,a,e,n,o),e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([i.data(),a.data()])];case 1:return u=h.sent(),c=u[0],l=u[1],f=Da(c,l,e,n,o),i!==r&&i.dispose(),a!==t&&a.dispose(),[2,f]}})})},Hg=_({nonMaxSuppressionWithScore_:function(r,t,e,n,o,i){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),i===void 0&&(i=0);var a=k(r,"boxes","nonMaxSuppression"),s=k(t,"scores","nonMaxSuppression"),u=Vi(a,s,e,n,o,i),c={maxOutputSize:e=u.maxOutputSize,iouThreshold:n=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:i=u.softNmsSigma},l=W.runKernel("NonMaxSuppressionV5",{boxes:a,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),jg=function(r,t,e,n,o,i){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),i===void 0&&(i=0),be(this,void 0,void 0,function(){var a,s,u,c,l,f,h;return Se(this,function(d){switch(d.label){case 0:return a=k(r,"boxes","nonMaxSuppressionAsync"),s=k(t,"scores","nonMaxSuppressionAsync"),u=Vi(a,s,e,n,o,i),e=u.maxOutputSize,n=u.iouThreshold,o=u.scoreThreshold,i=u.softNmsSigma,[4,Promise.all([a.data(),s.data()])];case 1:return c=d.sent(),l=c[0],f=c[1],h=Fa(l,f,e,n,o,i),a!==r&&a.dispose(),s!==t&&s.dispose(),[2,h]}})})},Vg=_({cropAndResize_:function(r,t,e,n,o,i){var a=k(r,"image","cropAndResize"),s=k(t,"boxes","cropAndResize","float32"),u=k(e,"boxInd","cropAndResize","int32");o=o||"bilinear",i=i||0;var c=s.shape[0];return B(a.rank===4,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."}),B(s.rank===2&&s.shape[1]===4,function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),B(u.rank===1&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),B(n.length===2,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."}),B(n[0]>=1&&n[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+n}),B(o==="bilinear"||o==="nearest",function(){return"method must be bilinear or nearest, but was "+o}),W.runKernelFunc(function(l,f){return l.cropAndResize(a,s,u,n,o,i)},{images:a,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:i,cropSize:n})}}),es=Object.freeze({resizeBilinear:_g,resizeNearestNeighbor:Qg,nonMaxSuppression:zg,nonMaxSuppressionAsync:Ug,nonMaxSuppressionWithScore:Hg,nonMaxSuppressionWithScoreAsync:jg,cropAndResize:Vg}),ts=function(r,t){return!(r>0)||t==="linear"},ns=function(r,t,e){if(e==null||e==="linear")return r;if(e==="relu")return r.mul(t.step());throw new Error("Gradient for activation "+e+" has not been implemented yet.")},rs=function(r,t){var e=t,n=gn(r.shape,t.shape);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},os=function(r,t,e){if(t==="linear")return r;if(t==="relu")return nn(r);if(t==="elu")return Sl(r);if(t==="relu6")return Bl(r);if(t==="prelu")return Rl(r,e);throw new Error("Unknown fused activation "+t+".")},Gg=_({fusedMatMul_:function(r){var t,e=r.a,n=r.b,o=r.transposeA,i=o!==void 0&&o,a=r.transposeB,s=a!==void 0&&a,u=r.bias,c=r.activation,l=c===void 0?"linear":c,f=r.preluActivationWeights;if(ts(W.state.gradientDepth,l)===!1){var h=Ui(e,n,i,s);return u!=null&&(h=mt(h,u)),os(h,l,f)}var d=k(e,"a","fused matMul"),p=k(n,"b","fused matMul");t=vt(d,p),d=t[0],p=t[1];var v=i?d.shape[d.rank-2]:d.shape[d.rank-1],g=s?p.shape[p.rank-1]:p.shape[p.rank-2],m=i?d.shape[d.rank-1]:d.shape[d.rank-2],w=s?p.shape[p.rank-2]:p.shape[p.rank-1],E=d.shape.slice(0,-2),b=p.shape.slice(0,-2),C=Re(E),S=Re(b);B(d.rank>=2&&p.rank>=2&&d.rank===p.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+p.rank+"."}),B(Ke(E,b),function(){return"Error in fused matMul: outer dimensions ("+E+") and ("+b+") of Tensors with shapes "+d.shape+" and "+p.shape+" must match."}),B(v===g,function(){return"Error in fused matMul: inner shapes ("+v+") and ("+g+") of Tensors with shapes "+d.shape+" and "+p.shape+" and transposeA="+i+" and transposeB="+s+" must match."});var N,O,F=d.shape.slice(0,-2).concat([m,w]),P=i?d.as3D(C,v,m):d.as3D(C,m,v),U=s?p.as3D(S,w,g):p.as3D(S,g,w);u!=null&>(F,(N=vt(N=k(u,"bias","fused matMul"),d)[0]).shape),f!=null&&(O=k(f,"prelu weights","fused matMul"));var Q={a:P,b:U};u!=null&&(Q.bias=N),f!=null&&(Q.preluActivationWeights=O);var V=[P,U];return W.runKernelFunc(function(X,te){var ue=X.fusedBatchMatMul({a:P,b:U,transposeA:i,transposeB:s,bias:N,activation:l,preluActivationWeights:O});return te([P,U,ue]),ue},Q,function(X,te){var ue=te[0],se=te[1],oe=te[2],he=ns(X,oe,l),pe={};return u!=null&&(pe={bias:function(){return rs(N,he)}}),Object.assign(i||s?!i&&s?{a:function(){return he.matMul(se,!1,!1)},b:function(){return he.matMul(ue,!0,!1)}}:i&&!s?{a:function(){return se.matMul(he,!1,!0)},b:function(){return ue.matMul(he,!1,!1)}}:{a:function(){return se.matMul(he,!0,!0)},b:function(){return he.matMul(ue,!0,!0)}}:{a:function(){return he.matMul(se,!1,!0)},b:function(){return ue.matMul(he,!0,!1)}},pe)},"_FusedMatMul",{transposeA:i,transposeB:s,activation:l},V,[!0]).reshape(F)}}),Xg=_({fusedConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,i=r.dataFormat,a=i===void 0?"NHWC":i,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,f=r.activation,h=f===void 0?"linear":f,d=r.preluActivationWeights;if(h=h||"linear",ts(W.state.gradientDepth,h)===!1){var p=Yn(t,e,n,o,a,u,c);return l!=null&&(p=mt(p,l)),os(p,h,d)}var v=k(t,"x","conv2d"),g=k(e,"filter","conv2d"),m=v,w=!1;v.rank===3&&(w=!0,m=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),B(m.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+m.rank+"."}),B(g.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."}),c!=null&&B(Ue(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."}),B(m.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+m.shape[3]+") must match input depth for filter "+g.shape[2]+"."}),B(Ln(n,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"}),B(a==="NHWC",function(){return"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported."});var E,b,C=Lr(m.shape,g.shape,n,u,o,c);l!=null&&(E=vt(E=k(l,"bias","fused conv2d"),v)[0],gt(C.outShape,E.shape)),d!=null&&(b=k(d,"prelu weights","fused conv2d"));var S={x:m,filter:g};l!=null&&(S.bias=E),d!=null&&(S.preluActivationWeights=b);var N=[g,m],O=W.runKernelFunc(function(F,P){var U=F.fusedConv2d({input:m,filter:g,convInfo:C,bias:E,activation:h,preluActivationWeights:b});return P([g,m,U]),U},S,function(F,P){var U=P,Q=U[0],V=U[1],X=U[2],te=ns(F,X,h);B($r(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var ue={};return l!=null&&(ue={bias:function(){return rs(E,te)}}),Object.assign({x:function(){return Al(V.shape,te,Q,n,o)},filter:function(){return Ja(V,te,Q.shape,n,o)}},ue)},"FusedConv2D",{convInfo:C,activation:h},N,[!0]);return w?O.as3D(O.shape[1],O.shape[2],O.shape[3]):O}}),Jg=_({fusedDepthwiseConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,i=r.dataFormat,a=i===void 0?"NHWC":i,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,f=r.activation,h=f===void 0?"linear":f,d=r.preluActivationWeights;if(ts(W.state.gradientDepth,h)===!1){var p=zi(t,e,n,o,a,u,c);return l!=null&&(p=mt(p,l)),os(p,h,d)}var v=k(t,"x","depthwiseConv2d"),g=k(e,"filter","depthwiseConv2d"),m=v,w=!1;v.rank===3&&(w=!0,m=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),B(m.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+m.rank+"."}),B(g.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+g.rank+"."}),B(m.shape[3]===g.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+m.shape[3]+") must match the inChannels dimension in filter "+g.shape[2]+"."}),u==null&&(u=[1,1]),B(Ln(n,u),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"}),c!=null&&B(Ue(o),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."});var E,b,C=Lr(m.shape,g.shape,n,u,o,c,!0);l!=null&&(E=vt(E=k(l,"bias","fused conv2d"),v)[0],gt(C.outShape,E.shape)),d!=null&&(b=k(d,"prelu weights","fused depthwiseConv2d"));var S={x:m,filter:g};l!=null&&(S.bias=E),d!=null&&(S.preluActivationWeights=b);var N=[g,m],O=W.runKernelFunc(function(F,P){var U=F.fusedDepthwiseConv2D({input:m,filter:g,convInfo:C,bias:E,activation:h,preluActivationWeights:b});return P([g,m,U]),U},S,function(F,P){B($r(u),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"});var U=P[0],Q=P[1],V=P[2],X=ns(F,V,h),te={};return l!=null&&(te={bias:function(){return rs(E,X)}}),Object.assign({x:function(){return yl(Q.shape,X,U,C)},filter:function(){return xl(Q,X,U.shape,C)}},te)},"FusedDepthwiseConv2D",{convInfo:C,activation:h},N,[!0]);return w?O.as3D(O.shape[1],O.shape[2],O.shape[3]):O}}),Kg=Object.freeze({matMul:Gg,conv2d:Xg,depthwiseConv2d:Jg}),Zg=Object.freeze({image:es,linalg:Wg,losses:Ng,spectral:yg,fused:Kg,signal:Cg,square:Tp,squaredDifference:el,conv1d:_v,conv2d:Yn,conv3d:Qv,depthwiseConv2d:zi,separableConv2d:Ka,conv2dTranspose:zv,conv3dTranspose:Uv,op:_,batchNormalization2d:av,batchNormalization3d:sv,batchNormalization4d:uv,batchNormalization:cv,batchNorm:al,batchNorm2d:lv,batchNorm3d:fv,batchNorm4d:hv,booleanMaskAsync:Wv,complex:kn,real:Zn,imag:fr,concat:An,concat1d:mh,concat2d:Ah,concat3d:yh,concat4d:xh,split:Aa,matMul:Ui,dot:Hv,outerProduct:jv,reverse:Yo,reverse1d:Vv,reverse2d:Gv,reverse3d:Xv,reverse4d:Jv,maxPool:En,avgPool:$o,pool:Kv,maxPool3d:Zv,avgPool3d:qv,slice:dr,slice1d:Yv,slice2d:$v,slice3d:El,slice4d:eg,abs:Dp,acos:Fp,acosh:Pp,asin:Np,asinh:Op,atan:Mp,atanh:Lp,ceil:Wp,clipByValue:Ha,cos:_p,cosh:Qp,erf:zp,exp:ja,expm1:Up,floor:Hp,log:jp,log1p:Vp,logSigmoid:Gp,neg:Mi,reciprocal:Xp,round:Jp,rsqrt:tl,sigmoid:nl,sign:Kp,isNaN:Zp,isInf:qp,isFinite:Yp,sin:$p,sinh:ev,softplus:tv,sqrt:nv,step:rv,tan:ov,tanh:iv,all:tg,any:ng,argMax:rg,argMin:og,logSumExp:ig,max:Hi,mean:ag,min:sg,moments:ug,sum:Il,prod:cg,equal:fl,equalStrict:Bv,greater:kv,greaterEqual:hl,greaterEqualStrict:Tv,greaterStrict:Dv,less:Fv,lessEqual:Pv,lessEqualStrict:Nv,lessStrict:Ov,notEqual:Mv,notEqualStrict:Lv,add:mt,addN:vv,addStrict:gv,atan2:mv,div:ir,divNoNan:Av,divStrict:yv,floorDiv:cl,maximum:Va,maximumStrict:xv,minimum:ll,minimumStrict:bv,mod:wv,modStrict:Ev,mul:Fn,mulStrict:Cv,pow:Qi,powStrict:Iv,squaredDifferenceStrict:Sv,sub:xn,subStrict:Rv,elu:Sl,leakyRelu:lg,prelu:Rl,relu:nn,relu6:Bl,selu:fg,logicalAnd:_i,logicalNot:dv,logicalOr:sl,logicalXor:pv,where:no,whereAsync:ul,buffer:ot,print:kh,batchToSpaceND:Uu,broadcastTo:Th,cast:Dh,clone:Fh,cumsum:Ph,depthToSpace:Nh,expandDims:qn,eye:Hu,multinomial:Oh,oneHot:xa,pad:Yr,pad1d:Mh,pad2d:Lh,pad3d:Wh,pad4d:_h,rand:Qh,randomNormal:zh,randomGamma:Uh,randomUniform:ju,reshape:rr,spaceToBatchND:Vu,squeeze:Gu,stack:jn,tile:vo,truncatedNormal:Hh,unstack:yn,setdiff1dAsync:jh,fill:hr,linspace:gh,ones:po,range:xi,scalar:Fe,tensor:Tn,tensor1d:vn,tensor2d:Mr,tensor3d:ma,tensor4d:Qn,tensor5d:dh,tensor6d:ph,variable:vh,zeros:en,onesLike:zu,zerosLike:Bt,transpose:Wr,softmax:Cr,logSoftmax:Gh,localResponseNormalization:hg,norm:kl,gather:Ga,unsortedSegmentSum:vl,basicLSTMCell:dg,multiRNNCell:pg,movingAverage:vg,stridedSlice:gg,topk:mg,scatterND:Ag,fft:Za,ifft:ji,rfft:qa,irfft:Tl,sparseToDense:xg,gatherND:bg,diag:wg,dropout:Eg,hannWindow:Ya,hammingWindow:Fl,frame:$a,stft:Pl,inTopKAsync:Ig});function fe(r,t){Array.isArray(r)||(r=[r]),r.forEach(function(e){e!=null&&B(e.dtype!=="complex64",function(){return t+" does not support complex64 tensors."})})}function is(r,t,e,n){if(e==="linear")return r.linear(t);if(e==="relu")return r.relu(t);if(e==="elu")return r.elu(t);if(e==="relu6")return r.relu6(t);if(e==="prelu")return r.prelu(t,n);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}var qg=function(r){function t(){var e=r.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new ec(e,W),e}return Pe(t,r),t.prototype.write=function(e,n,o){this.firstUse&&(this.firstUse=!1,J().get("IS_NODE")&&Ai(` ============================ 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 i={};return this.data.set(i,{values:e,dtype:o}),i},t.prototype.move=function(e,n,o,i){this.data.set(e,{values:n,dtype:i})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return be(this,void 0,void 0,function(){return Se(this,function(n){return[2,this.readSync(e)]})})},t.prototype.readSync=function(e){var n=this.data.get(e),o=n.dtype,i=n.complexTensors;return o==="complex64"?Ta(this.readSync(i.real.dataId),this.readSync(i.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var n=this.readSync(e.dataId),o=n;if(e.dtype==="string")try{o=n.map(function(i){return Oe(i)})}catch(i){throw new Error("Failed to decode encoded string bytes into utf-8")}return ot(e.shape,e.dtype,o)},t.prototype.makeOutput=function(e,n,o){var i=this.write(e,n,o);return W.makeTensorFromDataId(i,n,o,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var n=this.data.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return be(this,void 0,void 0,function(){var n;return Se(this,function(o){return n=ee(),e(),[2,{kernelMs:ee()-n}]})})},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.complex=function(e,n){var o=this.makeOutput(null,e.shape,"complex64");return this.data.get(o.dataId).complexTensors={real:W.keep(e.clone()),imag:W.keep(n.clone())},o},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,n,o){if(fe(e,"slice"),Ca(e.shape,n,o)){var i=Ia(n,e.strides),a=Re(o);return Tn(this.readSync(e.dataId).subarray(i,i+a),o,e.dtype)}for(var s=ot(o,e.dtype),u=this.bufferSync(e),c=0;cp&&(p=m,v=g)}l[h]=v}return u},t.prototype.cumsum=function(e,n,o,i){if(fe(e,"cumsum"),n!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+n);for(var a=Lt(e.dtype,"int32"),s=en(e.shape,a),u=this.readSync(s.dataId),c=this.readSync(e.dataId),l=e.shape[e.rank-1],f=i?function(g,m){return g+l-m-1}:function(g,m){return g+m},h=0;hi?1:0})},t.prototype.greaterEqual=function(e,n){return fe([e,n],"greaterEqual"),this.broadcastedBinaryOp(e,n,"bool",function(o,i){return o>=i?1:0})},t.prototype.logicalNot=function(e){fe(e,"logicalNot");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),i=0;i1||n.rank===1?1:Re(n.shape.slice(1)),h=0;h=0&&i>=0?a:(a+i)%i})},t.prototype.max=function(e,n){fe(e,"max"),_n("max",n,e.rank);for(var o=Bn(e.shape,n),i=o[0],a=o[1],s=en(i,e.dtype),u=Re(a),c=this.readSync(s.dataId),l=this.readSync(e.dataId),f=0;fd&&(d=v)}c[f]=d}return s},t.prototype.maximum=function(e,n){return fe([e,n],"maximum"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,i){return Math.max(o,i)})},t.prototype.all=function(e,n){fe(e,"all"),_n("all",n,e.rank);for(var o=Bn(e.shape,n),i=o[0],a=o[1],s=en(i,e.dtype),u=Re(a),c=this.readSync(s.dataId),l=this.readSync(e.dataId),f=0;f0?o[i]=1:o[i]=0;return this.makeOutput(o,e.shape,"float32")},t.prototype.isNaN=function(e){fe(e,"x");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),i=0;i.5?o[i]=Math.ceil(n[i]):o[i]=a%2==0?a:a+1}return this.makeOutput(o,e.shape,"float32")},t.prototype.exp=function(e){fe(e,"exp");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),i=0;i=0?a:Math.exp(a)-1}return this.makeOutput(n,e.shape,"float32")},t.prototype.eluDer=function(e,n){fe([e,n],"eluDer");for(var o=new Float32Array(n.size),i=this.readSync(n.dataId),a=this.readSync(e.dataId),s=0;s=1?a[s]:a[s]*(u+1)}return this.makeOutput(o,n.shape,"float32")},t.prototype.selu=function(e){fe(e,"selu");for(var n=za,o=Ua,i=new Float32Array(e.size),a=this.readSync(e.dataId),s=0;s=0?o*u:n*(Math.exp(u)-1)}return this.makeOutput(i,e.shape,"float32")},t.prototype.clip=function(e,n,o){fe(e,"clip");for(var i=new Float32Array(e.size),a=this.readSync(e.dataId),s=0;so?o:u-n,u=i[a]0?1:n}return this.makeOutput(o,e.shape,"float32")},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,i=e.convInfo,a=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.conv2d(n,o,i);return a&&(c=this.add(c,a)),s&&(c=is(this,c,s,u)),c},t.prototype.conv2d=function(e,n,o){fe([e,n],"conv2d");for(var i=o.filterHeight,a=o.filterWidth,s=o.dilationHeight,u=o.dilationWidth,c=o.padInfo.left,l=o.padInfo.top,f=o.dataFormat==="channelsLast",h=ot(o.outShape,e.dtype),d=e.strides[0],p=f?e.strides[1]:e.strides[2],v=f?e.strides[2]:1,g=f?1:e.strides[1],m=h.strides[0],w=f?h.strides[1]:h.strides[2],E=f?h.strides[2]:1,b=f?1:h.strides[1],C=this.readSync(e.dataId),S=this.readSync(n.dataId),N=h.values,O=0;O=o.inHeight))for(var ue=X*n.strides[0],se=F+te*p,oe=0;oe=o.inWidth))for(var Ne=se+ke*v,et=ue+xe*n.strides[1],Ye=0;Ye=o.inDepth))for(var P=O*n.strides[0],U=E+F*e.strides[1],Q=0;Q=o.inHeight))for(var se=P+te*n.strides[1],oe=U+ue*e.strides[2],he=0;he=o.inWidth))for(var et=se+ke*n.strides[2],Ye=oe+Ne*o.inChannels,st=et,xt=0;xt=o.inHeight))for(var O=S*n.strides[0],F=m+N*e.strides[1],P=0;P=o.inWidth))for(var te=O+V*n.strides[1],ue=F+X*o.inChannels,se=U,oe=te,he=0;hese?se=Ne:o==="avg"&&(oe+=Ne,he++)}if(isNaN(se))break}g[Q+V*E+N]=o==="avg"?oe/he:se}return v.toTensor()},t.prototype.maxPool=function(e,n){return this.pool(e,n,"max")},t.prototype.maxPoolPositions=function(e,n){for(var o=ot(n.outShape,"int32"),i=n.strideHeight,a=n.strideWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,f=n.padInfo.top,h=n.padInfo.left,d=this.bufferSync(e),p=0;pO&&(O=X,F=U*l+V)}o.set(F,p,g,b,v)}}return o.toTensor()},t.prototype.maxPoolBackprop=function(e,n,o,i){fe([n,o],"maxPoolBackprop");for(var a=this.maxPoolPositions(n,i),s=i.strideHeight,u=i.strideWidth,c=i.dilationHeight,l=i.dilationWidth,f=i.effectiveFilterHeight,h=i.effectiveFilterWidth,d=h-1-i.padInfo.left,p=f-1-i.padInfo.top,v=ot(n.shape,"float32"),g=this.bufferSync(a),m=this.bufferSync(e),w=0;w=i.outHeight||Math.floor(P)!==P))for(var U=0;U=i.outWidth||Math.floor(Q)!==Q)){var V=f*h-1-g.get(w,P,Q,E)===F*h+U?1:0;V!==0&&(O+=m.get(w,P,Q,E)*V)}}}v.set(O,w,b,C,E)}return v.toTensor()},t.prototype.avgPoolBackprop=function(e,n,o){fe([e,n],"avgPoolBackprop");for(var i=o.strideHeight,a=o.strideWidth,s=o.filterHeight,u=o.filterWidth,c=o.dilationHeight,l=o.dilationWidth,f=o.effectiveFilterHeight,h=o.effectiveFilterWidth,d=h-1-o.padInfo.left,p=f-1-o.padInfo.top,v=ot(n.shape,"float32"),g=1/(s*u),m=this.bufferSync(e),w=0;w=o.outHeight||Math.floor(P)!==P))for(var U=0;U=o.outWidth||Math.floor(Q)!==Q||(O+=m.get(w,P,Q,E))}}v.set(O*g,w,b,C,E)}return v.toTensor()},t.prototype.pool3d=function(e,n,o){fe(e,"pool3d");for(var i=n.strideDepth,a=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,f=n.effectiveFilterDepth,h=n.effectiveFilterHeight,d=n.effectiveFilterWidth,p=n.padInfo.front,v=n.padInfo.top,g=n.padInfo.left,m=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,w=this.readSync(e.dataId),E=ot(n.outShape,e.dtype),b=E.values,C=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],S=n.outShape[2]*n.outShape[3]*n.outShape[4],N=n.outShape[3]*n.outShape[4],O=n.outShape[4],F=0;FCt?Ct=on:o==="avg"&&(kt+=on,fn++),isNaN(Ct))break}if(isNaN(Ct))break}if(isNaN(Ct))break}b[xt+Q]=o==="avg"?kt/fn:Ct}}}return E.toTensor()},t.prototype.avgPool3d=function(e,n){return fe(e,"avgPool3d"),this.pool3d(e,n,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,n,o){fe([e,n],"avgPool3dBackprop");for(var i=o.strideDepth,a=o.strideHeight,s=o.strideWidth,u=o.filterDepth,c=o.filterHeight,l=o.filterWidth,f=o.dilationDepth,h=o.dilationHeight,d=o.dilationWidth,p=o.effectiveFilterDepth,v=o.effectiveFilterHeight,g=o.effectiveFilterWidth,m=p-1-o.padInfo.front,w=g-1-o.padInfo.left,E=v-1-o.padInfo.top,b=ot(n.shape,"float32"),C=1/(u*c*l),S=this.bufferSync(e),N=0;N=o.outDepth||Math.floor(se)!==se))for(var oe=0;oe=o.outHeight||Math.floor(he)!==he))for(var pe=0;pe=o.outWidth||Math.floor(xe)!==xe||(te+=S.get(N,se,he,xe,O))}}}b.set(te*C,N,F,P,U,O)}return b.toTensor()},t.prototype.maxPool3d=function(e,n){return fe(e,"maxPool3d"),this.pool3d(e,n,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,n){for(var o=ot(n.outShape,"int32"),i=n.strideDepth,a=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,f=n.effectiveFilterDepth,h=n.effectiveFilterHeight,d=n.effectiveFilterWidth,p=n.padInfo.front,v=n.padInfo.top,g=n.padInfo.left,m=this.bufferSync(e),w=0;w=ue&&(ue=et,se=he*h*d+xe*h+Ne)}o.set(se,w,b,O,Q,E)}}}return o.toTensor()},t.prototype.maxPool3dBackprop=function(e,n,o,i){fe([n,o],"maxPool3dBackprop");for(var a=this.maxPool3dPositions(n,i),s=i.strideDepth,u=i.strideHeight,c=i.strideWidth,l=i.dilationDepth,f=i.dilationHeight,h=i.dilationWidth,d=i.effectiveFilterDepth,p=i.effectiveFilterHeight,v=i.effectiveFilterWidth,g=d-1-i.padInfo.front,m=v-1-i.padInfo.left,w=p-1-i.padInfo.top,E=ot(n.shape,"float32"),b=this.bufferSync(a),C=this.bufferSync(e),S=0;S=i.outDepth||Math.floor(ue)!==ue))for(var se=0;se=i.outHeight||Math.floor(oe)!==oe))for(var he=0;he=i.outWidth||Math.floor(pe)!==pe)){var xe=d*p*v-1-b.get(S,ue,oe,pe,N)===te*p*v+se*v+he?1:0;xe!==0&&(X+=C.get(S,ue,oe,pe,N)*xe)}}}}E.set(X,S,O,F,P,N)}return E.toTensor()},t.prototype.cast=function(e,n){return Ba(e,n,this)},t.prototype.reshape=function(e,n){return Di(e,n)},t.prototype.avgPool=function(e,n){return fe(e,"avgPool"),this.pool(e,n,"avg").toFloat()},t.prototype.resizeBilinear=function(e,n,o,i){fe(e,"resizeBilinear");for(var a=e.shape,s=a[0],u=a[1],c=a[2],l=a[3],f=this.readSync(e.dataId),h=new Float32Array(Re([s,n,o,l])),d=[i&&n>1?u-1:u,i&&o>1?c-1:c],p=[i&&n>1?n-1:n,i&&o>1?o-1:o],v=0,g=d[0]/p[0],m=d[1]/p[1],w=0;w1?s-1:s,o&&h>1?u-1:u],v=[o&&f>1?f-1:f,o&&h>1?h-1:h],g=p[0]/v[0],m=p[1]/v[1],w=this.readSync(e.dataId),E=0,b=0;b1?u-1:u,i&&o>1?c-1:c],p=[i&&n>1?n-1:n,i&&o>1?o-1:o],v=d[0]/p[0],g=d[1]/p[1],m=0,w=0;w1?s-1:s,o&&h>1?u-1:u],g=[o&&f>1?f-1:f,o&&h>1?h-1:h],m=v[0]/g[0],w=v[1]/g[1],E=1/m,b=1/w,C=2*Math.ceil(E)+2,S=2*Math.ceil(b)+2,N=0;N=f)){var xe=O+pe*e.strides[1],ke=pe*m;if(F===Math.min(s-1,o?Math.round(ke):Math.floor(ke)))for(var Ne=0;Ne=h)){var Ye=xe+et*e.strides[2],st=et*w;V===Math.min(u-1,o?Math.round(st):Math.floor(st))&&(oe+=p[Ye+se])}}}}d[X+se]=oe}return Qn(d,n.shape,n.dtype)},t.prototype.batchNormalization=function(e,n,o,i,a,s){fe([e,n,o,a,s],"batchNorm");for(var u=this.readSync(e.dataId),c=this.readSync(n.dataId),l=this.readSync(o.dataId),f=a?this.readSync(a.dataId):new Float32Array([1]),h=s?this.readSync(s.dataId):new Float32Array([0]),d=new Float32Array(u.length),p=h.length,v=f.length,g=l.length,m=c.length,w=0,E=0,b=0,C=0,S=0;S=p&&(w=0),E>=m&&(E=0),b>=v&&(b=0),C>=g&&(C=0);return Qn(d,e.shape)},t.prototype.localResponseNormalization4D=function(e,n,o,i,a){fe(e,"localResponseNormalization4D");var s=e.shape[3],u=s-1,c=this.readSync(e.dataId),l=e.size,f=new Float32Array(l);function h(g){for(var m=g%s,w=g-m+Math.max(0,m-n),E=g-m+Math.min(m+n,u),b=0;w<=E;w++){var C=c[w];b+=C*C}return b}for(var d=0;d=0&&s[u]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+n});for(var i=e.shape[0],a=e.shape[1],s=e.shape[2],u=e.shape[3],c=a*n,l=s*n,f=u/(n*n),h=this.readSync(e.dataId),d=new Float32Array(i*c*l*f),p=0,v=0;v=c))for(var V=p>1?(P-O)*(l-1)/(p-1):0,X=v>1?(U-F)*(f-1)/(v-1):0,te=0;te1?O*(l-1)+te*V:.5*(O+P)*(l-1);if(ue<0||ue>l-1)for(var se=0;se1?F*(f-1)+se*X:.5*(F+U)*(f-1))<0||It>f-1)for(oe=0;oe1?F*(f-1)+se*X:.5*(F+U)*(f-1))<0||It>f-1)for(oe=0;oe=e.size/c)throw new Error("Invalid indices: "+v+" does not index into "+e.shape);for(var E=0;E=i/a)throw new Error("Invalid indices: "+m+" does not index into "+o);for(var C=0;C0,function(){return"scheme must not be an empty string."});var n=r.getInstance();B(n.managers[t]==null,function(){return"A model store manager is already registered for scheme '"+t+"'."}),n.managers[t]=e},r.getManager=function(t){var e=this.getInstance().managers[t];if(e==null)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},r.getSchemes=function(){return Object.keys(this.getInstance().managers)},r}();function Xi(r){if(r.indexOf(Eo)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+_r.getSchemes().join(","));return{scheme:r.split(Eo)[0],path:r.split(Eo)[1]}}function zl(r,t,e){return e===void 0&&(e=!1),be(this,void 0,void 0,function(){var n,o,i,a,s,u,c,l,f;return Se(this,function(h){switch(h.label){case 0:return B(r!==t,function(){return"Old path and new path are the same: '"+r+"'"}),B((n=Vn.getLoadHandlers(r)).length>0,function(){return"Copying failed because no load handler is found for source URL "+r+"."}),B(n.length<2,function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+r+"."}),o=n[0],B((i=Vn.getSaveHandlers(t)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+t+"."}),B(i.length<2,function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."}),a=i[0],s=Xi(r).scheme,u=Xi(r).path,c=s===Xi(r).scheme,[4,o.load()];case 1:return l=h.sent(),e&&c?[4,_r.getManager(s).removeModel(u)]:[3,3];case 2:h.sent(),h.label=3;case 3:return[4,a.save(l)];case 4:return f=h.sent(),!e||c?[3,6]:[4,_r.getManager(s).removeModel(u)];case 5:h.sent(),h.label=6;case 6:return[2,f.modelArtifactsInfo]}})})}var ro="models_store",Qr="model_info_store";function Ul(){if(!J().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var r=window||self,t=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ds(r){var t=r.result;t.createObjectStore(ro,{keyPath:"modelPath"}),t.createObjectStore(Qr,{keyPath:"modelPath"})}var Co=function(){function r(t){if(this.indexedDB=Ul(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return r.prototype.save=function(t){return be(this,void 0,void 0,function(){return Se(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},r.prototype.load=function(){return be(this,void 0,void 0,function(){return Se(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},r.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(o,i){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return ds(a)},a.onsuccess=function(){var s=a.result;if(e==null){var u=s.transaction(ro,"readonly"),c=u.objectStore(ro).get(n.modelPath);c.onsuccess=function(){if(c.result==null)return s.close(),i(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));o(c.result.modelArtifacts)},c.onerror=function(v){return s.close(),i(c.error)},u.oncomplete=function(){return s.close()}}else{var l,f=ei(e),h=s.transaction(Qr,"readwrite"),d=h.objectStore(Qr),p=d.put({modelPath:n.modelPath,modelArtifactsInfo:f});p.onsuccess=function(){var v=(l=s.transaction(ro,"readwrite")).objectStore(ro).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:f});v.onsuccess=function(){return o({modelArtifactsInfo:f})},v.onerror=function(g){var m=(d=h.objectStore(Qr)).delete(n.modelPath);m.onsuccess=function(){return s.close(),i(v.error)},m.onerror=function(w){return s.close(),i(v.error)}}},p.onerror=function(v){return s.close(),i(p.error)},h.oncomplete=function(){l==null?s.close():l.oncomplete=function(){return s.close()}}}},a.onerror=function(s){return i(a.error)}})},r.URL_SCHEME="indexeddb://",r}(),Hl=function(r){return J().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Co.URL_SCHEME)?(t=r.slice(Co.URL_SCHEME.length),new Co(t)):null;var t};Vn.registerSaveRouter(Hl),Vn.registerLoadRouter(Hl);var om=function(){function r(){this.indexedDB=Ul()}return r.prototype.listModels=function(){return be(this,void 0,void 0,function(){var t=this;return Se(this,function(e){return[2,new Promise(function(n,o){var i=t.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return ds(i)},i.onsuccess=function(){var a=i.result,s=a.transaction(Qr,"readonly"),u=s.objectStore(Qr).getAll();u.onsuccess=function(){for(var c={},l=0,f=u.result;l0,function(){return"promises must be a none empty array"})})(r),function(i,a){B(i>=0&&i<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+i}),B(a>=0&&a<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+a}),B(a>=i,function(){return"startFraction must be no more than endFraction, but got startFraction "+i+" and endFraction "+a})}(e=e==null?0:e,n=n==null?1:n);var o=0;return Promise.all(r.map(function(i){return i.then(function(a){var s=e+ ++o/r.length*(n-e);return t(s),a}),i}))}function Kl(r,t){return be(this,void 0,void 0,function(){var e,n,o,i,a,s,u,c,l;return Se(this,function(f){switch(f.label){case 0:return t==null&&(t={}),e=t.fetchFunc==null?J().platform.fetch:t.fetchFunc,n=r.map(function(h){return e(h,t.requestInit,{isBinary:!0})}),o=0,i=.5,t.onProgress!=null?[3,2]:[4,Promise.all(n)];case 1:return a=f.sent(),[3,4];case 2:return[4,Jl(n,t.onProgress,o,i)];case 3:a=f.sent(),f.label=4;case 4:return s=a.map(function(h){return h.arrayBuffer()}),u=.5,c=1,t.onProgress!=null?[3,6]:[4,Promise.all(s)];case 5:return l=f.sent(),[3,8];case 6:return[4,Jl(s,t.onProgress,u,c)];case 7:l=f.sent(),f.label=8;case 8:return[2,l]}})})}function Zl(r){var t=this;return function(e,n,o){return n===void 0&&(n=""),be(t,void 0,void 0,function(){var i,a,s,u,c,l,f,h,d,p;return Se(this,function(v){switch(v.label){case 0:if(i=e.map(function(){return!1}),a={},s=o!=null?o.map(function(){return!1}):[],u=[],e.forEach(function(g,m){var w=0;g.weights.forEach(function(E){var b="quantization"in E?E.quantization.dtype:E.dtype,C=ls[b]*Re(E.shape),S=function(){i[m]=!0,a[m]==null&&(a[m]=[]),a[m].push({manifestEntry:E,groupOffset:w,sizeBytes:C})};o!=null?o.forEach(function(N,O){N===E.name&&(S(),s[O]=!0)}):S(),u.push(E.name),w+=C})}),!s.every(function(g){return g}))throw c=o.filter(function(g,m){return!s[m]}),new Error("Could not find weights in manifest with names: "+c.join(", ")+`. Manifest JSON has weights with names: `+u.join(", ")+".");return l=i.reduce(function(g,m,w){return m&&g.push(w),g},[]),f=[],l.forEach(function(g){e[g].paths.forEach(function(m){var w=n+(n.endsWith("/")?"":"/")+m;f.push(w)})}),[4,r(f)];case 1:return h=v.sent(),d={},p=0,l.forEach(function(g){for(var m=e[g].paths.length,w=0,E=0;E0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&B(t.length===2,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return r.prototype.save=function(t){return be(this,void 0,void 0,function(){var e,n,o,i;return Se(this,function(a){switch(a.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(o)],{type:"application/json"}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((i=a.sent()).ok)return[2,{modelArtifactsInfo:ei(t),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}})})},r.prototype.load=function(){return be(this,void 0,void 0,function(){var t,e,n,o,i,a,s,u,c,l,f,h;return Se(this,function(d){switch(d.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=d.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");d.label=2;case 2:return d.trys.push([2,4,,5]),[4,t.json()];case 3:return e=d.sent(),[3,5];case 4:throw d.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" 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.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(o=e.modelTopology,i=e.weightsManifest,a=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,o==null&&i==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return i==null?[3,7]:[4,this.loadWeights(i)];case 6:h=d.sent(),l=h[0],f=h[1],d.label=7;case 7:return[2,{modelTopology:o,weightSpecs:l,weightData:f,userDefinedMetadata:c,generatedBy:a,convertedBy:s,format:u}]}})})},r.prototype.loadWeights=function(t){return be(this,void 0,void 0,function(){var e,n,o,i,a,s,u,c,l,f,h;return Se(this,function(d){switch(d.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(p){var v=p.lastIndexOf("/"),g=p.lastIndexOf("?"),m=p.substring(0,v),w=g>v?p.substring(g):"";return[m+"/",w]}(e),o=n[0],i=n[1],a=this.weightPathPrefix||o,s=[],u=0,c=t;u0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, but got "+e}),B(n.rank===1,function(){return"Expected the rank of labels to be 1, but got "+n.rank}),B(o.rank===1,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),B(n.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+n.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),B(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+e});var i=xa(n.asType("int32"),e),a=xa(o.asType("int32"),e);return i.transpose().matMul(a).asType("int32")}}),i1=Object.freeze({confusionMatrix:gm}),mm=_({fromPixels_:function(r,t){if(t===void 0&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,n=!1,o=!1,i=!1,a=!1;if(r.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)i=!0;else{if(r.getContext==null)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+r.constructor.name);a=!0}if(o&&o&&r.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the