// @tensorflow/tfjs Copyright 2019 Google !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.tf=t.tf||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t,e,n,r){return new(n||(n=Promise))(function(i,a){function o(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(o,s)}u((r=r.apply(t,e||[])).next())})}function i(t,e){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function c(t,e,n){return Math.max(t,Math.min(e,n))}function p(t){return t%2==0?t:t+1}function h(t){for(var e=0,n=0;n=n?i():setTimeout(o,s)}};o()})}function E(t,e){for(var n=1,r=-1,i=0;i=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var a=t.slice();return a[r]=e/n,a}function S(t,e){var n=e.length;return f((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ts)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[o]<=s&&o++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function I(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function A(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function R(t,e){for(var n=0;n=0;--r)n[r]=n[r+1]*t[r+1];return n}function U(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=g(t)),n&&R(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function $(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.encode(e,n)}function X(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.decode(e,n)}var Y=Object.freeze({shuffle:l,clamp:c,nearestLargerEven:p,sum:h,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r0?f:"")+" "}console.log("%c"+s+"\t%c"+o+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+p+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),Q=20,tt=3,et=7;function nt(t,e,n){return N(Array.isArray(t)?parseFloat(t[0].toFixed(et))+" + "+parseFloat(t[1].toFixed(et))+"j":M(t)?"'"+t+"'":"bool"===n?rt(t):parseFloat(t.toFixed(et)).toString(),e)}function rt(t){return 0===t?"false":"true"}function it(t){for(var e=[],n=0;n=this.shape[n]){var o="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(o)}n++}for(var s=t[t.length-1],u=0;u1)for(var l=0;lQ){var c=tt*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice(u-tt*s,u));return"complex64"===r&&(p=it(p),h=it(h)),["["+p.map(function(t,e){return nt(t,a[e],r)}).join(", ")+", ..., "+h.map(function(t,e){return nt(t,a[u-tt+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?it(e):Array.from(e)).map(function(t,e){return nt(t,a[e],r)}).join(", ")+"]"]}var f=n.slice(1),d=i.slice(1),m=i[0]*s,g=[];if(u>Q){for(var v=0;v0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return r(this,void 0,void 0,function(){var e,n;return i(this,function(r){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(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var i={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.state.activeTape.push(i)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.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},t.prototype.endScope=function(t){for(var e=this,n=wt(t),r=new Set(n.map(function(t){return t.id})),i=0;i0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)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)});f(a instanceof lt,function(){return"The result y returned by f() must be a tensor."});var o=function(t,e,n){for(var r={},i={},a=0;a=0;a--)for(o=(d=t[a]).inputs,c=0;c0)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 t,r,s={};s[a.id]=null==n?(r=G(v(t=a.shape),"float32"),lt.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var i=e[r],a=[];if(i.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=lt.make(e.shape,{values:H(e.size,e.dtype)},e.dtype);a.push(r)}}),null==i.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+i.name+".");var o=i.gradient(1===i.outputs.length?a[0]:a),s=function(e){if(!(e in o))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(o)+".");var r=n(function(){return o[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+i.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=i.inputs[e];if(!y(r.shape,a.shape))throw new Error("Error in gradient for op "+i.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in i.inputs)s(u)},i=e.length-1;i>=0;i--)r(i)}(s,o,function(t){return i.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===i.state.gradientDepth&&(i.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),i.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return f(B(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],i=0;ir||n>r)throw i="["+e+"x"+n+"]",new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function re(t,e){return fe(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ie(t,e,n,r,i,a,o,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Bt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,i)}),Bt(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,o,s)}),Bt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ae(t,e,n,r){de(t,r),Bt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function oe(t,e,n,r){return fe(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function se(t,e,n){return t.getUniformLocation(e,n)}function ue(t,e,n,r,i,a){Bt(t,e,function(){return ae(t,e,r,a)}),Bt(t,e,function(){return t.uniform1i(i,a)})}function le(t,e,n,r){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Bt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function ce(t,e,n){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Bt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function pe(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+he(t,e))}function he(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function fe(t,e,n,r){var i=Bt(t,e,function(){return n()});if(null==i)throw new Error(r);return i}function de(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function me(t,e){return void 0===e&&(e=2),v(t.slice(0,t.length-e))}function ge(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function ve(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[me(t)].concat(ge(t))),e}function ye(e,n){var r;void 0===n&&(n=!1);var i=t.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n&&(i*=2,1===(e=e.map(function(t,n){return n>=e.length-2?p(e[n]):e[n]})).length&&(e=[2,e[0]])),2!==e.length){var a=k(e);e=a.newShape}var o=v(e);if(e.length<=1&&o<=i)return[1,o];if(2===e.length&&e[0]<=i&&e[1]<=i)return e;if(3===e.length&&e[0]*e[1]<=i&&e[2]<=i)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=i&&e[1]*e[2]<=i)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=i&&e[3]<=i)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=i&&e[1]*e[2]*e[3]<=i)return[e[0],e[1]*e[2]*e[3]];if(n){var s=me(e),u=2,l=2;return e.length&&(u=(r=ge(e))[0],l=r[1]),w(o=s*(u/2)*(l/2)).map(function(t){return 2*t})}return w(o)}function be(t){return t%2==0}function xe(t,e){if(y(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(be(n)&&be(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&be(t[0])&&be(e[0])}function we(t){if(null==Kt){var e=_t(t);Kt=e.getParameter(e.MAX_TEXTURE_SIZE)}return Kt}function Ne(t){if(null==$t){var e=_t(t);$t=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,$t)}function Ce(t){if(0===t)return 0;var e=_t(t);return Ee(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ee(e,"EXT_disjoint_timer_query")?1:0}function Ee(t,e){return null!=t.getExtension(e)}function Se(t){try{if(null!=_t(t))return!0}catch(t){return!1}return!1}function ke(t){if(0===t)return!1;var e=_t(t);if(1===t){if(!Ee(e,"OES_texture_float"))return!1}else if(!Ee(e,"EXT_color_buffer_float"))return!1;return Ae(e)}function Ie(t){if(0===t)return!1;var e=_t(t);return 1!==t?Ee(e,"EXT_color_buffer_float")?Ae(e):!!Ee(e,"EXT_color_buffer_half_float")&&function(t,e){var n=Pt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(i),a}(e,e.getExtension("EXT_color_buffer_half_float")):!!Ee(e,"OES_texture_float")&&!!Ee(e,"WEBGL_color_buffer_float")&&Ae(e)}function Ae(t){var e=Pt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),i}function Re(t){return 2===t&&null!=_t(t).fenceSync}var Te=Object.freeze({callAndCheck:Bt,canBeRepresented:Ut,getWebGLErrorMessage:jt,getExtensionOrThrow:Gt,createVertexShader:Ht,createFragmentShader:qt,createProgram:Yt,linkProgram:Jt,validateProgram:Zt,createStaticVertexBuffer:Qt,createStaticIndexBuffer:te,getNumChannels:function(){return 2===t.ENV.getNumber("WEBGL_VERSION")?1:4},createTexture:ee,validateTextureSize:ne,createFramebuffer:re,bindVertexBufferToProgramAttribute:ie,bindTextureUnit:ae,unbindTextureUnit:function(t,e,n){de(t,n),Bt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:oe,getProgramUniformLocation:se,bindTextureToProgramUniformSampler:ue,bindCanvasToFramebuffer:function(t,e){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Bt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Bt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:le,unbindColorTextureFromFramebuffer:ce,validateFramebuffer:pe,getFramebufferErrorMessage:he,getBatchDim:me,getRowsCols:ge,getShapeAs3D:ve,getTextureShapeFromLogicalShape:ye,isReshapeFree:xe,getWebGLMaxTextureSize:we,resetMaxTextureSize:function(){Kt=null},resetMaxTexturesInShader:function(){$t=null},getMaxTexturesInShader:Ne,getWebGLDisjointQueryTimerVersion:Ce,hasExtension:Ee,isWebGLVersionEnabled:Se,isCapableOfRenderingToFloatTexture:ke,isDownloadFloatTextureEnabled:Ie,isWebGLFenceEnabled:Re});function De(e){t.ENV.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Oe(){return kt.memory()}function _e(t,e){return kt.tidy(t,e)}function Fe(t){wt(t).forEach(function(t){return t.dispose()})}function Me(t){return kt.keep(t)}function ze(){return kt.backend}function Le(){for(var e=[],n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),f(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),a=0;a=0&&(a=i),Be(i,a,n,r),null==e||!O(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){var o=null==e?"null":e.constructor.name;throw new Error("Argument '"+n+"' passed to '"+r+"' must be a Tensor or TensorLike, but got '"+o+"'")}var s=Pe(e,a);O(e)||Array.isArray(e)||(e=[e]);var u="string"!==a?U(e,a,t.ENV.getBool("DEBUG")):g(e,[],!0);return lt.make(s,{values:u},a)}function We(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Ve(t,e+"["+r+"]",n)},r)}function Ue(t,e){for(var n=0;n=0&&e0}),t.ENV.registerFlag("WEBGL_VERSION",function(){return Se(2)?2:Se(1)?1:0}),t.ENV.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===t.ENV.get("WEBGL_VERSION")}),t.ENV.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),t.ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK",function(){return t.ENV.getBool("HAS_WEBGL")}),t.ENV.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_CLIP",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_REDUCE",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_LAZILY_UNPACK",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_CONV_IM2COL",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return we(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ne(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var e=t.ENV.getNumber("WEBGL_VERSION");return 0===e?0:Ce(e)}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(e=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(e)||/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(e.substr(0,4))));var e}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return ke(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!t.ENV.getBool("WEBGL_FORCE_F16_TEXTURES")&&t.ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),t.ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ie(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Re(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),ut=De;var Qe=Ze({complex_:function(t,e){var n=Ve(t,"real","complex"),r=Ve(e,"imag","complex");return d(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),kt.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),tn=Ze({real_:function(t){var e=Ve(t,"input","real");return kt.runKernel(function(t){return t.real(e)},{$input:e})}}),en=Ze({imag_:function(t){var e=Ve(t,"input","imag");return kt.runKernel(function(t){return t.imag(e)},{$input:e})}});function nn(t,e,n){return rn(t,e,Pe(t,n),n)}function rn(e,n,r,i){if(null==i&&(i=P(e)),"complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!O(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)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(null!=n){K(n);var a=v(n),o=v(r);f(a===o,function(){return"Based on the provided shape, ["+n+"], the tensor should have "+a+" values but has "+o});for(var s=0;s1)return fn([0],r);var i=H(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return"Pass at least one tensor to concat"});var n=We(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")}),e=S(e,n[0].shape)[0];var r=Je(n.map(function(t){return t.shape}),e);if(0===v(r))return nn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});Ye(i,e);var a=n;return kt.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=i.map(function(t){return t[e]});return En(t,n,e).map(function(t){return function(){return t}})})}}),xn=Ze({concat1d_:function(t){return bn(t,0)}}),wn=Ze({concat2d_:function(t,e){return bn(t,e)}}),Nn=Ze({concat3d_:function(t,e){return bn(t,e)}}),Cn=Ze({concat4d_:function(t,e){return bn(t,e)}}),En=Ze({split_:function(t,e,n){void 0===n&&(n=0);var r,i=Ve(t,"x","split");return n=S(n,i.shape)[0],"number"==typeof e?(f(i.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(i.shape[n]/e)):(f(i.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),kt.runKernel(function(t){return t.split(i,r,n)},{$x:i},function(t){return{$x:function(){return bn(t,n)}}})}});function Sn(t,e){return t(e={exports:{}},e.exports),e.exports}var kn=Sn(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+1.1102230246251565e-16*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),In=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),An=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Rn=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),Tn=Sn(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,a=e.i;return e.w=r=r+1640531527|0,n=i[a+34&127],t=i[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,i,a,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,a=-32;a>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=0==(n=s[127&a]^=r+o)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=o,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Dn=Sn(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),On=Sn(function(t){!function(e,n){var r,i=this,a=256,o=6,s="random",u=n.pow(a,o),l=n.pow(2,52),c=2*l,p=a-1;function h(t,p,h){var v=[],y=m(function t(e,n){var r,i=[],a=typeof e;if(n&&"object"==a)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==a?e:e+"\0"}((p=1==p?{entropy:!0}:p||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,g(e)]}}():t,3),v),b=new f(v),x=function(){for(var t=b.g(o),e=u,n=0;t=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,m(g(b.S),e),(p.pass||h||function(t,e,r,i){return i&&(i.S&&d(i,b),t.state=function(){return d(b,{})}),r?(n[s]=t,e):t})(x,y,"global"in p?p.global:this==n,p.state)}function f(t){var e,n=t.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Mn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var i=r||Math.random();this.randu=_n(i.toString()),this.randn=new Fn(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 t.prototype.nextValue=function(){for(var t,e,n,r,i,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(i=this.randu())=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),f(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),f(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),kt.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Vn=Ze({cast_:function(t,e){var n=Ve(t,"x","cast");if(!T(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return kt.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Wn=Ze({clone_:function(t){var e=Ve(t,"x","clone",null);return kt.runKernel(function(t){return lt.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),Un=Ze({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=Ve(t,"x","cumsum"),a=Ke([e|=0],i.rank),o=i;null!=a&&(o=i.transpose(a));var s=Xe(1,i.rank)[0],u=kt.runKernel(function(t){return t.cumsum(o,s,n,r)},{permutedX:o},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),jn=Ze({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Ve(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return f(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),f(a*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape}),f(o%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+o+" for depthToSpace with input shape "+r.shape}),kt.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Gn=Ze({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ve(t,"x","expandDims",null);f(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(f(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),rr(n,r)}}),Hn=Ze({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=Ln([t,e],r),a=t<=e?t:e,o=0;o2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?i.as2D(1,-1):i,u=kt.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===o?u.as1D():u}}),Kn=Ze({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var i=Ve(t,"indices","oneHot","int32"),a=i.shape.concat([e]);return i=i.flatten(),kt.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return fn(i.shape,"float32")}}}).reshape(a)}}),$n=Ze({pad_:function(t,e,n){void 0===n&&(n=0);var r=Ve(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return kt.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),Xn=Ze({pad1d_:function(t,e,n){return void 0===n&&(n=0),f(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),$n(t,[e],n)}}),Yn=Ze({pad2d_:function(t,e,n){return void 0===n&&(n=0),f(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Jn=Ze({pad3d_:function(t,e,n){return void 0===n&&(n=0),f(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Zn=Ze({pad4d_:function(t,e,n){return void 0===n&&(n=0),f(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Qn=Ze({rand_:function(t,e,n){var r=v(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var a=0;a=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),f(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),f(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),kt.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),ar=Ze({squeeze_:function(t,e){var n=Ve(t,"x","squeeze");return rr(n,k(n.shape,e).newShape)}}),or=Ze({stack_:function(t,e){void 0===e&&(e=0);var n=We(t,"tensors","stack");if(f(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,i=n[0].shape,a=n[0].dtype;f(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){d(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){f(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var o=n.map(function(t){return t.expandDims(e)});return bn(o,e)}}),sr=Ze({tile_:function(t,e){var n=Ve(t,"x","tile",null);return f(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),kt.runKernel(function(t,r){var i=t.tile(n,e);return r([n]),i},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=yn(r);if(1===r.rank)for(var i=0;i=-n.shape.length&&e=2*e+1||i%2==1?o.push(i):a.push(i);r.push.apply(r,a),r.push(0),r.push.apply(r,o)}return r}function fr(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var a=1;at.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],i=1,a=0;a1?e.shape[e.rank-1]:1,i=n.length,a=1,o=r;o0;)1&t&&e.push(n),t/=2,n++;return e}function wr(t,e,n){for(var r=[],i=0;i0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),c(0,a,s-1)}function Cr(t,e,n,r,i){var a=e[i],o=n[i]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),o>0?c(0,a,s):c(-1,a,s-1)}function Er(t,e,n){for(var r=n.length,i=0;i1){r=i;break}for(i=r+1;i0||n[i]!==t[i])return!1;return!0}function Sr(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var o=kt.gradients(t,e,null,!0),s=o.value,u=o.grads;f(u.some(function(t){return null!=t}),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()."}),f(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e])}),null!=i&&i.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Ir(t){return kt.customGrad(t)}function Ar(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var Rr=Ze({softmax_:function(t,e){void 0===e&&(e=-1);var n=Ve(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Ir(function(t,n){var r=t.logSumExp([e],!0),i=t.toFloat().sub(r).exp();return n([i]),{value:i,gradFunc:function(t,n){var r=n[0],i=t.mul(r);return i.sub(i.sum([e],!0).mul(r))}}})(n)}}),Tr=Ze({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Ve(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Ir(function(t,n){var r=t.max(e,!0),i=t.sub(r),a=i.toFloat().sub(i.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),Dr=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),Or=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t){throw t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.isNaN=function(t){throw new Error("Not yet implemented")},t.prototype.isInf=function(t){throw new Error("Not yet implemented")},t.prototype.isFinite=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.fusedConv2d=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.avgPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPool3dBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPool3dBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,i,a,o){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.diag=function(t){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function _r(t,e){for(var n=t.length,r=[],i=0;i1&&1===o&&r.unshift(a)}return r}function Fr(t,e){for(var n=[],r=0;r1)&&n.unshift(a)}return n}function Mr(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;ii}).sort(function(t,e){return e.score-t.score}),o=[],s=0;s=0;--h)if(ri(t,c,o[h])>=r){p=!0;break}if(!p&&(o.push(c),o.length>=n))break}return on(o,"int32")}function ri(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),c=Math.min(i[1],i[3]),p=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),f=(s-a)*(u-o),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(a,l),g=Math.max(o,c),v=Math.min(s,p),y=Math.min(u,h),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(f+d-b)}function ii(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var a=t.slice(r,i);return r[n]+=e,a})}function ai(t,e){for(var n=new Array(t.rank),r=0;r":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function pi(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function hi(t,e){return 1===e?[t]:pi(t,e)}function fi(){var e,n,r,i,a,o,s,u,l,c;return 2===t.ENV.getNumber("WEBGL_VERSION")?(e="#version 300 es",n="in",r="out",i="in",a="texture",o="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 0. || val == 0.) ? false : true;\n }\n ",l="",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",n="attribute",r="varying",i="varying",a="texture2D",o="gl_FragColor",s="",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:n,varyingVs:r,varyingFs:i,texture2D:a,output:o,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function di(t,e,n){void 0===n&&(n="index");var r=W(e);return r.map(function(e,i){return"int "+t[i]+" = "+n+" / "+e+"; "+(i===r.length-1?"int "+t[i+1]+" = "+n+" - "+t[i]+" * "+e:"index -= "+t[i]+" * "+e)+";"}).join("")}function mi(t){var e=W(t).map(function(t){return t.toString()});return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var gi="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function vi(t,e,n,r){var i=[];t.forEach(function(t){var e=v(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?i.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var a,o,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n,r,i;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=fi(),"\n vec4 "+r+"() {\n return "+i.texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=fi();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+i[0]+", "+i[1]+", index);\n return "+a.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,a=i[0],o=i[1],s=fi();if(null!=i&&y(e,i))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o+".0, "+a+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=Math.ceil(e[1]/2);return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+l+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){var s=n.slice(1),u=Si(e,s);return"\n "+t(u)+"\n vec4 "+i+"(int b, int row, int col) {\n return "+i+"("+ki(["b","row","col"],[1,2])+");\n }\n "}var l=o[0],c=o[1],p=Math.ceil(n[2]/2),h=p*Math.ceil(n[1]/2),f=fi();return"\n vec4 "+i+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+l+", "+c+", "+h+", "+p+", b, row, col);\n return "+f.texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=o[0],u=o[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f=1?"coords = 0;":u.map(function(t){return"coords."+p[t+c]+" = 0;"}).join("\n");var h;h=s<2&&o>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+c]}).join(", ");var f="return outputValue;",d=1===v(t.shapeInfo.logicalShape),m=1===v(e.logicalShape);if(1!==o||d||m){if(d&&!m)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var g=o-2,y=o-1;u.indexOf(g)>-1&&u.indexOf(y)>-1?f="return vec4(outputValue.x);":u.indexOf(g)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(y)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+l+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+i+"("+h+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",a=e.texShape,o=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&y(o,a))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=Ei(u),c=_r(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+i+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+h[t+p]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+p]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),l=e.texShape,c=fi(),p="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+c.texture2D+"(textureSampler, uv).r;\n }\n ",h=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n #define isnan(value) isnan_custom(value)\n "+t.defineSpecialNaN+"\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+yi+"\n "+bi+"\n "+xi+"\n "}(c);return e.isPacked?(a=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=(a=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+i[0]+", "+i[1]+"));\n int index = resTexRC.x * "+i[1]+" + resTexRC.y;\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),i=r*Math.ceil(t[t.length-2]/2),a=i,o="",s="b, r, c",u=2;u2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],a=Math.ceil(i/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var o,s,u=this.outputShape,l=u.length,c=Ei(l),p=hi("coords",l);if(1===a){var h=Ei(s=l+1);o="\n "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,o="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),m="."+d[s-1],g=d.map(function(t){return"int "+t}),v=hi("sourceLocR",s-1).concat("inIdx.r"),y=hi("sourceLocG",s-1).concat("inIdx.g"),b=hi("sourceLocB",s-1).concat("inIdx.b"),x=hi("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",N=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+"),\n getBestIndicesAChannel("+x.join()+")));",C="vec4(\n getAChannel("+v.join()+"),\n hasNextCol ? getAChannel("+y.join()+") : 0.,\n hasNextRow ? getAChannel("+b.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",E=r?"":"\n float getBestIndicesAChannel("+g.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+g.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+E+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+o+"\n ivec4 srcIdx = ivec4(sourceLocR"+m+", sourceLocG"+m+",\n sourceLocB"+m+", sourceLocA"+m+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+N+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},Ai=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+o+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},Ri=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=p-1-t.padInfo.top,m=h-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+i+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ti=function(t,e,n,r,i,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="0.0";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=i&&(Mr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Di=function(t,e,n,r,i,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="vec4(0.0)";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(Mr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+o+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},Oi=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},_i="return a + b;",Fi="return a - b;",Mi="return a * b;",zi="return (a < 0.) ? b * a : a;",Li=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Pi="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Bi=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Mr(e,n);var i=this.outputShape.length,a="";if(r)if(0===i||1===v(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+Ei(i)+" coords = getOutputCoords();\n ",1===i)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var o=hi("coords",i);a+="\n bool nextRowOutOfBounds =\n ("+o[i-2]+" + 1) >= "+this.outputShape[i-2]+";\n bool nextColOutOfBounds =\n ("+o[i-1]+" + 1) >= "+this.outputShape[i-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+a+"\n\n setOutput(result);\n }\n "},Vi=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Wi=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ui=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},ji=function(t){this.outputShape=[],this.outputShape=Je(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},qi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a="channelsLast"===t.dataFormat,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ki=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,a=t.padInfo.top,o=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+i+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+a+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},$i=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Xi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Yi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=e-1-t.padInfo.top,o=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ji=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var i=t.padInfo.top,a=t.padInfo.left,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,m=d?1:2,g=d?2:3,v=d?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+i+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+h+") *\n getW(wR, wC, "+h+", d2);\n } else {\n dotProd +=\n getX(batch, "+h+", xR, xC) *\n getW(wR, wC, "+h+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2),\n getW(wR, wC, "+h+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1),\n getX(batch, xR, xC, "+h+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC),\n getX(batch, "+h+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+x+"\n "+b+"\n setOutput(result);\n }\n "},Zi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Qi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+r+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "},ta=function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+d+"C"+m+" = vec4(previous.zw, xTexelR"+d+"C"+m+".xy);\n } else {\n xR"+d+"C"+m+" = vec4(0, 0, xTexelR"+d+"C"+m+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = xTexelR"+d+"C"+m+";\n ",m+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(f+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n "),f+="\n xR"+d+"C"+(m+1)+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".xy);\n "):f+="\n xCOffset = xC + "+v+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+d+"C"+(m+1)+" = xTexelR"+d+"C"+(m+2)+";\n "}}else m= 0 && xR < "+e+") {\n ",i%2==1?(f+="\n xCOffset = xC + 1 - "+o+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".zw);\n ",m+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+d+"C"+(m+1)+" = vec4(xTexelR"+d+"C"+(m+2)+".xy, final.xy);\n ")):(f+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + "+o+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".xy, xTexelR"+d+"C"+(m+2)+".xy);\n ",m+11?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],v=g[0],y=g[1],b=g[2],x=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=x[0],N=x[1],C=x[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+N+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+C+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},na=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Ei(r)+" coords = getOutputCoords();\n int end = "+ra(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+ra(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function ra(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var ia=function(t,e){this.variableNames=["A"];var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},aa=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},oa=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),sa=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},ua=function(t){this.variableNames=["A"];var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},la=function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},ca=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode="\n "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+o+", 0., 0., 0.);\n }\n "},pa=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;o+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n \n "+o+"\n\n "+r.output+" = "+s+";\n }\n "},ha=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},fa=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),da=function(t){this.variableNames=["A"];var e=fi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},ma=function(t){this.variableNames=["A"];var e=fi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "},ga=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var i=Ei(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],a=0;a1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function ya(t,e){var n=fi();return Ht(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function ba(t,e){return Qt(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function xa(t,e){return te(t,e,new Uint16Array([0,1,2,2,1,3]))}function wa(t,e,n,r,i,a,o){ne(n,r);var s=ee(t,e),u=t.TEXTURE_2D;return Bt(t,e,function(){return t.bindTexture(u,s)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Bt(t,e,function(){return t.texImage2D(u,0,i,n,r,0,a,o,null)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function Na(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],i.internalFormatFloat,i.textureFormatFloat,t.FLOAT)}function Ca(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function Ea(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Sa(t,e,n,r,i){var a=Lt(n,r);return wa(t,e,a[0],a[1],i.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ka(t,e,n,r,i){var a=Lt(n,r);return wa(t,e,a[0],a[1],i.internalFormatPackedHalfFloat,t.RGBA,i.textureTypeHalfFloat)}function Ia(t,e,n,r){return Bt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),ie(t,e,n,"clipSpacePos",r,3,20,0)&&ie(t,e,n,"uv",r,2,20,12)}function Aa(t,e,n,r,i,a,o){var s,u,l;Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*i*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*i*4),u=t.FLOAT,l=o.internalFormatPackedFloat),s.set(a),Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,i,0,t.RGBA,u,s)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ra(t,e,n,r){Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ta(t,e,n,r,i){var a=t.createBuffer();Bt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var o=16*n*r;return Bt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,o,t.STREAM_READ)}),Bt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Bt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function Da(t,e,n){var r=t,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function Oa(t,e,n,r,i){var a=Mt(n,r),o=a[0],s=a[1],u=new Uint8Array(n*r*4);return Bt(t,e,function(){return t.readPixels(0,0,o,s,i.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function _a(t,e,n,r,i,a,o,s){var u=t,l=new Float32Array(function(t,e){var n=Lt(a,o);return n[0]*n[1]*4}());return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function Fa(t,e,n,r){var i=new Float32Array(n*r*4);return Bt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,i)}),i}var Ma=Object.freeze({createVertexShader:ya,createVertexBuffer:ba,createIndexBuffer:xa,createFloat32MatrixTexture:Na,createFloat16MatrixTexture:Ca,createUnsignedBytesMatrixTexture:Ea,createPackedMatrixTexture:Sa,createFloat16PackedMatrixTexture:ka,bindVertexProgramAttributeStreams:Ia,uploadDenseMatrixToTexture:Aa,uploadPixelDataToTexture:Ra,createBufferFromOutputTexture:Ta,downloadFloat32MatrixFromBuffer:Da,downloadByteEncodedFloatMatrixFromOutputTexture:Oa,downloadPackedMatrixFromBuffer:_a,downloadMatrixFromPackedOutputTexture:Fa}),za=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var n=t.ENV.getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,Ot(n,e)):this.gl=_t(n),1===t.ENV.getNumber("WEBGL_VERSION"))this.textureFloatExtension=Gt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=Gt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else if(Ee(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Ee(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=ba(this.gl,this.debug),this.indexBuffer=xa(this.gl,this.debug),this.framebuffer=re(this.gl,this.debug),this.textureConfig=Pt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return t.ENV.getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&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."),null!=this.outputTexture&&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;Bt(e,this.debug,function(){return e.finish()}),Bt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Bt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Bt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Bt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Bt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Na(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ca(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Ea(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Ra(this.gl,this.debug,t,e)},e.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Aa(this.gl,this.debug,t,e,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ka(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Sa(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(ce(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Bt(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Oa(r.gl,r.debug,e,n,r.textureConfig)})},e.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,i,a){return _a(this.gl,t,0,0,0,i,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Da(this.gl,t,e)},e.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ta(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},e.prototype.createFence=function(e){var n,r,i=this;if(t.ENV.getBool("WEBGL_FENCE_API_ENABLED")){var a=e,o=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=function(){var t=a.clientWaitSync(o,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},n=o}else t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(n=this.beginQuery(),this.endQuery(),r=function(){return i.isQueryAvailable(n,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:n,isFencePassed:r}},e.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Fa(r.gl,r.debug,e,n)})},e.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=qt(e,this.debug,t),r=ya(e,this.debug),i=Yt(e,this.debug);return Bt(e,this.debug,function(){return e.attachShader(i,r)}),Bt(e,this.debug,function(){return e.attachShader(i,n)}),Jt(e,this.debug,i),this.debug&&Zt(e,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=Ia(e,this.debug,this.program,this.vertexBuffer)),i},e.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Bt(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},e.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Zt(this.gl,this.debug,this.program),Bt(this.gl,this.debug,function(){return e.gl.useProgram(t)})},e.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?oe(this.gl,this.debug,t,e):se(this.gl,t,e)},e.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},e.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},e.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),ue(this.gl,this.debug,this.program,t,e,n)},e.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},e.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Lt(e,n),i=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,i,a)},e.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},e.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&Zt(this.gl,this.debug,this.program),pe(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Bt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return t.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Gt(this.gl,this.debug,2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(n.TIME_ELAPSED_EXT,r),r}var i=this.getQueryTimerExtensionWebGL1(),a=i.createQueryEXT();return i.beginQueryEXT(i.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var n=this.gl,r=this.getQueryTimerExtensionWebGL2();n.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return r(this,void 0,void 0,function(){var n=this;return i(this,function(r){switch(r.label){case 0:return[4,C(function(){return n.disposed||n.isQueryAvailable(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return r.sent(),[2,this.getQueryTime(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},e.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||C(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),le(this.gl,this.debug,t,this.framebuffer),this.debug&&pe(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(le(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&pe(this.gl)):ce(this.gl,this.debug,this.framebuffer)},e.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;le(r,this.debug,t,this.framebuffer),this.debug&&pe(r),this.outputTexture=t,Bt(r,this.debug,function(){return r.viewport(0,0,e,n)}),Bt(r,this.debug,function(){return r.scissor(0,0,e,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return i.gl.scissor(t,e,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function La(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,i=e[n],a=i.shape;if(!y(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!i.isUniform){var o=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!y(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var Pa=function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,i=n.inChannels,a=n.strideWidth,o=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=n.dataFormat,h=s.left,f=s.top,d=i*r,m=fi(),g="channelsLast"===p,v=g?0:1,y=g?1:2,b="",x=0;x<=1;x++)for(var w=0;w<=1;w++)b+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+x+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+o+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+i+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+i+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*x+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*x+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},Ba=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+a+";\n setOutput(val);\n }\n "},Va=function(t,e,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},Wa=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+o+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+o+"; j <= "+o+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+a+";\n setOutput(result);\n }\n "},Ua=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,a=t.effectiveFilterWidth,o=i-1-t.padInfo.top,s=a-1-t.padInfo.left,u=i*a-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+a+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},ja=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+p+", "+h+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+i+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+o+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ga=function(t,e,n,r,i,a,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===a&&(a=null),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";a&&(f=o?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",d="result = activation(result);");var m=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+h[0]+");\n result += ("+p[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+d+"\n\n setOutput(result);\n }\n "},Ha=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),qa=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Ka=function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=hi("rc",e),r=Ei(e),i=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",i=t-2;i= "+e[i],i= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),o=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var a=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),o=2;o= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+i+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}},$a=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+i+" start = "+i+"("+a+");\n "+i+" end = "+i+"("+o+");\n\n void main() {\n "+i+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+i+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Xa=function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=hi("rc",r),u=hi("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[i+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var m=4*Math.floor(r/4),g=r%4,v="\n if ("+h+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\n const ivec2 pads = ivec2("+c+", "+p+");\n const float initializationValue = "+f+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+f+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+d+");\n }\n "}},Ja=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left;this.outputShape=t.outShape;var g="avg"===e,v="0.0";if(g||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+p+" * "+h+" +\n wR * "+h+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var b=4*Math.floor(r/4),x=r%4,w="\n if ("+g+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n getValue(batch, xD, xR, xC + 3 * "+l+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Za=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=Math.ceil(i/n);this.outputShape=[r,a];var o="0.0",s="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",s="min"):"max"===e&&(o="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";i%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+o+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},Qa=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+di(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+mi(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},to=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},eo=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},no=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+o+".0,\n "+o+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},ro=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},io=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},ao=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),i=Ei(n);this.userCode="\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},oo=function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=hi("rc",n),i=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],o=Ei(n);function s(n){var r=t.map(function(r,i){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(i,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+i+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+s(r.slice())+";\n if("+i+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+a+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+i+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},so=function(t,e,n,r,i,a,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Ei(i.length),u=Ei(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},uo=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=t.numSegments,o=a*Math.ceil(i/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";i%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var p="";i%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},lo=function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "},co=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Ei(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return po.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return"sourceLoc."+po[e]+" = start["+e+"] + coords."+po[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+i+"));\n }\n "}return t.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,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),po=["x","y","z","w","u","v"],ho=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Ei(this.rank),n=hi("coords",this.rank),r=hi("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+i+")",o="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+" \n vec4 result = vec4(0.);\n "+o+"\n "+s+"\n setOutput(result);\n }\n "}return t.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,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),fo=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,i=Ei(n.length),a=Ei(n.length),o="";if(1===r)o="coords * strides + begin";else{var s=0;o=n.map(function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"}).join(",")}this.userCode="\n "+i+" begin = "+i+"("+t+");\n "+i+" strides = "+i+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+o+"));\n }\n "},mo=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,i=go(e,n),a=vo(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 o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}return this.numUsedTextures++,this.log(),i===Rt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Rt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Rt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Rt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Rt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var i=vo(e,go(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[i],o=a.indexOf(t);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(o,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function go(e,n){if(e===At.UPLOAD)return Rt.PACKED_2X2_FLOAT32;if(e===At.RENDER||null==e)return function(e){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Rt.PACKED_2X2_FLOAT32:Rt.UNPACKED_FLOAT32:e?Rt.PACKED_2X2_FLOAT16:Rt.UNPACKED_FLOAT16}(n);if(e===At.DOWNLOAD||e===At.PIXELS)return Rt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function vo(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var yo=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=Ei(this.rank),a=pi("rc",this.rank),o=new Array(this.rank);for(r=0;r0?this.gpgpu.beginQuery():{startMs:q(),endMs:null}},e.prototype.endTimer=function(e){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=q(),e)},e.prototype.getQueryTime=function(e){return r(this,void 0,void 0,function(){var n;return i(this,function(r){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]})})},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,i=e.texShape,a=e.usage,o=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,a,o)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return t.ENV.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=kt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.sizet.ENV.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(e.length/2),o=this.concat(e.slice(0,a),n),s=this.concat(e.slice(a),n);return this.concat([o,s],n)}if(t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var u=new Gi(e.map(function(t){return t.shape}),n);return this.compileAndRun(u,e)}var l=Je(e.map(function(t){return t.shape}),n),c=e.map(function(t){return t.as2D(-1,v(t.shape.slice(n)))}),p=new ji(c.map(function(t){return t.shape}));return this.compileAndRun(p,c).reshape(l)},e.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ro,e.dtype);var n=new Co(e.shape,Ro);return this.compileAndRun(n,[e])},e.prototype.batchMatMul=function(t,e,n,r){var i=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],o=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===i||1===a)&&o>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,o,1),l=1===a?2:1,c=1===a?e.as3D(s,1,o):e;return this.multiply(u,c).sum(l,!0)}var p=vt(t.dtype,e.dtype),h=new Ga(t.shape,[s,i,a],n,r),f=this.makePackedTensor(h.outputShape,p);return this.compileAndRun(h,[t,e],f)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,i=t.transposeB,a=t.bias,o=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=i?n.shape[1]:n.shape[2],c=e.shape[0],p=vt(e.dtype,n.dtype),h=null!=a,f=null!=s,d=o?Wo(o,!0):null,m=new Ga(e.shape,[c,u,l],r,i,h,d,f),g=this.makePackedTensor(m.outputShape,p),v=[e,n];return a&&v.push(a),s&&v.push(s),this.compileAndRun(m,v,g)},e.prototype.multiply=function(e,n){if("complex64"===e.dtype){var r=this.texData.get(e.dataId),i=this.texData.get(n.dataId),a=new Oi("return areal * breal - aimag * bimag;",e.shape,n.shape),o=new Oi("return areal * bimag + aimag * breal;",e.shape,n.shape),s=[this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag),this.makeComplexComponentTensorHandle(n,i.complexTensors.real),this.makeComplexComponentTensorHandle(n,i.complexTensors.imag)],u=this.compileAndRun(a,s),l=this.compileAndRun(o,s),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Mi,e.dtype);var p=new Li(Mi,e.shape,n.shape),h=this.makeOutputArray(p.outputShape,e.dtype);return this.compileAndRun(p,[e,n],h)},e.prototype.batchNormalization=function(e,n,r,i,a,o){var s=[e,n,r],u=null;null!=o&&(u=o.shape,s.push(o));var l=null;if(null!=a&&(l=a.shape,s.push(a)),t.ENV.getBool("WEBGL_PACK_NORMALIZATION")){var c=new Di(e.shape,n.shape,r.shape,u,l,i);return this.compileAndRun(c,s)}var p=new Ti(e.shape,n.shape,r.shape,u,l,i);return this.compileAndRun(p,s)},e.prototype.localResponseNormalization4D=function(e,n,r,i,a){var o=t.ENV.getBool("WEBGL_PACK_NORMALIZATION")?new Wa(e.shape,n,r,i,a):new Ba(e.shape,n,r,i,a);return this.compileAndRun(o,[e])},e.prototype.LRNGrad=function(t,e,n,r,i,a,o){var s=new Va(e.shape,r,i,a,o);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return X(t)});return ai(Ln(t.shape,t.dtype,n),e)}var r=new yo(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(e,n,r){var i=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xa(e.shape,n,r):new $a(e.shape,n,r);return this.compileAndRun(i,[e])},e.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var r=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xo(e.shape,n):new bo(e.shape,n);return this.compileAndRun(r,[e])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ga(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){f(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=pr(t.shape,e,r),a=hr(i.length,e.length),o=fr(t.shape,e,r),s=dr(n,e.length),u=mr(o,n,e.length);return t.reshape(i).transpose(a).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){f(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var a=1+e.length;ae||n===t?r=!0:n=V(t,n+1);return n}(o,i),u=new uo({windowSize:s,inSize:o,batchSize:a,numSegments:i},e),l=u.outputShape,c=l[0],p=l[1],h=this.makeOutputArray([c,p],r);return this.compileAndRun(u,[t,n],h),h.shape[1]===i?h:(n=gn(0,i).tile([o/s]),this.segOpCompute(h,e,n,r,i))},e.prototype.argMinMaxReduce=function(e,n,r){var i=[n];if(qe("arg"+r.charAt(0).toUpperCase()+r.slice(1),i,e.rank),!t.ENV.getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var a=Ge(e.shape,i),o=a[0],s=v(a[1]),u=e.as2D(-1,s);return this.argReduce(u,r).reshape(o)}return this.argReducePacked(e,r)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var i=new na(t.shape,n,r);return this.compileAndRun(i,[t])},e.prototype.equal=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(equal(a, b));\n","bool");var r=new Li("return float(a == b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.notEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(notEqual(a, b));\n","bool");var r=new Li("return float(a != b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(lessThan(a, b));\n","bool");var r=new Li("return float(a < b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.lessEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(lessThanEqual(a, b));\n","bool");var r=new Li("return float(a <= b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(greaterThan(a, b));\n","bool");var r=new Li("return float(a > b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.greaterEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(greaterThanEqual(a, b));\n","bool");var r=new Li("return float(a >= b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.logicalNot=function(t){var e=new Co(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var r=new Li("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.logicalOr=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var r=new Li("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.select=function(t,e,n){var r=new lo(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,vt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},e.prototype.where=function(t){Le("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return si(t.shape,e)},e.prototype.topk=function(t,e,n){return oi(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){qe("min",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"min",a.dtype).reshape(r)},e.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.mod=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);qe("max",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"max",a.dtype).reshape(r)},e.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.all=function(t,e){qe("all",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"all",a.dtype).reshape(r)},e.prototype.any=function(t,e){qe("any",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"any",a.dtype).reshape(r)},e.prototype.squaredDifference=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("return (a - b) * (a - b);",e.shape,n.shape):new Li("return (a - b) * (a - b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.realDivide=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(b.x == 0.0) {\n result.x = NAN;\n } else if(a.x == b.x) {\n result.x = 1.;\n }\n if(b.y == 0.0) {\n result.y = NAN;\n } else if(a.y == b.y) {\n result.y = 1.;\n }\n if(b.z == 0.0) {\n result.z = NAN;\n } else if(a.z == b.z) {\n result.z = 1.;\n }\n if(b.w == 0.0) {\n result.w = NAN;\n } else if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var r=new Li("\nif (b == 0.0) {\n return NAN;\n}\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"float32");return this.compileAndRun(r,[e,n],i)},e.prototype.floorDiv=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var r=new Li("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"int32");return this.compileAndRun(r,[e,n],i)},e.prototype.add=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,_i);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var r=vt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,_i,r);var i=new Li(_i,e.shape,n.shape),a=this.makeOutputArray(i.outputShape,r);return this.compileAndRun(i,[e,n],a)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Po(t.shape,e),i=this.makePackedTensor(r.outputShape,n);return this.compileAndRun(r,[t],i)},e.prototype.packedBinaryOp=function(t,e,n,r,i){void 0===i&&(i=!1);var a=new Bi(n,t.shape,e.shape,i),o=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],o)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),a=this.texData.get(e.dataId),o=[[i.complexTensors.real,a.complexTensors.real],[i.complexTensors.imag,a.complexTensors.imag]].map(function(i){var a=i[0],o=i[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,o),l=new Li(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,vt(a.dtype,o.dtype));return r.compileAndRun(l,[s,u],c)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(e){if(1===e.length)return e[0];if(e.length>t.ENV.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),r=this.addN(e.slice(0,n)),i=this.addN(e.slice(n));return this.addN([r,i])}var a=e.map(function(t){return t.dtype}).reduce(function(t,e){return vt(t,e)}),o=e.map(function(t){return t.shape}),s=t.ENV.getBool("WEBGL_PACK"),u=s?new li(e[0].shape,o):new ui(e[0].shape,o),l=s?this.makePackedTensor(u.outputShape,a):this.makeOutputArray(u.outputShape,a);return this.compileAndRun(u,e,l)},e.prototype.subtract=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,Fi);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var r=vt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Fi,e.dtype);var i=new Li(Fi,e.shape,n.shape),a=this.makeOutputArray(i.outputShape,r);return this.compileAndRun(i,[e,n],a)},e.prototype.pow=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=r?new Bi("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,n.shape),a=vt(e.dtype,n.dtype),o=r?this.makePackedTensor(i.outputShape,a):this.makeOutputArray(i.outputShape,a);return this.compileAndRun(i,[e,n],o)},e.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,To,e.dtype);var n=new Co(e.shape,To);return this.compileAndRun(n,[e])},e.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Do,e.dtype);var n=new Co(e.shape,Do);return this.compileAndRun(n,[e])},e.prototype.sign=function(t){var e=new Co(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new Co(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isInf=function(t){var e=new Co(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isFinite=function(t){var e=new Co(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.round=function(t){var e=new Co(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Oo,e.dtype);var n=new Co(e.shape,Oo);return this.compileAndRun(n,[e])},e.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_o,e.dtype);var n=new Co(e.shape,_o);return this.compileAndRun(n,[e])},e.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",e.dtype);var n=new Co(e.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(n,[e])},e.prototype.log1p=function(t){var e=new Co(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Co(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Co(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.square=function(t){var e=new Co(t.shape,"return x * x;");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Co(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(e){var n;return n=t.ENV.getBool("WEBGL_PACK")?new Po(e.shape,zo):new Co(e.shape,Io),this.compileAndRun(n,[e])},e.prototype.prelu=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi(Pi,e.shape,n.shape):new Li(zi,e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.elu=function(e){if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Lo,e.dtype);var n=new Co(e.shape,Ao);return this.compileAndRun(n,[e])},e.prototype.eluDer=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",e.shape,n.shape):new Li("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.selu=function(t){var e=new Co(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Co(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},e.prototype.clip=function(e,n,r){var i,a=(i=t.ENV.getBool("WEBGL_PACK_CLIP")?new Wi(e.shape):new Vi(e.shape)).getCustomSetupFunc(n,r);return this.compileAndRun(i,[e],null,a)},e.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ko,e.dtype);var n=new Co(e.shape,ko);return this.compileAndRun(n,[e])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Ui(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Co(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Co(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Co(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Co(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Co(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.sinh=function(t){var e=new Co(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new Co(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new Co(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new Co(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Co(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new Co(t.shape,function(t){return void 0===t&&(t=0),Eo+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(e,n,r,i,a,o){var s=e.shape,u=this.texData.get(e.dataId),l=r.inChannels,c=s[0]*s[1]*s[2],p=r.outChannels,h="channelsLast"===r.dataFormat,d=(1===c||1===p)&&l>1e3,m=s[2]%2!=0&&!!u.isPacked;if(d||!t.ENV.getBool("WEBGL_LAZILY_UNPACK")||!t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!m){var g=h?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],v=this.reshape(e,[1,g,r.inChannels]),y=this.reshape(n,[1,r.inChannels,r.outChannels]);return this.reshape(this.fusedBatchMatMul({a:v,b:y,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:o}),r.outShape)}var b=h?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),x=lt.make([1,b,r.inChannels],{dataId:e.dataId},e.dtype,this),w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,f(xe(u.shape,x.shape),function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"});var N=this.reshape(n,[1,r.inChannels,r.outChannels]),C=this.fusedBatchMatMul({a:x,b:N,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:o}),E=this.texData.get(C.dataId);return f(E.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=w,E.shape=r.outShape,lt.make(r.outShape,{dataId:C.dataId},C.dtype,this)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,i,a){var o=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,p="channelsLast"===n.dataFormat,h=o*s*u,f=c*l,d=[h,f],m=t.squeeze([0]),g=e.reshape([1,h,-1]),v=new Pa(d,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,d[0],d[1]]),b=null!=r,x=null!=a,w=i?Wo(i,!0):null,N=new Ga(y.shape,[1,f,n.outChannels],!0,!1,b,w,x),C=[y,g];r&&C.push(r),x&&C.push(a);var E=this.compileAndRun(N,C);return p?E.reshape([1,c,l,n.outChannels]):E.reshape([1,n.outChannels,c,l])},e.prototype.fusedConv2d=function(e,n,r,i,a,o){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,i,a,o);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,i,a,o);var s=null!=i,u=null!=o,l=a?Wo(a,!1):null,c=new Ji(r,s,l,u),p=[e,n];return i&&p.push(i),o&&p.push(o),this.compileAndRun(c,p)},e.prototype.conv2d=function(e,n,r){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r);var i=new Ji(r);return this.compileAndRun(i,[e,n])},e.prototype.conv2dDerInput=function(t,e,n){var r=new qi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Hi(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2D=function(e,n,r){var i;return t.ENV.getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels==1?(i=new ta(r),this.compileAndRun(i,[e,n],this.makePackedTensor(r.outShape,e.dtype))):(i=new Qi(r),this.compileAndRun(i,[e,n]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Yi(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Xi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Zi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new $i(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new Ki(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Ya(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},e.prototype.avgPool=function(t,e){var n=new Ya(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},e.prototype.maxPoolBackprop=function(t,e,n,r){var i=new Ya(r,"max",!0),a=this.compileAndRun(i,[e]),o=new Ua(r),s=this.makeOutputArray(o.outputShape,e.dtype),u=this.compileAndRun(o,[t,a],s);return a.dispose(),u},e.prototype.avgPoolBackprop=function(t,e,n){var r=new Ai(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},e.prototype.cast=function(t,e){return $r(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,a=0;a1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],o="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=a*e,l=o/(e*e),c=new oa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return ii(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=br(0,t,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=t.reshape([a,i]),p=e.reshape([a,o]);if(0===u)return Xr(nn([]),n);var h=an(0),f=new so(a,i,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var i=br(0,t,n),a=i.sliceRank,o=i.numUpdates,s=i.strides,u=i.outputSize,l=new so(o,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ha("return real * expR - imag * expI;",t.shape,e),i=new ha("return real * expI + imag * expR;",t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],o=this.compileAndRun(r,a),s=this.compileAndRun(i,a),u=this.complex(o,s).as2D(t.shape[0],t.shape[1]);return o.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=gr(t,e),a=i[0],o=i[1],s=i[2],u=i[3],l=e.reshape([o,r]),c=t.reshape([t.size/s,s]),p=new va(r,u,[o,s]);return this.compileAndRun(p,[c,l]).reshape(a)},e.prototype.fill=function(t,e,n){if("string"===(n=n||P(e))){var r=A(n,v(t));return r.fill(e),lt.make(t,{values:r},n)}var i=new fa(t,e),a=i.getCustomSetupFunc(e),o=this.makeOutputArray(t,n);return this.compileAndRun(i,[],o,a)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Yr(t,e,n)},e.prototype.makeOutputArray=function(t,e){return lt.make(t,{},e,this)},e.prototype.makePackedTensor=function(t,e){var n=lt.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},e.prototype.unpackTensor=function(t){var e=new Bo(t.shape);return this.compileAndRun(e,[t],lt.make(e.outputShape,{},t.dtype,this))},e.prototype.packTensor=function(t){var e=new Ka(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},e.prototype.packedReshape=function(t,e){var n=t.reshape([me(t.shape)].concat(ge(t.shape))),r=[me(e)].concat(ge(e)),i=new Qa(r,n.shape);return this.compileAndRun(i,[n]).reshape(e)},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,i=n.shape,a=n.dtype,o=ve(i),s=zt(i),u=this.makeTensorHandle(i,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new aa(o,s):new ia(o,s),this.compileAndRun(e,[{shape:o,dtype:a,dataId:t}],u,null,!0),u},e.prototype.compileAndRun=function(e,n,r,i,a){var o=this;if(void 0===a&&(a=!1),null==r&&(r=e.usesPackedTextures?this.makePackedTensor(e.outputShape,n[0].dtype):this.makeOutputArray(e.outputShape,n[0].dtype)),0===r.size)return this.texData.get(r.dataId).values=I(r.dtype,0),r;var s=n.map(function(n){if("complex64"===n.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var r=o.texData.get(n.dataId);if(null==r.texture){if(!e.usesPackedTextures&&v(n.shape)<=t.ENV.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:n.shape,texData:null,isUniform:!0,uniformValues:r.values};e.usesPackedTextures&&(r.isPacked=!0,r.shape=n.shape)}else if(!!r.isPacked!=!!e.usesPackedTextures)n=r.isPacked?o.unpackTensor(n):o.packTensor(n),r=o.texData.get(n.dataId);else if(r.isPacked&&!xe(r.shape,n.shape)){var i=n,a=n.shape;n.shape=r.shape,n=o.packedReshape(n,a),r=o.texData.get(n.dataId),i.shape=a}return o.uploadToGPU(n.dataId),{shape:n.shape,texData:r,isUniform:!1}});this.uploadToGPU(r.dataId);var u,l={shape:r.shape,texData:this.texData.get(r.dataId),isUniform:!1},c=function(t,e,n){var r="";s.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(e,0,l),p=this.getAndSaveBinary(c,function(){return function(e,n,r,i){var a=n.userCode,o=r.map(function(t,e){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:n.variableNames[e],shapeInfo:r}}),s=o.map(function(t){return t.shapeInfo}),u={logicalShape:i.shape,texShape:i.texData.texShape,isUniform:!1,isPacked:i.texData.isPacked,flatOffset:null},l=vi(o,u,a,n.usesPackedTextures),c=e.createProgram(l),p=null,h=e.getUniformLocation(c,"NAN",!1);1===t.ENV.getNumber("WEBGL_VERSION")&&(p=e.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d0)return 32}return 16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,i=n.dtype,a=n.values,o=n.texture,s=n.usage,u=n.isPacked;if(null==o){var l,c=null!=this.activeTimers;c&&(l=q());var p=n.texShape;if(null==p&&(p=ye(r,u),n.texShape=p),null!=a){var h=ve(r),f=void 0,d=p[1],m=p[0],g=a instanceof Uint8Array;u?(d=(e=Lt(p[0],p[1]))[0],m=e[1],f=new pa(h,[m,d],g)):f=new ca(h,[m,d],g);var y=this.makeTensorHandle([m,d],i);this.texData.get(y.dataId).usage=g?At.PIXELS:At.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,m,a);var b=this.makeTensorHandle(f.outputShape,y.dtype);b.size=v(f.outputShape),this.texData.get(b.dataId).isPacked=u,this.compileAndRun(f,[y],b);var x=this.texData.get(b.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(y.dataId),this.texData.delete(b.dataId),n.values=null,c&&(this.uploadWaitMs+=q()-l)}else{var w=this.acquireTexture(p,s,i,u);n.texture=w}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*_(e)},e}();It()&&kt.registerBackend("webgl",function(){return new jo},2);var Go=Ze({abs_:function(t){var e=Ve(t,"x","abs");return"complex64"===e.dtype?kt.runKernel(function(t){return t.complexAbs(e)},{$x:e}):kt.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),Ho=Ze({acos_:function(t){var e=Ve(t,"x","acos");return kt.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),qo=Ze({acosh_:function(t){var e=Ve(t,"x","acosh");return kt.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),Ko=Ze({asin_:function(t){var e=Ve(t,"x","asin");return kt.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).sub(n.toFloat().square()).sqrt())}}})}}),$o=Ze({asinh_:function(t){var e=Ve(t,"x","asinh");return kt.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).add(n.toFloat().square()).sqrt())}}})}}),Xo=Ze({atan_:function(t){var e=Ve(t,"x","atan");return kt.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),Yo=Ze({atanh_:function(t){var e=Ve(t,"x","atanh");return kt.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(an(1).sub(n.toFloat().square()))}}})}}),Jo=Ze({ceil_:function(t){var e=Ve(t,"x","ceil");return kt.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),Zo=Ze({clipByValue_:function(t,e,n){var r=Ve(t,"x","clipByValue");return f(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),kt.runKernel(function(t,i){var a=t.clip(r,e,n);return i([r]),a},{$x:r},function(t,r){var i=r[0];return{$x:function(){return t.where(i.greaterEqual(e).logicalAnd(i.lessEqual(n)),yn(t))}}})}}),Qo=Ze({cos_:function(t){var e=Ve(t,"x","cos");return kt.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),ts=Ze({cosh_:function(t){var e=Ve(t,"x","cosh");return kt.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),es=Ze({erf_:function(t){var e=Ve(t,"x","erf");return f("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),kt.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),ns=Ze({exp_:function(t){var e=Ve(t,"x","exp");return kt.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),rs=Ze({expm1_:function(t){var e=Ve(t,"x","expm1");return kt.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),is=Ze({floor_:function(t){var e=Ve(t,"x","floor");return kt.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),as=Ze({log_:function(t){var e=Ve(t,"x","log");return kt.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),os=Ze({log1p_:function(t){var e=Ve(t,"x","log1p");return kt.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),ss=Ze({logSigmoid_:function(t){var e=Ve(t,"x","logSigmoid");return kt.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),us=Ze({neg_:function(t){var e=Ve(t,"x","neg");return kt.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),ls=Ze({reciprocal_:function(t){var e=Ve(t,"x","reciprocal");return kt.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),cs=Ze({round_:function(t){var e=Ve(t,"x","round");return kt.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ps=Ze({rsqrt_:function(t){var e=Ve(t,"x","rsqrt");return kt.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),hs=Ze({sigmoid_:function(t){var e=Ve(t,"x","sigmoid");return kt.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(an(1).sub(n)))}}})}}),fs=Ze({sign_:function(t){var e=Ve(t,"x","sign");return kt.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ds=Ze({isNaN_:function(t){var e=Ve(t,"x","isNaN");return kt.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ms=Ze({isInf_:function(t){var e=Ve(t,"x","isInf");return kt.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),gs=Ze({isFinite_:function(t){var e=Ve(t,"x","isFinite");return kt.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),vs=Ze({sin_:function(t){var e=Ve(t,"x","sin");return kt.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),ys=Ze({sinh_:function(t){var e=Ve(t,"x","sinh");return kt.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),bs=Ze({softplus_:function(t){var e=Ve(t,"x","softplus");return kt.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),xs=Ze({sqrt_:function(t){var e=Ve(t,"x","sqrt");return kt.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),ws=Ze({square_:function(t){var e=Ve(t,"x","square");return kt.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),Ns=Ze({step_:function(t,e){void 0===e&&(e=0);var n=Ve(t,"x","step");return kt.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return yn(t)}}})}}),Cs=Ze({tan_:function(t){var e=Ve(t,"x","tan");return kt.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),Es=Ze({tanh_:function(t){var e=Ve(t,"x","tanh");return kt.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return an(1).sub(n.square()).mulStrict(t)}}})}});function Ss(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),f(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),f(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(2===o.rank||1===o.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function ks(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),f(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),f(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(3===o.rank||1===o.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function Is(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),f(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),f(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(4===o.rank||1===o.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function As(t,e,n,r,i,a){null==a&&(a=.001);var o,s,u,l=Ve(t,"x","batchNorm"),c=Ve(e,"mean","batchNorm"),p=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(c.rank===p.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),f(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),f(null==o||c.rank===o.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,kt.runKernel(function(t,e){var n=t.batchNormalization(u,Rs(c),Rs(p),a,Rs(o),Rs(s));return e([l,c,p,o]),n},{$x:l,$mean:c,$variance:p,$scale:o,$offset:s},function(t,e){var n=e,r=n[0],i=n[1],o=n[2],s=n[3],l=null==s?an(1):s,c=Fr(i.shape,u.shape),p=[];if(1===i.rank){for(var h=0;h0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),qs=Ze({addN_:function(t){f(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),f(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Ve(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!y(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return kt.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),Ks=Ze({addStrict_:function(t,e){var n=Ve(t,"a","addStrict"),r=Ve(e,"b","addStrict");return d(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),$s=Ze({atan2_:function(t,e){var n,r=Ve(t,"a","atan2"),i=Ve(e,"b","atan2");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.atan2(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Hs(n.square(),r.square()),i=t.mul(r.div(e)),o=Fr(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var e=Hs(n.square(),r.square()),i=us(t.mul(n.div(e))),o=Fr(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Xs=Ze({div_:function(t,e){var n,r=Ve(t,"a","div"),i=Ve(e,"b","div");if(n=bt(r,i),r=n[0],i=n[1],"int32"===r.dtype&&"int32"===i.dtype)return Js(r,i);var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.realDivide(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),Ys=Ze({divStrict_:function(t,e){var n=Ve(t,"a","div"),r=Ve(e,"b","div");return d(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Js=Ze({floorDiv_:function(t,e){var n,r=Ve(t,"a","floorDiv"),i=Ve(e,"b","floorDiv");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.floorDiv(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),Zs=Ze({maximum_:function(t,e){var n,r=Ve(t,"a","maximum"),i=Ve(e,"b","maximum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.maximum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),Qs=Ze({maximumStrict_:function(t,e){var n=Ve(t,"a","maximumStrict"),r=Ve(e,"b","maximumStrict");return d(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),tu=Ze({minimum_:function(t,e){var n,r=Ve(t,"a","minimum"),i=Ve(e,"b","minimum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.minimum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),eu=Ze({minimumStrict_:function(t,e){var n=Ve(t,"a","minimumStrict"),r=Ve(e,"b","minimumStrict");return d(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),nu=Ze({mod_:function(t,e){var n,r=Ve(t,"a","mod"),i=Ve(e,"b","mod");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.mod(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Fr(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),ru=Ze({modStrict_:function(t,e){var n=Ve(t,"a","modStrict"),r=Ve(e,"b","modStrict");return d(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),iu=Ze({mul_:function(t,e){var n,r=Ve(t,"a","mul"),i=Ve(e,"b","mul");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.multiply(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),au=Ze({mulStrict_:function(t,e){var n=Ve(t,"a","mul"),r=Ve(e,"b","mul");return d(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),ou=Ze({pow_:function(t,e){var n=Ve(t,"base","pow"),r=Ve(e,"exp","pow"),i=Mr(n.shape,r.shape);return t=n.cast(vt(n.dtype,r.dtype)),e=r.cast(vt(n.dtype,r.dtype)),kt.runKernel(function(t,e){var i=t.pow(n,r);return e([n,r,i]),i},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(an(1))))),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),o=n.log().where(e,yn(n)),s=t.mul(a.mul(o)),u=Fr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),su=Ze({powStrict_:function(t,e){return d(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),uu=Ze({squaredDifference_:function(t,e){var n,r=Ve(t,"a","squaredDifference"),i=Ve(e,"b","squaredDifference");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.squaredDifference(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1],i=an(2);return{$a:function(){return t.mul(n.sub(r).mul(i))},$b:function(){return t.mul(r.sub(n).mul(i))}}})}}),lu=Ze({squaredDifferenceStrict_:function(t,e){var n=Ve(t,"a","squaredDifferenceStrict"),r=Ve(e,"b","squaredDifferenceStrict");return d(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),cu=Ze({sub_:function(t,e){var n,r=Ve(t,"a","sub"),i=Ve(e,"b","sub");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),pu=Ze({subStrict_:function(t,e){var n=Ve(t,"a","subStrict"),r=Ve(e,"b","subStrict");return d(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),hu=Ze({equal_:function(t,e){var n,r=Ve(t,"a","equal"),i=Ve(e,"b","equal");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.equal(r,i)},{$a:r,$b:i})}}),fu=Ze({equalStrict_:function(t,e){var n=Ve(t,"a","equalStrict"),r=Ve(e,"b","equalStrict");return d(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),du=Ze({greater_:function(t,e){var n,r=Ve(t,"a","greater"),i=Ve(e,"b","greater");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.greater(r,i)},{$a:r,$b:i})}}),mu=Ze({greaterEqual_:function(t,e){var n,r=Ve(t,"a","greaterEqual"),i=Ve(e,"b","greaterEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.greaterEqual(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return yn(n)},$b:function(){return yn(r)}}})}}),gu=Ze({greaterEqualStrict_:function(t,e){var n=Ve(t,"a","greaterEqualStrict"),r=Ve(e,"b","greaterEqualStrict");return d(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),vu=Ze({greaterStrict_:function(t,e){var n=Ve(t,"a","greaterStrict"),r=Ve(e,"b","greaterStrict");return d(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),yu=Ze({less_:function(t,e){var n,r=Ve(t,"a","less"),i=Ve(e,"b","less");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.less(r,i)},{$a:r,$b:i})}}),bu=Ze({lessEqual_:function(t,e){var n,r=Ve(t,"a","lessEqual"),i=Ve(e,"b","lessEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.lessEqual(r,i)},{$a:r,$b:i})}}),xu=Ze({lessEqualStrict_:function(t,e){var n=Ve(t,"a","lessEqualStrict"),r=Ve(e,"b","lessEqualStrict");return d(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),wu=Ze({lessStrict_:function(t,e){var n=Ve(t,"a","lessStrict"),r=Ve(e,"b","lessStrict");return d(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Nu=Ze({notEqual_:function(t,e){var n,r=Ve(t,"a","notEqual"),i=Ve(e,"b","notEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.notEqual(r,i)},{$a:r,$b:i})}}),Cu=Ze({notEqualStrict_:function(t,e){var n=Ve(t,"a","notEqualStrict"),r=Ve(e,"b","notEqualStrict");return d(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Eu(t,e){for(var n=[],r=t;r0,function(){return"mask cannot be scalar"}),d(u.slice(o,o+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=o;c=2&&o.rank>=2&&a.rank===o.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+o.rank+"."}),f(y(p,h),function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+a.shape+" and "+o.shape+" must match."}),f(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+o.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var g=a.shape.slice(0,-2).concat([l,c]),b=n?a.as3D(d,s,l):a.as3D(d,l,s),x=r?o.as3D(m,c,u):o.as3D(m,u,c);return kt.runKernel(function(t,e){var i=t.batchMatMul(b,x,n,r);return e([b,x]),i},{$a:b,$b:x},function(t,e){var i=e,a=i[0],o=i[1];return n||r?!n&&r?{$a:function(){return t.matMul(o,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return o.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return o.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(o,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(g)}}),ju=Ze({dot_:function(t,e){var n=Ve(t,"t1","dot"),r=Ve(e,"t2","dot");f(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var i=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return f(i===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+a+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Gu=Ze({outerProduct_:function(t,e){var n=Ve(t,"v1","outerProduct"),r=Ve(e,"v2","outerProduct");return f(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Hu=Ze({reverse_:function(t,e){var n=Ve(t,"x","reverse");if(0===n.rank)return n.clone();var r=S(e,n.shape);return kt.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),qu=Ze({reverse1d_:function(t){var e=Ve(t,"x","reverse");return f(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Hu(e,0)}}),Ku=Ze({reverse2d_:function(t,e){var n=Ve(t,"x","reverse");return f(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Hu(n,e)}}),$u=Ze({reverse3d_:function(t,e){var n=Ve(t,"x","reverse");return f(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Hu(n,e)}}),Xu=Ze({reverse4d_:function(t,e){var n=Ve(t,"x","reverse");return f(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Hu(n,e)}});function Yu(t,e,n,r,i,a){var o=Ve(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),null==r&&(r=[1,1]),f(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),f(qr(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&f(b(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=zr(s.shape,e,n,r,i,a),c=kt.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var o=a[0],s=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=Ve(t,"dy","maxPoolBackprop"),l=Ve(e,"input","maxPoolBackprop"),c=Ve(n,"output","maxPoolBackprop");f(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),f(qr(i,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),f(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),f(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."});var p=zr(l.shape,r,i,a,o,s);return kt.runKernel(function(t){return t.maxPoolBackprop(u,l,c,p)},{$dy:u,$input:l})}(t,o,s,e,n,r,i)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function Ju(t,e,n,r,i,a){var o=Ve(t,"x","avgPool","float32");null==r&&(r=[1,1]),f(qr(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&f(b(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=zr(s.shape,e,n,r,i,a),c=kt.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,a){var o=Ve(t,"dy","avgPoolBackprop"),s=Ve(e,"input","avgPoolBackprop");f(s.rank===o.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"}),null==i&&(i=[1,1]),f(qr(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,l=o,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),f(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=zr(u.shape,n,r,i,a),h=kt.runKernel(function(t){return t.avgPoolBackprop(l,u,p)},{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,i)}}});return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Zu=Ze({maxPool_:function(t,e,n,r,i){return Yu(t,e,n,1,r,i)}}),Qu=Ze({avgPool_:function(t,e,n,r,i){return Ju(t,e,n,1,r,i)}}),tl=Ze({pool_:function(t,e,n,r,i,a){null==i&&(i=[1,1]),null==a&&(a=1),0===r&&(r="valid");var o=Ve(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(qr(a,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"});var l,c=zr(s.shape,e,a,i,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],d=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),a=t.concat(r,i),o=e.map(function(t,e){return(t-a[e]%t)%t}),s=i.map(function(t,e){return t+o[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,o[e]]})]}([c.inHeight,c.inWidth],p,l),m=d[0],g=d[1],v=h?r:"valid",y=h?s:ir(s,p,m),b=("avg"===n?function(){return Ju(y,e,a,1,v)}:function(){return Yu(y,e,a,1,v)})(),x=h?b:Bn(b,p,g);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),el=Ze({maxPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=Ve(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),f(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),f("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),f(qr(n,o),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&f(b(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),p=kt.runKernel(function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n},{x:u},function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=Ve(t,"dy","maxPool3dBackprop"),l=Ve(e,"input","maxPool3dBackprop"),c=Ve(n,"output","maxPool3dBackprop"),p=u,h=l,d=c,m=!1;4===l.rank&&(m=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),f(5===p.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."}),f(5===h.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+h.rank+"."}),f(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==a&&(a=[1,1,1]),f(qr(i,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),null!=s&&f(b(o),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."});var g=Lr(h.shape,r,i,a,o,s),v=kt.runKernel(function(t){return t.maxPool3dBackprop(p,h,d,g)},{dy5D:p,input5D:h});return m?v.as4D(v.shape[1],v.shape[2],v.shape[3],v.shape[4]):v}(t,s,u,e,n,o,r,i)}}});return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),nl=Ze({avgPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=Ve(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),f(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),f("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),f(qr(n,o),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&f(b(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),p=kt.runKernel(function(t){return t.avgPool3d(u,c)},{x:u},function(t){return{x:function(){return function(t,e,n,r,i,a,o){var s=Ve(t,"dy","avgPool3dBackprop"),u=Ve(e,"input","avgPool3dBackprop"),l=s,c=u,p=!1;4===u.rank&&(p=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),f(5===l.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."}),f(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==i&&(i=[1,1,1]),f(qr(r,i),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"}),null!=o&&f(b(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."});var h=Lr(c.shape,n,r,i,a,o),d=kt.runKernel(function(t){return t.avgPool3dBackprop(l,c,h)},{dy5D:l,input5D:c});return p?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,o,r,i)}}});return p=p.cast(u.dtype),l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),rl=Ze({slice_:function(t,e,n){var r,i,a=Ve(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length=0?t:(f(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),a.shape[e]-r[e])}),function(t,e,n){f(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),f(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){f(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},i=0;i0&&(e=e.sum(a)),e.reshape(r.shape)}}})}}),Cl=Ze({relu_:function(t){var e=Ve(t,"x","relu");return"bool"===e.dtype?e.toInt():kt.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),El=Ze({selu_:function(t){var e=Ve(t,"x","selu");return kt.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(an(0)),r=an(wo),i=an(No),a=t.mul(i),o=t.mul(r).mul(n.toFloat().exp());return js(e,a,o)}}})}}),Sl=Ze({transpose_:function(t,e){var n=Ve(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),f(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){f(t>=0&&ti)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var a=kt.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}}),_l=Ze({scatterND_:function(t,e,n){var r=Ve(t,"indices","scatterND","int32"),i=Ve(e,"updates","scatterND");return function(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,i=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rankr){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(fn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=Qe(n,u).as2D(i,r),c=Fl(l),p=Math.floor(r/2)+1,h=tn(c),d=en(c),m=h.split([p,r-p],h.shape.length-1),g=d.split([p,r-p],d.shape.length-1),v=n.shape.slice();return v[n.shape.length-1]=p,Qe(m[0],g[0]).reshape(v)}}),Ll=Ze({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=Ml(r);return tn(i)}var a=[n,2*(e-1)],o=tn(t).as2D(n,e),s=en(t).as2D(n,e),u=o.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(an(-1)),c=o.concat(u,1),p=s.concat(l,1);return r=Qe(c,p).as2D(a[0],a[1]),i=Ml(r),tn(i)}}),Pl=Object.freeze({fft:Fl,ifft:Ml,rfft:zl,irfft:Ll}),Bl=Ze({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=Ve(t,"sparseIndices","sparseToDense","int32"),a=Ve(e,"sparseValues","sparseToDense"),o=Ve(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var i=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var o=e.size;if(0!==e.rank&&(1!==e.rank||o!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,a,n,o),kt.runKernel(function(t){return t.sparseToDense(i,a,n,o)},{$sparseIndices:i,$sparseValues:a,$defaultValue:o})}}),Vl=Ze({gatherND_:function(t,e){var n=Ve(e,"indices","gatherND","int32"),r=Ve(t,"x","gatherND");return kt.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}}),Wl=Ze({diag_:function(t){var e=Ve(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return kt.runKernel(function(t){return t.diag(e)},{$x:e}).reshape(n)}}),Ul=Ze({dropout_:function(t,e,n,r){var i=Ve(t,"x","dropout");if(f("float32"===i.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+i.dtype+" tensor instead."}),f(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof lt?i.clone():i;var a=function(t,e){if(null==e)return t.shape.slice();if(y(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank}),f(r.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank}),d(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=r.shape[r.shape.length-1],f(n>0&&n<=o,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n}),[4,r.data()];case 1:return s=i.sent(),[4,a.data()];case 2:for(u=i.sent(),l=[s.length/o,o],p=l[1],h=I("bool",c=l[0]),m=0;m1?u.div(an(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(an(i.size));var l=a.mul(hn(i.shape)).notEqual(an(0)).sum().toFloat();return o.sum().div(l)}throw Error("Unknown reduction: "+r)}}),Zl=Ze({cosineDistance_:function(e,n,r,i,a){void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","cosineDistance"),s=Ve(n,"predictions","cosineDistance"),u=null;null!=i&&(u=Ve(i,"weights","cosineDistance")),d(o.shape,s.shape,"Error in cosineDistance: ");var l=an(1).sub(o.mul(s).sum(r,!0));return Jl(l,u,a)}}),Ql=Ze({hingeLoss_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ve(e,"labels","hingeLoss"),o=Ve(n,"predictions","hingeLoss"),s=null;null!=r&&(s=Ve(r,"weights","hingeLoss")),d(a.shape,o.shape,"Error in hingeLoss: ");var u=an(1);a=an(2).mul(a).sub(u);var l=u.sub(a.mul(o)).relu();return Jl(l,s,i)}}),tc=Ze({huberLoss_:function(e,n,r,i,a){void 0===i&&(i=1),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","huberLoss"),s=Ve(n,"predictions","huberLoss"),u=null;null!=r&&(u=Ve(r,"weights","huberLoss")),d(o.shape,s.shape,"Error in huberLoss: ");var l=an(i),c=s.sub(o).abs(),p=tu(c,l),h=c.sub(p),f=an(.5).mul(p.square()).add(l.mul(h));return Jl(f,u,a)}}),ec=Ze({logLoss_:function(e,n,r,i,a){void 0===i&&(i=1e-7),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","logLoss"),s=Ve(n,"predictions","logLoss"),u=null;null!=r&&(u=Ve(r,"weights","logLoss")),d(o.shape,s.shape,"Error in logLoss: ");var l=an(1),c=an(i),p=o.mul(s.add(c).log()).neg().sub(l.sub(o).mul(l.sub(s).add(c).log()));return Jl(p,u,a)}}),nc=Ze({meanSquaredError_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ve(e,"labels","meanSquaredError"),o=Ve(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=Ve(r,"weights","meanSquaredError")),d(a.shape,o.shape,"Error in meanSquaredError: ");var u=a.squaredDifference(o);return Jl(u,s,i)}}),rc=Ze({sigmoidCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"multiClassLabels","sigmoidCrossEntropy"),s=Ve(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=Ve(r,"weights","sigmoidCrossEntropy")),d(o.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(.5);o=o.mul(c.sub(l)).add(p.mul(l))}var h=function(t,e){var n=Ve(t,"labels","sigmoidCrossEntropyWithLogits"),r=Ve(e,"logits","sigmoidCrossEntropyWithLogits");d(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),a=r.mul(n),o=r.abs().neg().exp().log1p();return i.sub(a).add(o)}(o,s);return Jl(h,u,a)}}),ic=Ze({softmaxCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"onehotLabels","softmaxCrossEntropy"),s=Ve(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=Ve(r,"weights","softmaxCrossEntropy")),d(o.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(o.shape[1]);o=o.mul(c.sub(l)).add(l.div(p))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Ir(function(t,e,r){var i=e.logSumExp([n],!0),a=e.toFloat().sub(i);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],i=e[1],a=He(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(i.exp())),t.reshape(a).mul(i.exp().sub(r.toFloat()))]}}})(t,e)}(o,s);return Jl(h,u,a)}}),ac=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:Yl,computeWeightedLoss:Jl,cosineDistance:Zl,hingeLoss:Ql,huberLoss:tc,logLoss:ec,meanSquaredError:nc,sigmoidCrossEntropy:rc,softmaxCrossEntropy:ic});function oc(t,e){return void 0===e&&(e=!1),kt.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],i=Hn(n),a=t.clone(),o=sn([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=i;e=kt.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=sn([[-1]]).where(l.greater(0),sn([[1]])),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?o.clone():o.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=a.slice([t,0],[n-t,r]),m=f.mul(s);if(0===t)a=d.sub(m.matMul(s.transpose().matMul(d)));else{var g=d.sub(m.matMul(s.transpose().matMul(d)));a=a.slice([0,0],[t,r]).concat(g,0)}var v=i.slice([0,t],[n,i.shape[1]-t]);if(0===t)i=v.sub(v.matMul(s).matMul(m.transpose()));else{var y=v.sub(v.matMul(s).matMul(m.transpose()));i=i.slice([0,0],[n,t]).concat(y,1)}return[s,a,i]}),s=e[0],a=e[1],i=e[2],Fe([u,l,c])},c=0;cr&&(i=i.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[i,a]})}var sc=Ze({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,f(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){f(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return oc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return lr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=oc(t,e),a=n[0],o=n[1];r.push(a),i.push(o)}),[or(r,0).reshape(t.shape),or(i,0).reshape(t.shape)]}}),lc=Object.freeze({gramSchmidt:sc,qr:uc});function cc(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),f(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),f(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),f(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),f(1===e.rank,function(){return"scores must be a 1D tensor"}),f(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var pc=Ze({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Ve(t,"images","resizeBilinear");f(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),f(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([i]),t.resizeBilinear(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),hc=Ze({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Ve(t,"images","resizeNearestNeighbor");f(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),f(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),f("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([i]),t.resizeNearestNeighbor(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),fc=Ze({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var a=Ve(t,"boxes","nonMaxSuppression"),o=Ve(e,"scores","nonMaxSuppression"),s=cc(a,o,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,kt.runKernel(function(t){return t.nonMaxSuppression(a,o,n,r,i)},{$boxes:a})}}),dc=Ze({cropAndResize_:function(t,e,n,r,i,a){var o=Ve(t,"image","cropAndResize","float32"),s=Ve(e,"boxes","cropAndResize","float32"),u=Ve(n,"boxInd","cropAndResize","int32");i=i||"bilinear",a=a||0;var l=s.shape[0];return f(4===o.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."}),f(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),f(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),f(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),f(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),f("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),kt.runKernel(function(t,e){return t.cropAndResize(o,s,u,r,i,a)},{$image:o,$boxes:s})}}),mc=Object.freeze({resizeBilinear:pc,resizeNearestNeighbor:hc,nonMaxSuppression:fc,nonMaxSuppressionAsync:function(t,e,n,a,o){return void 0===a&&(a=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return r=Ve(t,"boxes","nonMaxSuppressionAsync"),s=Ve(e,"scores","nonMaxSuppressionAsync"),u=cc(r,s,n,a,o),n=u.maxOutputSize,a=u.iouThreshold,o=u.scoreThreshold,[4,Promise.all([r.data(),s.data()])];case 1:return l=i.sent(),c=l[0],p=l[1],h=ni(c,p,n,a,o),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,h]}})})},cropAndResize:dc}),gc=Ze({matMul_:function(t){var e,n=t.a,r=t.b,i=t.transposeA,a=void 0!==i&&i,o=t.transposeB,s=void 0!==o&&o,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights,h=Ve(n,"a","fused matMul"),d=Ve(r,"b","fused matMul");e=bt(h,d),h=e[0],d=e[1];var m=a?h.shape[h.rank-2]:h.shape[h.rank-1],g=s?d.shape[d.rank-1]:d.shape[d.rank-2],b=a?h.shape[h.rank-1]:h.shape[h.rank-2],x=s?d.shape[d.rank-2]:d.shape[d.rank-1],w=h.shape.slice(0,-2),N=d.shape.slice(0,-2),C=v(w),E=v(N);f(h.rank>=2&&d.rank>=2&&h.rank===d.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+h.rank+" and "+d.rank+"."}),f(y(w,N),function(){return"Error in fused matMul: outer dimensions ("+w+") and ("+N+") of Tensors with shapes "+h.shape+" and "+d.shape+" must match."}),f(m===g,function(){return"Error in fused matMul: inner shapes ("+m+") and ("+g+") of Tensors with shapes "+h.shape+" and "+d.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var S,k,I=h.shape.slice(0,-2).concat([b,x]),A=a?h.as3D(C,m,b):h.as3D(C,b,m),R=s?d.as3D(E,x,g):d.as3D(E,g,x);null!=u&&Mr(I,(S=bt(S=Ve(u,"bias","fused matMul"),h)[0]).shape),null!=p&&(k=Ve(p,"prelu weights","fused matMul"));var T={$a:A,$b:R};return null!=u&&(T.$bias=S),null!=p&&(T.$preluActivationWeights=k),kt.runKernel(function(t,e){var n=t.fusedBatchMatMul({a:A,b:R,transposeA:a,transposeB:s,bias:S,activation:c,preluActivationWeights:k});return e([A,R,n]),n},T,function(t,e){var n,r=e[0],i=e[1],o=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(o.step())}var l={};return null!=u&&(l={$bias:function(){var t=n,e=Fr(S.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(S.shape)}}),a||s?!a&&s?Object.assign({$a:function(){return n.matMul(i,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}},l):a&&!s?Object.assign({$a:function(){return i.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}},l):Object.assign({$a:function(){return i.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}},l):Object.assign({$a:function(){return n.matMul(i,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}},l)}).reshape(I)}}),vc=Ze({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,i=t.pad,a=t.dataFormat,o=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,d=t.preluActivationWeights,m=Ve(e,"x","conv2d"),g=Ve(n,"filter","conv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),f(4===v.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."}),f(4===g.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."}),null!=l&&f(b(i),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+i+"."}),f(v.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+g.shape[2]+"."}),f(qr(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),f("NHWC"===o,function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported."});var x,w,N=Pr(v.shape,g.shape,r,u,i,l);null!=c&&(x=bt(x=Ve(c,"bias","fused conv2d"),m)[0],Mr(N.outShape,x.shape)),null!=d&&(w=Ve(d,"prelu weights","fused conv2d"));var C={x:v,$filter:g};null!=c&&(C.$bias=x),null!=d&&(C.$preluActivationWeights=w);var E=kt.runKernel(function(t,e){var n=t.fusedConv2d(v,g,N,x,h,w);return e([g,v,n]),n},C,function(t,e){var n,a=e,o=a[0],s=a[1],l=a[2];if(null==h||"linear"===h)n=t;else{if("relu"!==h)throw new Error("Gradient for activation "+h+" has not been implemented yet.");n=t.mul(l.step())}f(Hr(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var p={};return null!=c&&(p={$bias:function(){var t=n,e=Fr(x.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(x.shape)}}),Object.assign({x:function(){return Lu(s.shape,n,o,r,i)},$filter:function(){return zu(s,n,o.shape,r,i)}},p)});return y?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),yc=Object.freeze({matMul:gc,conv2d:vc}),bc=Object.freeze({image:mc,linalg:lc,losses:ac,spectral:Pl,fused:yc,signal:$l,op:Ze,batchNormalization2d:Ds,batchNormalization3d:Os,batchNormalization4d:_s,batchNormalization:Fs,batchNorm:Ms,batchNorm2d:zs,batchNorm3d:Ls,batchNorm4d:Ps,booleanMaskAsync:Au,complex:Qe,real:tn,imag:en,concat:bn,concat1d:xn,concat2d:wn,concat3d:Nn,concat4d:Cn,split:En,conv1d:_u,conv2d:Fu,conv3d:Mu,conv2dDerFilter:zu,conv2dDerInput:Lu,depthwiseConv2d:Pu,separableConv2d:Bu,conv2dTranspose:Vu,conv3dTranspose:Wu,matMul:Uu,dot:ju,outerProduct:Gu,reverse:Hu,reverse1d:qu,reverse2d:Ku,reverse3d:$u,reverse4d:Xu,maxPool:Zu,avgPool:Qu,pool:tl,maxPool3d:el,avgPool3d:nl,slice:rl,slice1d:il,slice2d:al,slice3d:ol,slice4d:sl,abs:Go,acos:Ho,acosh:qo,asin:Ko,asinh:$o,atan:Xo,atanh:Yo,ceil:Jo,clipByValue:Zo,cos:Qo,cosh:ts,erf:es,exp:ns,expm1:rs,floor:is,log:as,log1p:os,logSigmoid:ss,neg:us,reciprocal:ls,round:cs,rsqrt:ps,sigmoid:hs,sign:fs,isNaN:ds,isInf:ms,isFinite:gs,sin:vs,sinh:ys,softplus:bs,sqrt:xs,square:ws,step:Ns,tan:Cs,tanh:Es,all:ll,any:cl,argMax:pl,argMin:hl,logSumExp:fl,max:dl,mean:ml,min:gl,moments:vl,sum:yl,prod:bl,equal:hu,equalStrict:fu,greater:du,greaterEqual:mu,greaterEqualStrict:gu,greaterStrict:vu,less:yu,lessEqual:bu,lessEqualStrict:xu,lessStrict:wu,notEqual:Nu,notEqualStrict:Cu,add:Hs,addN:qs,addStrict:Ks,atan2:$s,div:Xs,divStrict:Ys,floorDiv:Js,maximum:Zs,maximumStrict:Qs,minimum:tu,minimumStrict:eu,mod:nu,modStrict:ru,mul:iu,mulStrict:au,pow:ou,powStrict:su,squaredDifference:uu,squaredDifferenceStrict:lu,sub:cu,subStrict:pu,elu:xl,leakyRelu:wl,prelu:Nl,relu:Cl,selu:El,logicalAnd:Bs,logicalNot:Vs,logicalOr:Ws,logicalXor:Us,where:js,whereAsync:Gs,buffer:Ln,print:Pn,batchToSpaceND:Bn,cast:Vn,clone:Wn,cumsum:Un,depthToSpace:jn,expandDims:Gn,eye:Hn,multinomial:qn,oneHot:Kn,pad:$n,pad1d:Xn,pad2d:Yn,pad3d:Jn,pad4d:Zn,rand:Qn,randomNormal:tr,randomGamma:er,randomUniform:nr,reshape:rr,spaceToBatchND:ir,squeeze:ar,stack:or,tile:sr,truncatedNormal:ur,unstack:lr,setdiff1dAsync:cr,fill:dn,linspace:mn,ones:hn,range:gn,scalar:an,tensor:nn,tensor1d:on,tensor2d:sn,tensor3d:un,tensor4d:ln,tensor5d:cn,tensor6d:pn,zeros:fn,onesLike:vn,zerosLike:yn,transpose:Sl,softmax:Rr,logSoftmax:Tr,localResponseNormalization:kl,norm:Il,gather:ku,unsortedSegmentSum:Iu,basicLSTMCell:Al,multiRNNCell:Rl,movingAverage:Tl,stridedSlice:Dl,topk:Ol,scatterND:_l,fft:Fl,ifft:Ml,rfft:zl,irfft:Ll,sparseToDense:Bl,gatherND:Vl,diag:Wl,dropout:Ul,hannWindow:Gl,hammingWindow:Hl,frame:ql,stft:Kl,inTopKAsync:Xl});function xc(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var wc=function(){function e(){if(this.blockSize=48,this.firstUse=!0,t.ENV.get("IS_BROWSER")){var e="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==e&&(this.fromPixels2DContext=e.getContext("2d"))}this.data=new Dr(this,kt)}return e.prototype.register=function(e,n,r){if(this.firstUse&&(this.firstUse=!1,t.ENV.get("IS_NODE")&&Le("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:r})},e.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},e.prototype.fromPixels=function(e,n){if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var r,i,a=e.data instanceof Uint8Array,o="undefined"!=typeof ImageData&&e instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,l=s?[e.videoWidth,e.videoHeight]:[e.width,e.height],c=l[0],p=l[1];if(t.ENV.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)r=e.getContext("2d").getImageData(0,0,c,p).data;else if(o||a)r=e.data;else{if(!u&&!s)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=c,this.fromPixels2DContext.canvas.height=p,this.fromPixels2DContext.drawImage(e,0,0,c,p),r=this.fromPixels2DContext.getImageData(0,0,c,p).data}if(4===n)i=new Int32Array(r);else{var h=c*p;i=new Int32Array(h*n);for(var f=0;fh&&(h=m,f=d)}u[c]=f}return o},e.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var i=vt(t.dtype,"int32"),a=fn(t.shape,i),o=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?1:0})},e.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},e.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],c=0;c=0&&e>=0?n:(n+e)%e})},e.prototype.max=function(t,e){this.assertNotComplex(t,"max"),qe("max",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=v(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;lp&&(p=f)}s[l]=p}return a},e.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},e.prototype.all=function(t,e){this.assertNotComplex(t,"all"),qe("all",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=v(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l0?n[r]=1:n[r]=0;return lt.make(t.shape,{values:n})},e.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return lt.make(t.shape,{values:n})},e.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?i:Math.exp(i)-1}return lt.make(t.shape,{values:e})},e.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=this.readSync(t.dataId),a=0;a=1?i[a]:i[a]*(o+1)}return lt.make(e.shape,{values:n})},e.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r=0?1.0507009873554805*i:1.7580993408473768*(Math.exp(i)-1)}return lt.make(t.shape,{values:e})},e.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=this.readSync(t.dataId),a=0;an?n:o-e,s=r[i]0?1:e}return lt.make(t.shape,{values:n})},e.prototype.fusedConv2d=function(t,e,n,r,i,a){var o=this.conv2d(t,e,n);return r&&(o=this.add(o,r)),i&&(o=xc(this,o,i,a)),o},e.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Ln(n.outShape,t.dtype),p=t.strides[0],h=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],m=c.strides[0],g=l?c.strides[1]:c.strides[2],v=l?c.strides[2]:1,y=l?1:c.strides[1],b=this.readSync(t.dataId),x=this.readSync(e.dataId),w=c.values,N=0;N=n.inHeight))for(var T=A*e.strides[0],D=C+R*h,O=0;O=n.inWidth))for(var L=D+z*f,P=T+M*e.strides[1],B=0;B=n.inDepth))for(var E=N*e.strides[0],S=v+C*t.strides[1],k=0;k=n.inHeight))for(var D=E+R*e.strides[1],O=S+T*t.strides[2],_=0;_=n.inWidth))for(var P=D+z*e.strides[2],B=O+L*n.inChannels,V=P,W=0;W=n.inHeight))for(var N=x*e.strides[0],C=m+w*t.strides[1],E=0;E=n.inWidth))for(var R=N+I*e.strides[1],T=C+A*n.inChannels,D=S,O=R,_=0;_D?D=L:"avg"===n&&(O+=L,_++)}if(isNaN(D))break}d[k+I*v+w]="avg"===n?O/_:D}return f.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=Ln(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p=this.bufferSync(t),h=0;hN&&(N=A,C=S*u+I)}n.set(C,h,d,y,f)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),a=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=c-1-r.padInfo.left,h=l-1-r.padInfo.top,f=Ln(e.shape,"float32"),d=this.bufferSync(i),m=this.bufferSync(t),g=0;g=r.outHeight||Math.floor(E)!==E))for(var S=0;S=r.outWidth||Math.floor(k)!==k)){var I=l*c-1-d.get(g,E,k,v)===C*c+S?1:0;0!==I&&(N+=m.get(g,E,k,v)*I)}}}f.set(N,g,y,b,v)}return f.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Ln(e.shape,"float32"),d=1/(a*o),m=this.bufferSync(t),g=0;g=n.outHeight||Math.floor(E)!==E))for(var S=0;S=n.outWidth||Math.floor(k)!==k||(N+=m.get(g,E,k,v))}}f.set(N*d,g,y,b,v)}return f.toTensor()},e.prototype.pool3d=function(t,e,n){this.assertNotComplex(t,"pool3d");for(var r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),v=Ln(e.outShape,t.dtype),y=v.values,b=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],x=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],N=e.outShape[4],C=0;CU?U=Y:"avg"===n&&(j+=Y,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[W+k]="avg"===n?j/G:U}}}return v.toTensor()},e.prototype.avgPool3d=function(t,e){return this.assertNotComplex(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=h-1-n.padInfo.front,g=d-1-n.padInfo.left,v=f-1-n.padInfo.top,y=Ln(e.shape,"float32"),b=1/(o*s*u),x=this.bufferSync(t),w=0;w=n.outDepth||Math.floor(D)!==D))for(var O=0;O=n.outHeight||Math.floor(_)!==_))for(var F=0;F=n.outWidth||Math.floor(M)!==M||(R+=x.get(w,D,_,M,N))}}}y.set(R*b,w,C,E,S,N)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return this.assertNotComplex(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Ln(e.outShape,"int32"),r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m=this.bufferSync(t),g=0;g=T&&(T=P,D=_*c*p+M*c+L)}n.set(D,g,y,N,k,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(e,r),a=r.strideDepth,o=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=p-1-r.padInfo.front,m=f-1-r.padInfo.left,g=h-1-r.padInfo.top,v=Ln(e.shape,"float32"),y=this.bufferSync(i),b=this.bufferSync(t),x=0;x=r.outDepth||Math.floor(T)!==T))for(var D=0;D=r.outHeight||Math.floor(O)!==O))for(var _=0;_=r.outWidth||Math.floor(F)!==F)){var M=p*h*f-1-y.get(x,T,O,F,w)===R*h*f+D*f+_?1:0;0!==M&&(A+=b.get(x,T,O,F,w)*M)}}}}v.set(A,x,N,C,E,w)}return v.toTensor()},e.prototype.cast=function(t,e){return $r(t,e,this)},e.prototype.reshape=function(t,e){return Xr(t,e)},e.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var i=t.shape,a=i[0],o=i[1],s=i[2],u=i[3],l=this.readSync(t.dataId),c=new Float32Array(v([a,e,n,u])),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g1?a-1:a,n&&c>1?o-1:o],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=this.readSync(t.dataId),v=0,y=0;y1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g1?a-1:a,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w=l)){var M=N+F*t.strides[1],z=F*m;if(C===Math.min(a-1,n?Math.round(z):Math.floor(z)))for(var L=0;L=c)){var B=M+P*t.strides[2],V=P*g;I===Math.min(o-1,n?Math.round(V):Math.floor(V))&&(O+=h[B+D])}}}}p[A+D]=O}return ln(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,i,a){this.assertNotComplex([t,e,n,i,a],"batchNorm");for(var o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=i?this.readSync(i.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),p=new Float32Array(o.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x=h&&(g=0),v>=m&&(v=0),y>=f&&(y=0),b>=d&&(b=0);return ln(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],o=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,o),u=0;r<=i;r++){var l=s[r];u+=l*l}return u}for(var p=0;p=0&&a[o]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],a=t.shape[2],o=t.shape[3],s=i*e,u=a*e,l=o/(e*e),c=this.readSync(t.dataId),p=new Float32Array(r*s*u*l),h=0,d=0;d=s))for(var I=h>1?(E-N)*(u-1)/(h-1):0,A=f>1?(S-C)*(l-1)/(f-1):0,R=0;R1?N*(u-1)+R*I:.5*(N+E)*(u-1);if(T<0||T>u-1)for(var D=0;D1?C*(l-1)+D*A:.5*(C+S)*(l-1))<0||H>l-1)for(O=0;O1?C*(l-1)+D*A:.5*(C+S)*(l-1))<0||H>l-1)for(O=0;O=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var v=0;v=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b0,function(){return"scheme must not be an empty string."});var r=t.getInstance();f(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function zc(t){if(-1===t.indexOf(Fc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Mc.getSchemes().join(","));return{scheme:t.split(Fc)[0],path:t.split(Fc)[1]}}function Lc(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return f(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),f((r=_c.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),f(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),a=r[0],f((o=_c.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),f(o.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=o[0],u=zc(t).scheme,l=zc(t).path,c=u===zc(t).scheme,[4,a.load()];case 1:return p=i.sent(),n&&c?[4,Mc.getManager(u).removeModel(l)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[4,s.save(p)];case 4:return h=i.sent(),!n||c?[3,6]:[4,Mc.getManager(u).removeModel(l)];case 5:i.sent(),i.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var Pc="models_store",Bc="model_info_store";function Vc(){if(!t.ENV.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window,n=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==n)throw new Error("The current browser does not appear to support IndexedDB.");return n}function Wc(t){var e=t.result;e.createObjectStore(Pc,{keyPath:"modelPath"}),e.createObjectStore(Bc,{keyPath:"modelPath"})}var Uc=function(){function t(t){if(this.indexedDB=Vc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return i(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)]})})},t.prototype.load=function(){return r(this,void 0,void 0,function(){return i(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Wc(i)},i.onsuccess=function(){var a=i.result;if(null==e){var o=a.transaction(Pc,"readonly"),s=o.objectStore(Pc).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},o.oncomplete=function(){return a.close()}}else{var u,l=Oc(e),c=a.transaction(Bc,"readwrite"),p=c.objectStore(Bc),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var i=(u=a.transaction(Pc,"readwrite")).objectStore(Pc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});i.onsuccess=function(){return t({modelArtifactsInfo:l})},i.onerror=function(t){var e=(p=c.objectStore(Bc)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(i.error)},e.onerror=function(t){return a.close(),r(i.error)}}},h.onerror=function(t){return a.close(),r(h.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),jc=function(e){return t.ENV.getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Uc.URL_SCHEME)?(n=e.slice(Uc.URL_SCHEME.length),new Uc(n)):null;var n};_c.registerSaveRouter(jc),_c.registerLoadRouter(jc);var Gc=function(){function t(){this.indexedDB=Vc()}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return i(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Wc(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(Bc,"readonly"),a=i.objectStore(Bc).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){f(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),f(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),f(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(a){return a.then(function(a){var o=n+ ++i/t.length*(r-n);return e(o),a}),a}))}function cp(e,n){return r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return null==n&&(n={}),r=null==n.fetchFunc?t.ENV.platform.fetch:n.fetchFunc,a=e.map(function(t){return r(t,n.requestInit,{isBinary:!0})}),o=0,s=.5,null!=n.onProgress?[3,2]:[4,Promise.all(a)];case 1:return u=i.sent(),[3,4];case 2:return[4,lp(a,n.onProgress,o,s)];case 3:u=i.sent(),i.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer()}),c=.5,p=1,null!=n.onProgress?[3,6]:[4,Promise.all(l)];case 5:return h=i.sent(),[3,8];case 6:return[4,lp(l,n.onProgress,c,p)];case 7:h=i.sent(),i.label=8;case 8:return[2,h]}})})}function pp(t){var e=this;return function(n,a,o){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,p,h,f,d;return i(this,function(i){switch(i.label){case 0:if(e=n.map(function(){return!1}),r={},s=null!=o?o.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var i=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Sc[a]*v(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:i,sizeBytes:l})};null!=o?o.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),i+=l})}),!s.every(function(t){return t}))throw l=o.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),p=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=i.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,i=0,a=0;a0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(e)&&f(2===e.length,function(){return"URL paths for http must have a length of 2, (actual length is "+e.length+")."}),this.path=e,null!=n.requestInit&&null!=n.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=n.requestInit||{}}return e.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a;return i(this,function(i){switch(i.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}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&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((a=i.sent()).ok)return[2,{modelArtifactsInfo:Oc(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,o,s,u;return i(this,function(i){switch(i.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=i.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.");i.label=2;case 2:return i.trys.push([2,4,,5]),[4,t.json()];case 3:return e=i.sent(),[3,5];case 4:throw i.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(r=e.modelTopology,a=e.weightsManifest,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=i.sent(),o=u[0],s=u[1],i.label=7;case 7:return[2,{modelTopology:r,weightSpecs:o,weightData:s}]}})})},e.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],o=this.weightPathPrefix||r,s=[],u=0,l=t;u0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),f(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),f(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),f(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),f(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=Kn(r.asType("int32"),n),o=Kn(i.asType("int32"),n);return a.transpose().matMul(o).asType("int32")}}),xp=Object.freeze({confusionMatrix:bp}),wp=Ze({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");var n="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement;if(n&&n&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the