= "+n);for(var a=0,o=0;o= "+a);for(var o=getPackedMatrixTextureShapeWidthHeight(t,r),i=o[0],s=o[1],u=r%2==1,l=t%2==1,c=Math.floor(r/2),p=Math.floor(t/2),d=u?4:0,h=r,f=0,m=0;m= "+a);for(var o=r%2==1,i=t%2==1,s=Math.floor(r/2),u=Math.floor(t/2),l=getPackedMatrixTextureShapeWidthHeight(t,r),c=l[0],p=l[1],d=o?4:0,h=r+(o?1:0),f=0,m=0,g=r,y=0;yn||r>n)throw a="["+t+"x"+r+"]",new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function createFramebuffer(e){return throwIfNull(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(e,t,r,n,a,o,i){var s=e.getAttribLocation(t,r);return-1!==s&&(callAndCheck(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),callAndCheck(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,o,i)}),callAndCheck(e,function(){return e.enableVertexAttribArray(s)}),!0)}function bindTextureUnit(e,t,r){validateTextureUnit(e,r),callAndCheck(e,function(){return e.activeTexture(e.TEXTURE0+r)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function unbindTextureUnit(e,t){validateTextureUnit(e,t),callAndCheck(e,function(){return e.activeTexture(e.TEXTURE0+t)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function getProgramUniformLocationOrThrow(e,t,r){return throwIfNull(e,function(){return e.getUniformLocation(t,r)},'uniform "'+r+'" not present in program.')}function getProgramUniformLocation(e,t,r){return e.getUniformLocation(t,r)}function bindTextureToProgramUniformSampler(e,t,r,n,a){callAndCheck(e,function(){return bindTextureUnit(e,r,a)}),callAndCheck(e,function(){return e.uniform1i(n,a)})}function bindCanvasToFramebuffer(e){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),callAndCheck(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),callAndCheck(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})}function bindColorTextureToFramebuffer(e,t,r){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)}),callAndCheck(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function unbindColorTextureFromFramebuffer(e,t){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),callAndCheck(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function validateFramebuffer(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+getFramebufferErrorMessage(e,t))}function getFramebufferErrorMessage(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function throwIfNull(e,t,r){var n=callAndCheck(e,function(){return t()});if(null==n)throw new Error(r);return n}function validateTextureUnit(e,t){var r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(nr)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+r+"].")}function getTextureShapeFromLogicalShape(e,t){2!==t.length&&(t=squeezeShape(t).newShape);var r=queryMaxTextureSize(e),n=sizeFromShape(t);return t.length<=1&&n<=r?[n,1]:2===t.length&&t[0]<=r&&t[1]<=r?t:3===t.length&&t[0]<=r&&t[1]*t[2]<=r?[t[0],t[1]*t[2]]:4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r?[t[0],t[1]*t[2]*t[3]]:sizeToSquarishShape(n)}var webgl_util=Object.freeze({createWebGLRenderingContext:createWebGLRenderingContext,createWebGLRenderingContextFromCanvas:createWebGLRenderingContextFromCanvas,callAndCheck:callAndCheck,enableDebugWebGLErrorChecking:enableDebugWebGLErrorChecking,checkWebGLError:checkWebGLError,getWebGLErrorMessage:getWebGLErrorMessage,getExtensionOrThrow:getExtensionOrThrow,createVertexShader:createVertexShader,createFragmentShader:createFragmentShader,createProgram:createProgram,linkProgram:linkProgram,validateProgram:validateProgram,createStaticVertexBuffer:createStaticVertexBuffer,createStaticIndexBuffer:createStaticIndexBuffer,queryMaxTextureSize:queryMaxTextureSize,getNumChannels:getNumChannels,createTexture:createTexture,validateTextureSize:validateTextureSize,createFramebuffer:createFramebuffer,bindVertexBufferToProgramAttribute:bindVertexBufferToProgramAttribute,bindTextureUnit:bindTextureUnit,unbindTextureUnit:unbindTextureUnit,getProgramUniformLocationOrThrow:getProgramUniformLocationOrThrow,getProgramUniformLocation:getProgramUniformLocation,bindTextureToProgramUniformSampler:bindTextureToProgramUniformSampler,bindCanvasToFramebuffer:bindCanvasToFramebuffer,bindColorTextureToFramebuffer:bindColorTextureToFramebuffer,unbindColorTextureFromFramebuffer:unbindColorTextureFromFramebuffer,validateFramebuffer:validateFramebuffer,getFramebufferErrorMessage:getFramebufferErrorMessage,getTextureShapeFromLogicalShape:getTextureShapeFromLogicalShape});function getWebGLContextAttributes(){return{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0}}function createWebGLContext(e){var t,r=getWebGLContextAttributes();return callAndCheck(t=null!=e?createWebGLRenderingContextFromCanvas(e,r):createWebGLRenderingContext(r),function(){return t.disable(t.DEPTH_TEST)}),callAndCheck(t,function(){return t.disable(t.STENCIL_TEST)}),callAndCheck(t,function(){return t.disable(t.BLEND)}),callAndCheck(t,function(){return t.disable(t.DITHER)}),callAndCheck(t,function(){return t.disable(t.POLYGON_OFFSET_FILL)}),callAndCheck(t,function(){return t.disable(t.SAMPLE_COVERAGE)}),callAndCheck(t,function(){return t.enable(t.SCISSOR_TEST)}),callAndCheck(t,function(){return t.enable(t.CULL_FACE)}),callAndCheck(t,function(){return t.cullFace(t.BACK)}),t}function createVertexShader$1(e){return createVertexShader(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function createVertexBuffer(e){return createStaticVertexBuffer(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function createIndexBuffer(e){return createStaticIndexBuffer(e,new Uint16Array([0,1,2,2,1,3]))}function getTextureConfig(e,t){var r,n,a,o,i,s,u,l=e;return 2===ENV.get("WEBGL_VERSION")?(r=l.R32F,n=l.R16F,a=l.RGBA32F,o=l.RED,i=4,s=1,u=l.HALF_FLOAT):(r=e.RGBA,n=e.RGBA,a=l.RGBA,o=e.RGBA,i=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:r,internalFormatHalfFloat:n,internalFormatPackedFloat:a,textureFormatFloat:o,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:i,defaultNumChannels:s,textureTypeHalfFloat:u}}function createAndConfigureTexture(e,t,r,n,a,o){validateTextureSize(e,t,r);var i=createTexture(e),s=e.TEXTURE_2D;return callAndCheck(e,function(){return e.bindTexture(s,i)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),callAndCheck(e,function(){return e.texImage2D(s,0,n,t,r,0,a,o,null)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),i}function createFloat32MatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatFloat,n.textureFormatFloat,e.FLOAT)}function createFloat16MatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatFloat,n.textureFormatFloat,n.textureTypeHalfFloat)}function createUnsignedBytesMatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function createPackedMatrixTexture(e,t,r,n){var a=getPackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function bindVertexProgramAttributeStreams(e,t,r){return callAndCheck(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),bindVertexBufferToProgramAttribute(e,t,"clipSpacePos",r,3,20,0)&&bindVertexBufferToProgramAttribute(e,t,"uv",r,2,20,12)}function uploadPixelDataToTexture(e,t,r){callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),callAndCheck(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function uploadDataToTexture(e,t,r,n,a,o){validateTextureSize(e,r,n),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),callAndCheck(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,o,e.FLOAT,a)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function uploadMatrixToTexture(e,t,r,n,a,o,i){var s,u=getUnpackedMatrixTextureShapeWidthHeight(r,n),l=u[0],c=u[1];1===i.defaultNumChannels?s=a:encodeMatrixToUnpackedArray(a,s=new Float32Array(getUnpackedArraySizeFromMatrixSize(a.length,o)),o),uploadDataToTexture(e,t,l,c,s,i.textureFormatFloat)}function uploadMatrixToPackedTexture(e,t,r,n,a,o){var i=getPackedMatrixTextureShapeWidthHeight(r,n),s=i[0],u=i[1],l=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(r,n));encodeMatrixToPackedRGBA(a,r,n,l),uploadDataToTexture(e,t,s,u,l,e.RGBA)}function downloadMatrixFromOutputTextureAsync(e,t,r,n,a){return __awaiter(this,void 0,void 0,function(){var o,i,s,u,l;return __generator(this,function(c){switch(c.label){case 0:return o=e,i=new Float32Array(getUnpackedArraySizeFromMatrixSize(r*n,a.downloadUnpackNumChannels)),s=i instanceof Float32Array?4*i.length:i,u=e.createBuffer(),callAndCheck(e,function(){return e.bindBuffer(o.PIXEL_PACK_BUFFER,u)}),callAndCheck(e,function(){return e.bufferData(o.PIXEL_PACK_BUFFER,s,e.STATIC_DRAW)}),callAndCheck(e,function(){return o.readPixels(0,0,n,r,e.RGBA,e.FLOAT,0)}),[4,t.getBufferSubDataAsync(o.PIXEL_PACK_BUFFER,0,i)];case 1:return c.sent(),l=new Float32Array(r*n),decodeMatrixFromUnpackedArray(i,l,a.downloadUnpackNumChannels),[2,l]}})})}function downloadFloat32MatrixFromOutputTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r),o=a[0],i=a[1],s=new Float32Array(getUnpackedArraySizeFromMatrixSize(t*r,n.downloadUnpackNumChannels));callAndCheck(e,function(){return e.readPixels(0,0,o,i,n.downloadTextureFormat,e.FLOAT,s)});var u=new Float32Array(t*r);return decodeMatrixFromUnpackedArray(s,u,n.downloadUnpackNumChannels),u}function downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r),o=a[0],i=a[1],s=new Uint8Array(getUnpackedArraySizeFromMatrixSize(t*r,4));return callAndCheck(e,function(){return e.readPixels(0,0,o,i,n.downloadTextureFormat,e.UNSIGNED_BYTE,s)}),new Float32Array(s.buffer)}function downloadMatrixFromPackedOutputTexture(e,t,r,n){var a=getPackedMatrixTextureShapeWidthHeight(t,r),o=a[0],i=a[1],s=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(t,r));callAndCheck(e,function(){return e.readPixels(0,0,o,i,e.RGBA,e.FLOAT,s)});var u=new Float32Array(t*r);return decodeMatrixFromPackedRGBA(s,t,r,u)}var gpgpu_util=Object.freeze({getWebGLContextAttributes:getWebGLContextAttributes,createWebGLContext:createWebGLContext,createVertexShader:createVertexShader$1,createVertexBuffer:createVertexBuffer,createIndexBuffer:createIndexBuffer,getTextureConfig:getTextureConfig,createFloat32MatrixTexture:createFloat32MatrixTexture,createFloat16MatrixTexture:createFloat16MatrixTexture,createUnsignedBytesMatrixTexture:createUnsignedBytesMatrixTexture,createPackedMatrixTexture:createPackedMatrixTexture,bindVertexProgramAttributeStreams:bindVertexProgramAttributeStreams,uploadPixelDataToTexture:uploadPixelDataToTexture,uploadMatrixToTexture:uploadMatrixToTexture,uploadMatrixToPackedTexture:uploadMatrixToPackedTexture,downloadMatrixFromOutputTextureAsync:downloadMatrixFromOutputTextureAsync,downloadFloat32MatrixFromOutputTexture:downloadFloat32MatrixFromOutputTexture,downloadByteEncodedFloatMatrixFromOutputTexture:downloadByteEncodedFloatMatrixFromOutputTexture,downloadMatrixFromPackedOutputTexture:downloadMatrixFromPackedOutputTexture}),GPGPUContext=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.autoDebugValidate=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[],this.gl=null!=e?e:createWebGLContext(),1===ENV.get("WEBGL_VERSION")?(this.textureFloatExtension=getExtensionOrThrow(this.gl,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=getExtensionOrThrow(this.gl,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=getExtensionOrThrow(this.gl,"EXT_color_buffer_float"),this.loseContextExtension=getExtensionOrThrow(this.gl,"WEBGL_lose_context"),ENV.get("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED")&&(this.getBufferSubDataAsyncExtension=this.gl.getExtension("WEBGL_get_buffer_sub_data_async")),this.vertexBuffer=createVertexBuffer(this.gl),this.indexBuffer=createIndexBuffer(this.gl),this.framebuffer=createFramebuffer(this.gl),this.textureConfig=getTextureConfig(this.gl,this.textureHalfFloatExtension)}return e.prototype.dispose=function(){var e=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 t=this.gl;callAndCheck(t,function(){return t.finish()}),callAndCheck(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),callAndCheck(t,function(){return t.deleteFramebuffer(e.framebuffer)}),callAndCheck(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,null)}),callAndCheck(t,function(){return t.deleteBuffer(e.vertexBuffer)}),callAndCheck(t,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)}),callAndCheck(t,function(){return t.deleteBuffer(e.indexBuffer)}),this.loseContextExtension.loseContext(),this.disposed=!0}},e.prototype.enableAutomaticDebugValidation=function(e){this.autoDebugValidate=e,enableDebugWebGLErrorChecking(e)},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),createFloat32MatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),createFloat16MatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),createUnsignedBytesMatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),uploadPixelDataToTexture(this.gl,e,t)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),createPackedMatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(unbindColorTextureFromFramebuffer(this.gl,this.framebuffer),this.outputTexture=null),callAndCheck(this.gl,function(){return t.gl.deleteTexture(e)})},e.prototype.uploadMatrixToTexture=function(e,t,r,n){this.throwIfDisposed();var a=getNumChannels();return uploadMatrixToTexture(this.gl,e,t,r,n,a,this.textureConfig)},e.prototype.uploadMatrixToPackedTexture=function(e,t,r,n){return this.throwIfDisposed(),uploadMatrixToPackedTexture(this.gl,e,t,r,n,this.textureConfig)},e.prototype.downloadFloat32MatrixFromOutputTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,function(){return downloadFloat32MatrixFromOutputTexture(n.gl,t,r,n.textureConfig)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,function(){return downloadByteEncodedFloatMatrixFromOutputTexture(n.gl,t,r,n.textureConfig)})},e.prototype.downloadMatrixFromTextureAsync=function(e,t,r){return __awaiter(this,void 0,void 0,function(){var n=this;return __generator(this,function(a){if(null==this.getBufferSubDataAsyncExtension)throw new Error("Cannot download matrix from output texture asynchronously, WEBGL_get_buffer_sub_data_async is not enabled.");return[2,this.downloadMatrixDriverAsync(e,function(){return downloadMatrixFromOutputTextureAsync(n.gl,n.getBufferSubDataAsyncExtension,t,r,n.textureConfig)})]})})},e.prototype.downloadMatrixFromPackedTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,function(){return downloadMatrixFromPackedOutputTexture(n.gl,t,r,n.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,r=createFragmentShader(t,e),n=createVertexShader$1(t),a=createProgram(t);return callAndCheck(t,function(){return t.attachShader(a,n)}),callAndCheck(t,function(){return t.attachShader(a,r)}),linkProgram(t,a),this.autoDebugValidate&&validateProgram(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=bindVertexProgramAttributeStreams(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&callAndCheck(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&validateProgram(this.gl,this.program),callAndCheck(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,r){return void 0===r&&(r=!0),this.throwIfDisposed(),r?getProgramUniformLocationOrThrow(this.gl,e,t):getProgramUniformLocation(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var r=this;return this.throwIfDisposed(),callAndCheck(this.gl,function(){return r.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),bindTextureToProgramUniformSampler(this.gl,this.program,e,t,r)},e.prototype.setOutputMatrixTexture=function(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,r){this.throwIfDisposed();var n=getPackedMatrixTextureShapeWidthHeight(t,r),a=n[0],o=n[1];this.setOutputMatrixTextureDriver(e,a,o)},e.prototype.setOutputMatrixWriteRegion=function(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&validateProgram(this.gl,this.program),validateFramebuffer(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),callAndCheck(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),callAndCheck(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=getExtensionOrThrow(this.gl,2===ENV.get("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.runQuery=function(e){var t=this.beginQuery();return e(),this.endQuery(),this.pollQueryTime(t)},e.prototype.beginQuery=function(){if(2===ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,r),r}var n=this.getQueryTimerExtensionWebGL1(),a=n.createQueryEXT();return n.beginQueryEXT(n.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(n=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollQueryTime=function(e){var t=this;return new Promise(function(r){var n=ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION");t.addItemToPoll(function(){return t.isQueryAvailable(e,n)},function(){return r(t.getQueryTime(e,n))})})},e.prototype.pollItems=function(){for(var e=binSearchLastTrue(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var r=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||repeatedTry(function(){return r.pollItems(),0===r.itemsToPoll.length})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}var n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6},e.prototype.downloadMatrixDriverSetup=function(e){this.throwIfDisposed(),bindColorTextureToFramebuffer(this.gl,e,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(this.gl)},e.prototype.downloadMatrixDriverTeardown=function(){null!=this.outputTexture?(bindColorTextureToFramebuffer(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(this.gl)):unbindColorTextureFromFramebuffer(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.downloadMatrixDriverSetup(e);var r=t();return this.downloadMatrixDriverTeardown(),r},e.prototype.downloadMatrixDriverAsync=function(e,t){return __awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(n){switch(n.label){case 0:return this.downloadMatrixDriverSetup(e),[4,t()];case 1:return r=n.sent(),this.downloadMatrixDriverTeardown(),[2,r]}})})},e.prototype.setOutputMatrixTextureDriver=function(e,t,r){this.throwIfDisposed();var n=this.gl;bindColorTextureToFramebuffer(n,e,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(n),this.outputTexture=e,callAndCheck(n,function(){return n.viewport(0,0,t,r)}),callAndCheck(n,function(){return n.scissor(0,0,t,r)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,r,n){var a=this;this.throwIfDisposed(),callAndCheck(this.gl,function(){return a.gl.scissor(e,t,r,n)})},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 binSearchLastTrue(e){for(var t=0,r=e.length-1,n=-1;t<=r;){var a=t+r>>1;e[a]()?(n=a,t=a+1):r=a-1}return n}function compileProgram(e,t,r,n){for(var a=t.userCode,o=r.map(function(e,r){var n={logicalShape:e.tensor.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform};return{name:t.variableNames[r],shapeInfo:n}}),i=o.map(function(e){return e.shapeInfo}),s={logicalShape:n.tensor.shape,texShape:n.texData.texShape,isUniform:!1},u=makeShader(o,s,a,!0===t.supportsBroadcasting),l=e.createProgram(u),c={},p=0;p4)throw Error("Where for rank "+r+" is not yet supported");if(1===r)a="resRC",n="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "},LRNProgram=function(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[];var o,i=t,s=e[3]-1;this.outputShape=e;var u="float("+r+") + float("+n+") * sum";o=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",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 = -"+i+"; j <= "+i+"; 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 * "+o+";\n setOutput(val);\n }\n "},MaxPool2DBackpropProgram=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,o=t-1-e.padInfo.top,i=r-1-e.padInfo.left,s=t*r-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\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 < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.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 = "+s+" - 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 * "+r+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},MatMulProgram=function(e,t,r,n){void 0===r&&(r=!1),void 0===n&&(n=!1),this.variableNames=["matrixA","matrixB"];var a=r?e[1]:e[0],o=n?t[0]:t[1],i=r?e[0]:e[1];this.outputShape=[a,o];var s=function(e,t){return r?t+" + "+e+", aRow":"aRow, "+t+" + "+e},u=function(e,t){return n?"bCol, "+t+" + "+e:t+" + "+e+", bCol"},l=4*Math.floor(i/4),c=i%4;this.userCode=" float dotARowBCol(int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+l+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+s(0,"i")+"),\n getMatrixA("+s(1,"i")+"),\n getMatrixA("+s(2,"i")+"),\n getMatrixA("+s(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+u(0,"i")+"),\n getMatrixB("+u(1,"i")+"),\n getMatrixB("+u(2,"i")+"),\n getMatrixB("+u(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1===c)+") {\n result += getMatrixA("+s(0,l)+") *\n getMatrixB("+u(0,l)+");\n } else if ("+(2===c)+") {\n vec2 a = vec2(\n getMatrixA("+s(0,l)+"),\n getMatrixA("+s(1,l)+")\n );\n vec2 b = vec2(\n getMatrixB("+u(0,l)+"),\n getMatrixB("+u(1,l)+")\n );\n result += dot(a, b);\n } else if ("+(3===c)+") {\n vec3 a = vec3(\n getMatrixA("+s(0,l)+"),\n getMatrixA("+s(1,l)+"),\n getMatrixA("+s(2,l)+")\n );\n vec3 b = vec3(\n getMatrixB("+u(0,l)+"),\n getMatrixB("+u(1,l)+"),\n getMatrixB("+u(2,l)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec2 resRC = getOutputCoords();\n setOutput(dotARowBCol(resRC.x, resRC.y));\n }\n "},MultinomialProgram=function(){function e(e,t,r){this.variableNames=["probs"],this.outputShape=[e,r],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 < "+(t-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("+(t-1)+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(r,n){null==t.seedLoc&&(t.seedLoc=r.getUniformLocation(n,"seed")),r.gl.uniform1f(t.seedLoc,e)}},e}(),OneHotProgram=function(e,t,r,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+n+"), float("+r+"),\n float(index == coords.y)));\n }\n "},PadProgram=function(e,t,r){this.variableNames=["x"],this.outputShape=t.map(function(t,r){return t[0]+e[r]+t[1]});var n=e.length,a=getCoordsDataType(n),o=t.map(function(e){return e[0]}).join(","),i=t.map(function(t,r){return t[0]+e[r]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=1!==n?"\n "+a+" start = "+a+"("+o+");\n "+a+" end = "+a+"("+i+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+r+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+o+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+r+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Pool2DProgram=function(e,t,r){if(this.variableNames=["x"],"avg"===t&&r)throw new Error("Cannot compute positions for average pool.");var n=e.filterHeight,a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,s=e.padInfo.top,u=e.padInfo.left;this.outputShape=e.outShape;var l="avg"===t,c="0.0";if(l||(c="-1.0 / 0.0"),r)this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+s+", "+u+");\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 float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+a+"; wC++) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.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 * "+a+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var p=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(p="avgValue / count");var d=4*Math.floor(a/4),h=a%4,f="\n if ("+l+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+s+", "+u+");\n const float initializationValue = "+c+";\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 >= "+e.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("+c+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n "+f+"\n }\n\n int xC = xCCorner + "+d+";\n if ("+(1===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n "+f+"\n }\n }\n setOutput("+p+");\n }\n "}},ReduceProgram=function(e,t){this.variableNames=["x"];var r=e.windowSize,n=e.batchSize,a=e.inSize,o=Math.ceil(a/r);this.outputShape=[n,o];var i="0.0",s="";"min"===t?(i="1.0 / 0.0",s="min"):"max"===t&&(i="-1.0 / 0.0",s="max");var u=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t?u="sumValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");var l=4*Math.floor(r/4),c=r%4,p="\n if ("+("sum"===t)+") {\n sumValue += dot(values, ones);\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",d="vec4";"all"===t?(i="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",d="bvec4"):"any"===t&&(i="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",d="bvec4");var h="";a%r>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+h+"\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 * "+r+";\n\n vec4 minMaxValue = vec4("+i+");\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 "+d+" values = "+d+"(\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 "+d+" values = "+d+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+d+" values = "+d+"(\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 "},ResizeBilinearBackpropProgram=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,a=n[1],o=n[2],i=e.shape,s=i[1],u=i[2],l=[r&&s>1?a-1:a,r&&u>1?o-1:o],c=[r&&s>1?s-1:s,r&&u>1?u-1:u],p=l[0]/c[0],d=l[1]/c[1],h=1/p,f=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+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("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\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), "+(a-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), "+(o-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 "},ResizeBilinearProgram=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var a=e[0],o=e[1],i=e[2],s=e[3];this.outputShape=[a,t,r,s];var u=[n&&t>1?o-1:o,n&&r>1?i-1:i],l=[n&&t>1?t-1:t,n&&r>1?r-1:r];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+i+".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 "},ResizeNearestNeigborBackpropProgram=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,a=n[1],o=n[2],i=e.shape,s=i[1],u=i[2],l=[r&&s>1?a-1:a,r&&u>1?o-1:o],c=[r&&s>1?s-1:s,r&&u>1?u-1:u],p=l[0]/c[0],d=l[1]/c[1],h=1/p,f=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+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("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\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("+a+") - 1),\n "+r+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+r+" ? 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 "},ResizeNearestNeighborProgram=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var a=e[0],o=e[1],i=e[2],s=e[3];this.outputShape=[a,t,r,s];var u=[n&&t>1?o-1:o,n&&r>1?i-1:i],l=[n&&t>1?t-1:t,n&&r>1?r-1:r],c=n?"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("+o+".0, "+i+".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 "},ReverseProgram=function(e,t){this.variableNames=["x"];var r=e.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");if(this.outputShape=e,1!==r){var n=e.map(function(r,n){return function(r){return-1!==t.indexOf(r)&&1!==e[r]?e[r]+" - coords["+r+"] - 1":"coords["+r+"]"}(n)}).join(","),a=getCoordsDataType(r);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+n+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "},SegmentOpProgram=function(e,t){this.variableNames=["x","segmentIds"];var r=e.windowSize,n=e.batchSize,a=e.inSize,o=e.numSegments,i=o*Math.ceil(a/r);this.outputShape=[n,i];var s=4*Math.floor(r/4),u=r%4,l="\n sumValue += dot(values, filter);\n ",c="";a%r>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var p="";a%r>0&&(p="\n if (inIdx < 0 || inIdx >= "+a+") {\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 "+o+")) * float("+r+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\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 filter = 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 filter = 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 filter = 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 filter = 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 "},SliceProgram=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=getCoordsDataType(this.rank),r=getCoords$1(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+r+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(r,n){if(null!=t.startLoc||(t.startLoc=r.getUniformLocationNoThrow(n,"start"),null!=t.startLoc))if(1===t.rank)r.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)r.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)r.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");r.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}();function getCoords$1(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}var StridedSliceProgram=function(e,t,r){this.variableNames=["x"],this.outputShape=r,this.rank=r.length;var n,a=getCoordsDataType(this.rank);n=1===this.rank?"coords * strides + begin":r.map(function(e,t){return"coords["+t+"] * strides["+t+"] + begin["+t+"]"}).join(","),this.userCode="\n "+a+" begin = "+a+"("+e+");\n "+a+" strides = "+a+"("+t+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+n+"));\n }\n "},TextureManager=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t){var r,n=getPhysicalFromLogicalTextureType(t),a=getKeyFromTextureShape(e,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(),n===PhysicalTextureType.FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===PhysicalTextureType.FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===PhysicalTextureType.UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(r),r},e.prototype.releaseTexture=function(e,t,r){var n=getKeyFromTextureShape(t,getPhysicalFromLogicalTextureType(r));n in this.freeTextures||(this.freeTextures[n]=[]),this.freeTextures[n].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[n],o=a.indexOf(e);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(o,1),this.log()},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function getPhysicalFromLogicalTextureType(e){if(e===TextureUsage.DOWNLOAD||e===TextureUsage.PIXELS)return PhysicalTextureType.UNSIGNED_BYTE;if(e===TextureUsage.UPLOAD)return PhysicalTextureType.FLOAT32;if(e===TextureUsage.RENDER)return ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?PhysicalTextureType.FLOAT32:PhysicalTextureType.FLOAT16;throw new Error("Unknown logical texture type "+e)}function getKeyFromTextureShape(e,t){return e[0]+"_"+e[1]+"_"+t}var TileProgram=function(e,t){this.variableNames=["A"];for(var r=new Array(e.length),n=0;n5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[],a=0;a6)throw Error("Transpose for rank "+t+" is not yet supported");for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t),a=0;a= 0.0) ? x : (exp(x) - 1.0);",SELU="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+SELU_SCALEALPHA+";\n float scale = "+SELU_SCALE+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";function STEP(e){return void 0===e&&(e=0),CHECK_NAN_SNIPPET$1+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}var NEG="return -x;",CEIL="return ceil(x);",FLOOR="return floor(x);",SIGN="\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n",ROUND="\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",EXP="return exp(x);",EXPM1="return exp(x) - 1.0;",LOG="if (x < 0.0) return NAN;\n return log(x);",LOG1P="return log(1.0 + x);",SQRT="return sqrt(x);",RSQRT="return inversesqrt(x);",SIGMOID="return 1.0 / (1.0 + exp(-1.0 * x));",SOFTPLUS="\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",SIN=CHECK_NAN_SNIPPET$1+"\n return sin(x);\n",COS=CHECK_NAN_SNIPPET$1+"\n return cos(x);\n",TAN="return tan(x);",ASIN="return asin(x);",ACOS="return acos(x);",ATAN=CHECK_NAN_SNIPPET$1+"\n return atan(x);\n",SINH="\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n",COSH="\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n",TANH="\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n",ASINH="return log(x + sqrt(x * x + 1.0));",ACOSH=CHECK_NAN_SNIPPET$1+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",ATANH=CHECK_NAN_SNIPPET$1+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",ERF='\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 = '+ERF_P+";\n float a1 = "+ERF_A1+";\n float a2 = "+ERF_A2+";\n float a3 = "+ERF_A3+";\n float a4 = "+ERF_A4+";\n float a5 = "+ERF_A5+";\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",SQUARE="return x * x;",RECIPROCAL="return 1.0 / x;",LOGICAL_NOT="return float(!(x >= 1.0));",TO_INT="return float(int(x));",BEFORE_PAGING_CONSTANT=300,SIZE_UPLOAD_UNIFORM=32,MathBackendWebGL=function(){function e(e,t){if(void 0===t&&(t=!0),this.gpgpu=e,this.delayedStorage=t,this.texData=new WeakMap,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.lruDataGPU=[],this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.binaryCache={},this.disposed=!1,ENV.get("WEBGL_VERSION")<1)throw new Error("WebGL is not supported on this device");ENV.get("IS_BROWSER")&&(this.canvas=document.createElement("canvas")),null==e?(this.gpgpu=new GPGPUContext(createWebGLContext(this.canvas)),this.gpgpuCreatedLocally=!0):this.gpgpuCreatedLocally=!1,this.NUM_BYTES_BEFORE_PAGING=window.screen.height*window.screen.width*window.devicePixelRatio*BEFORE_PAGING_CONSTANT,this.textureManager=new TextureManager(this.gpgpu)}return e.prototype.register=function(e,t,r){if(this.texData.has(e))throw new Error("Data buffer is already registered");this.texData.set(e,{shape:t,dtype:r,values:null,texture:null,texShape:null,usage:TextureUsage.RENDER})},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var r=[e.height,e.width],n=[e.height,e.width,t];if(!(e instanceof HTMLVideoElement||e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof ImageData))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(e instanceof HTMLVideoElement){if(null==this.fromPixelsCanvas){if(!ENV.get("IS_BROWSER"))throw new Error("Can't read pixels from HTMLImageElement outside the browser.");if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixelsCanvas=document.createElement("canvas")}this.fromPixelsCanvas.width=e.width,this.fromPixelsCanvas.height=e.height,this.fromPixelsCanvas.getContext("2d").drawImage(e,0,0,e.width,e.height),e=this.fromPixelsCanvas}var a=Tensor.make(r,{},"int32");this.texData.get(a.dataId).usage=TextureUsage.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(a.dataId),e);var o=new FromPixelsProgram(n),i=this.compileAndRun(o,[a]);return a.dispose(),i},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendWebGL.write(): values can not be null");this.throwIfNoData(e);var r=this.texData.get(e),n=r.texture,a=r.texShape,o=r.usage;null!=n&&(this.releaseTexture(e,n,a,o),r.texture=null,r.texShape=null),r.usage=TextureUsage.UPLOAD,r.values=t,this.delayedStorage||this.uploadToGPU(e)},e.prototype.readSync=function(e){this.throwIfNoData(e);var t=this.texData.get(e),r=t.shape,n=t.texture,a=t.values,o=t.texShape,i=t.dtype;if(null!=a)return this.cacheOnCPU(e),a;var s,u,l=null!=this.activeTimers;if(l&&(s=performance.now()),ENV.get("WEBGL_DOWNLOAD_FLOAT_ENABLED"))u=this.gpgpu.downloadFloat32MatrixFromOutputTexture(n,o[0],o[1]);else{var c=Tensor.make(r,{});this.texData.get(c.dataId).usage=TextureUsage.DOWNLOAD;var p=Tensor.make(r,{dataId:e},i),d=new EncodeFloatProgram(r),h=this.compileAndRun(d,[p],c),f=this.texData.get(c.dataId);u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(f.texture,f.texShape[0],f.texShape[1]),h.dispose(),p.dispose(),c.dispose()}return l&&(this.downloadWaitMs+=performance.now()-s),this.cacheOnCPU(e,u),t.values},e.prototype.read=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a,o,i,s,u;return __generator(this,function(l){switch(l.label){case 0:return this.pendingRead.has(e)?(t=this.pendingRead.get(e),[2,new Promise(function(e){return t.push(e)})]):(this.throwIfNoData(e),r=this.texData.get(e),n=r.texture,a=r.values,o=r.texShape,null!=a?(this.cacheOnCPU(e),[2,a]):ENV.get("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED")?[4,this.gpgpu.downloadMatrixFromTextureAsync(n,o[0],o[1])]:[3,2]);case 1:return i=l.sent(),this.cacheOnCPU(e,i),[2,r.values];case 2:return 0===ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?[2,this.readSync(e)]:(this.pendingRead.set(e,[]),[4,this.gpgpu.runQuery(function(){})]);case 3:return l.sent(),s=this.pendingRead.get(e),this.pendingRead.delete(e),u=this.readSync(e),s.forEach(function(e){return e(u)}),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)),[2,u]}})})},e.prototype.time=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a,o,i;return __generator(this,function(s){switch(s.label){case 0:return t=this.activeTimers,r=[],n=!1,null==this.programTimersStack?(this.programTimersStack=r,n=!0):this.activeTimers.push(r),this.activeTimers=r,e(),a=flatten(this.activeTimers),this.activeTimers=t,n&&(this.programTimersStack=null),[4,Promise.all(a).then(function(e){var t=0;return e.forEach(function(e){return t+=e}),t})];case 1:return o=s.sent(),i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:o,wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,i]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(r){return ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.pollQueryTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),r=t.texture,n=t.texShape,a=t.usage;null!=r&&this.releaseTexture(e,r,n,a),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.getCanvas=function(){return this.canvas},e.prototype.slice=function(e,t,r){var n=new SliceProgram(r),a=n.getCustomSetupFunc(t);return this.compileAndRun(n,[e],null,a)},e.prototype.stridedSlice=function(e,t,r,n,a,o){var i=getStridedSlicedInfo(e.shape,t,r,n,a,o),s=i[0],u=i[1];if(u.some(function(e){return 0===e}))return tensor([],u);var l=new StridedSliceProgram(s,n,u);return this.compileAndRun(l,[e])},e.prototype.reverse=function(e,t){var r=new ReverseProgram(e.shape,t);return this.compileAndRun(r,[e])},e.prototype.concat=function(e,t){var r=new ConcatProgram(e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.neg=function(e){var t=new UnaryOpProgram(e.shape,NEG);return this.compileAndRun(t,[e])},e.prototype.matMul=function(e,t,r,n){var a=new MatMulProgram(e.shape,t.shape,r,n);return this.compileAndRun(a,[e,t])},e.prototype.multiply=function(e,t){var r=new BinaryOpProgram(MUL,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,upcastType(e.dtype,t.dtype));return this.compileAndRun(r,[e,t],n)},e.prototype.batchNormalization=function(e,t,r,n,a,o){var i=[e,t,r],s=null;null!=o&&(s=o.shape,i.push(o));var u=null;null!=a&&(u=a.shape,i.push(a));var l=new BatchNormProgram(e.shape,t.shape,r.shape,s,u,n);return this.compileAndRun(l,i)},e.prototype.localResponseNormalization4D=function(e,t,r,n,a){var o=new LRNProgram(e.shape,t,r,n,a);return this.compileAndRun(o,[e])},e.prototype.tile=function(e,t){var r=new TileProgram(e.shape,t);return this.compileAndRun(r,[e])},e.prototype.pad=function(e,t,r){var n=new PadProgram(e.shape,t,r);return this.compileAndRun(n,[e])},e.prototype.transpose=function(e,t){var r=new TransposeProgram(e.shape,t);return this.compileAndRun(r,[e])},e.prototype.gather=function(e,t,r){var n=new GatherProgram(e.shape,t.size,r);return this.compileAndRun(n,[e,t])},e.prototype.reduce=function(e,t,r){var n=e.shape[0],a=e.shape[1],o=computeOptimalWindowSize(a),i=new ReduceProgram({windowSize:o,inSize:a,batchSize:n},t),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],r);return this.compileAndRun(i,[e],c),1===c.shape[1]?c:this.reduce(c,t,r)},e.prototype.argReduce=function(e,t,r){void 0===r&&(r=null);var n=e.shape[0],a=e.shape[1];null!=r&&(n=r.shape[0],a=r.shape[1]);var o=computeOptimalWindowSize(a),i=new ArgMinMaxProgram({windowSize:o,inSize:a,batchSize:n},t,null==r),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],"int32"),p=[e];return null!=r&&p.push(r),this.compileAndRun(i,p,c),1===c.shape[1]?c:this.argReduce(e,t,c)},e.prototype.sum=function(e,t){assertAxesAreInnerMostDims("sum",t,e.rank);var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=sizeFromShape(r[1]),o=e.as2D(-1,a),i=sumOutType(e.dtype);return this.reduce(o,"sum",i).reshape(n)},e.prototype.unsortedSegmentSum=function(e,t,r){var n=0,a=getAxesPermutation([n],e.rank),o=e;null!=a&&(o=e.transpose(a),n=getInnerMostAxes(1,e.rank)[0]);var i=computeOutShape$1(o.shape,n,r),s=sizeFromShape([o.shape[n]]),u=o.as2D(-1,s),l=sumOutType(e.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",t,l,r).reshape(i);return null!=a&&(c=c.transpose(getUndoAxesPermutation(a))),c},e.prototype.segOpCompute=function(e,t,r,n,a){var o=e.shape[0],i=e.shape[1],s=segOpComputeOptimalWindowSize(i,a),u=new SegmentOpProgram({windowSize:s,inSize:i,batchSize:o,numSegments:a},t),l=u.outputShape,c=l[0],p=l[1],d=this.makeOutputArray([c,p],n);return this.compileAndRun(u,[e,r],d),d.shape[1]===a?d:(r=range(0,a).tile([i/s]),this.segOpCompute(d,t,r,n,a))},e.prototype.argMin=function(e,t){var r=[t];assertAxesAreInnerMostDims("argMin",r,e.rank);var n=computeOutAndReduceShapes(e.shape,r),a=n[0],o=sizeFromShape(n[1]),i=e.as2D(-1,o);return this.argReduce(i,"min").reshape(a)},e.prototype.argMax=function(e,t){var r=[t];assertAxesAreInnerMostDims("argMax",r,e.rank);var n=computeOutAndReduceShapes(e.shape,r),a=n[0],o=sizeFromShape(n[1]),i=e.as2D(-1,o);return this.argReduce(i,"max").reshape(a)},e.prototype.cumsum=function(e,t,r,n){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new CumSumProgram(e.shape,r,n);return this.compileAndRun(a,[e])},e.prototype.equal=function(e,t){var r=new BinaryOpProgram(EQUAL,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.notEqual=function(e,t){var r=new BinaryOpProgram(NOT_EQUAL,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.less=function(e,t){var r=new BinaryOpProgram(LESS,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.lessEqual=function(e,t){var r=new BinaryOpProgram(LESS_EQUAL,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.greater=function(e,t){var r=new BinaryOpProgram(GREATER,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.greaterEqual=function(e,t){var r=new BinaryOpProgram(GREATER_EQUAL,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.logicalNot=function(e){var t=new UnaryOpProgram(e.shape,LOGICAL_NOT);return this.compileAndRun(t,[e])},e.prototype.logicalAnd=function(e,t){var r=new BinaryOpProgram(LOGICAL_AND,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.logicalOr=function(e,t){var r=new BinaryOpProgram(LOGICAL_OR,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,t],n)},e.prototype.where=function(e,t,r,n){var a=new WhereProgram(e.rank,t.shape,t.rank),o=this.makeOutputArray(a.outputShape,n);return this.compileAndRun(a,[e,t,r],o)},e.prototype.topKValues=function(e,t){throw new Error("topKValues GPU not yet implemented!")},e.prototype.topKIndices=function(e,t){throw new Error("topKIndices GPU not yet implemented!")},e.prototype.min=function(e,t){assertAxesAreInnerMostDims("min",t,e.rank);var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=sizeFromShape(r[1]),o=e.as2D(-1,a);return this.reduce(o,"min",o.dtype).reshape(n)},e.prototype.minimum=function(e,t){var r=new BinaryOpProgram(MIN,e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.mod=function(e,t){var r=new BinaryOpProgram(MOD,e.shape,t.shape),n=r.getCustomSetupFunc();return this.compileAndRun(r,[e,t],null,n)},e.prototype.max=function(e,t){assertAxesAreInnerMostDims("max",t,e.rank);var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=sizeFromShape(r[1]),o=e.as2D(-1,a);return this.reduce(o,"max",o.dtype).reshape(n)},e.prototype.maximum=function(e,t){var r=new BinaryOpProgram(MAX,e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.all=function(e,t){assertAxesAreInnerMostDims("all",t,e.rank);var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=sizeFromShape(r[1]),o=e.as2D(-1,a);return this.reduce(o,"all",o.dtype).reshape(n)},e.prototype.any=function(e,t){assertAxesAreInnerMostDims("any",t,e.rank);var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=sizeFromShape(r[1]),o=e.as2D(-1,a);return this.reduce(o,"any",o.dtype).reshape(n)},e.prototype.squaredDifference=function(e,t){var r=new BinaryOpProgram(SQUARED_DIFFERENCE,e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.realDivide=function(e,t){var r=new BinaryOpProgram(DIV,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"float32");return this.compileAndRun(r,[e,t],n)},e.prototype.floorDiv=function(e,t){var r=new BinaryOpProgram(INT_DIV,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,"int32");return this.compileAndRun(r,[e,t],n)},e.prototype.add=function(e,t){var r=new BinaryOpProgram(ADD,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,upcastType(e.dtype,t.dtype));return this.compileAndRun(r,[e,t],n)},e.prototype.subtract=function(e,t){var r=new BinaryOpProgram(SUB,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,upcastType(e.dtype,t.dtype));return this.compileAndRun(r,[e,t],n)},e.prototype.pow=function(e,t){var r=new BinaryOpProgram(POW,e.shape,t.shape),n=this.makeOutputArray(r.outputShape,upcastType(e.dtype,t.dtype));return this.compileAndRun(r,[e,t],n)},e.prototype.ceil=function(e){var t=new UnaryOpProgram(e.shape,CEIL);return this.compileAndRun(t,[e])},e.prototype.floor=function(e){var t=new UnaryOpProgram(e.shape,FLOOR);return this.compileAndRun(t,[e])},e.prototype.sign=function(e){var t=new UnaryOpProgram(e.shape,SIGN);return this.compileAndRun(t,[e])},e.prototype.round=function(e){var t=new UnaryOpProgram(e.shape,ROUND);return this.compileAndRun(t,[e])},e.prototype.exp=function(e){var t=new UnaryOpProgram(e.shape,EXP);return this.compileAndRun(t,[e])},e.prototype.expm1=function(e){var t=new UnaryOpProgram(e.shape,EXPM1);return this.compileAndRun(t,[e])},e.prototype.log=function(e){var t=new UnaryOpProgram(e.shape,LOG),r=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,r)},e.prototype.log1p=function(e){var t=new UnaryOpProgram(e.shape,LOG1P);return this.compileAndRun(t,[e])},e.prototype.sqrt=function(e){var t=new UnaryOpProgram(e.shape,SQRT);return this.compileAndRun(t,[e])},e.prototype.rsqrt=function(e){var t=new UnaryOpProgram(e.shape,RSQRT);return this.compileAndRun(t,[e])},e.prototype.square=function(e){var t=new UnaryOpProgram(e.shape,SQUARE);return this.compileAndRun(t,[e])},e.prototype.reciprocal=function(e){var t=new UnaryOpProgram(e.shape,RECIPROCAL);return this.compileAndRun(t,[e])},e.prototype.relu=function(e){var t=new UnaryOpProgram(e.shape,RELU);return this.compileAndRun(t,[e])},e.prototype.elu=function(e){var t=new UnaryOpProgram(e.shape,ELU);return this.compileAndRun(t,[e])},e.prototype.eluDer=function(e,t){var r=new BinaryOpProgram(ELU_DER,e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.selu=function(e){var t=new UnaryOpProgram(e.shape,SELU);return this.compileAndRun(t,[e])},e.prototype.int=function(e){var t=new UnaryOpProgram(e.shape,TO_INT),r=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],r)},e.prototype.clip=function(e,t,r){var n=new ClipProgram(e.shape,t,r);return this.compileAndRun(n,[e])},e.prototype.abs=function(e){var t=new UnaryOpProgram(e.shape,ABS);return this.compileAndRun(t,[e])},e.prototype.sigmoid=function(e){var t=new UnaryOpProgram(e.shape,SIGMOID);return this.compileAndRun(t,[e])},e.prototype.softplus=function(e){var t=new UnaryOpProgram(e.shape,SOFTPLUS);return this.compileAndRun(t,[e])},e.prototype.sin=function(e){var t=new UnaryOpProgram(e.shape,SIN);return this.compileAndRun(t,[e])},e.prototype.cos=function(e){var t=new UnaryOpProgram(e.shape,COS);return this.compileAndRun(t,[e])},e.prototype.tan=function(e){var t=new UnaryOpProgram(e.shape,TAN);return this.compileAndRun(t,[e])},e.prototype.asin=function(e){var t=new UnaryOpProgram(e.shape,ASIN);return this.compileAndRun(t,[e])},e.prototype.acos=function(e){var t=new UnaryOpProgram(e.shape,ACOS);return this.compileAndRun(t,[e])},e.prototype.atan=function(e){var t=new UnaryOpProgram(e.shape,ATAN);return this.compileAndRun(t,[e])},e.prototype.atan2=function(e,t){var r=new BinaryOpProgram(ATAN2,e.shape,t.shape);return this.compileAndRun(r,[e,t])},e.prototype.sinh=function(e){var t=new UnaryOpProgram(e.shape,SINH);return this.compileAndRun(t,[e])},e.prototype.cosh=function(e){var t=new UnaryOpProgram(e.shape,COSH);return this.compileAndRun(t,[e])},e.prototype.tanh=function(e){var t=new UnaryOpProgram(e.shape,TANH);return this.compileAndRun(t,[e])},e.prototype.asinh=function(e){var t=new UnaryOpProgram(e.shape,ASINH);return this.compileAndRun(t,[e])},e.prototype.acosh=function(e){var t=new UnaryOpProgram(e.shape,ACOSH),r=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,r)},e.prototype.atanh=function(e){var t=new UnaryOpProgram(e.shape,ATANH),r=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,r)},e.prototype.erf=function(e){var t=new UnaryOpProgram(e.shape,ERF);return this.compileAndRun(t,[e])},e.prototype.step=function(e,t){var r=new UnaryOpProgram(e.shape,STEP(t));return this.compileAndRun(r,[e])},e.prototype.conv2d=function(e,t,r){var n=new Conv2DProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.conv2dDerInput=function(e,t,r){var n=new Conv2DDerInputProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.conv2dDerFilter=function(e,t,r){var n=new Conv2DDerFilterProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.depthwiseConv2D=function(e,t,r){var n=new DepthwiseConv2DProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.depthwiseConv2DDerInput=function(e,t,r){var n=new DepthwiseConv2DDerInputProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.depthwiseConv2DDerFilter=function(e,t,r){var n=new DepthwiseConv2DDerFilterProgram(r);return this.compileAndRun(n,[e,t])},e.prototype.maxPool=function(e,t){var r=new Pool2DProgram(t,"max",!1),n=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[e],n)},e.prototype.avgPool=function(e,t){var r=new Pool2DProgram(t,"avg",!1),n=this.makeOutputArray(r.outputShape,"float32");return this.compileAndRun(r,[e],n)},e.prototype.maxPoolBackprop=function(e,t,r,n){var a=new Pool2DProgram(n,"max",!0),o=this.compileAndRun(a,[t]),i=new MaxPool2DBackpropProgram(n),s=this.makeOutputArray(i.outputShape,t.dtype),u=this.compileAndRun(i,[e,o],s);return o.dispose(),u},e.prototype.avgPoolBackprop=function(e,t,r){var n=new AvgPool2DBackpropProgram(r),a=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[e],a)},e.prototype.cast=function(e,t){return castTensor(e,t,this)},e.prototype.reshape=function(e,t){return reshapeTensor(e,t)},e.prototype.resizeBilinear=function(e,t,r,n){var a=new ResizeBilinearProgram(e.shape,t,r,n);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(e,t,r){var n=new ResizeBilinearBackpropProgram(e,t,r);return this.compileAndRun(n,[e])},e.prototype.resizeNearestNeighbor=function(e,t,r,n){var a=new ResizeNearestNeighborProgram(e.shape,t,r,n);return this.compileAndRun(a,[e])},e.prototype.resizeNearestNeighborBackprop=function(e,t,r){var n=new ResizeNearestNeigborBackpropProgram(e,t,r);return this.compileAndRun(n,[e])},e.prototype.multinomial=function(e,t,r,n){var a=t?e:softmax(e),o=a.shape[0],i=a.shape[1],s=new MultinomialProgram(o,i,r),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(n);return this.compileAndRun(s,[a],u,l)},e.prototype.oneHot=function(e,t,r,n){var a=new OneHotProgram(e.size,t,r,n);return this.compileAndRun(a,[e])},e.prototype.makeOutputArray=function(e,t){return Tensor.make(e,{},t)},e.prototype.compileAndRun=function(e,t,r,n){var a=this;null==r&&(r=this.makeOutputArray(e.outputShape,t[0].dtype));var o=t.map(function(e){var t=a.texData.get(e.dataId);return null==t.texture&&e.size<=SIZE_UPLOAD_UNIFORM?{tensor:e,texData:null,isUniform:!0}:(a.uploadToGPU(e.dataId),{tensor:e,texData:t,isUniform:!1})});this.uploadToGPU(r.dataId);var i,s={tensor:r,texData:this.texData.get(r.dataId),isUniform:!1},u=makeShaderKey(e,o,s),l=this.getAndSaveBinary(u,function(){return compileProgram(a.gpgpu,e,o,s)}),c=null!=this.activeTimers;if(c&&(i=this.startTimer()),runProgram(l,o,s,n),this.numBytesInGPU>this.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;p>0;){var d=this.lruDataGPU.shift(),h=this.texData.get(d),f=h.shape,m=h.dtype;p-=this.computeBytes(f,m),this.read(d)}return c&&(i=this.endTimer(i),this.activeTimers.push(this.getQueryTime(i))),r},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixelsCanvas&&this.fromPixelsCanvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.throwIfNoData=function(e){if(!this.texData.has(e))throw new Error("WebGL backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends")},e.prototype.uploadToGPU=function(e){this.throwIfNoData(e);var t=this.texData.get(e),r=t.shape,n=t.values,a=t.texture,o=t.dtype,i=t.usage;if(null!=a)return this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),void this.lruDataGPU.push(e);var s,u=null!=this.activeTimers;u&&(s=performance.now());var l=getTextureShapeFromLogicalShape(this.gpgpu.gl,r);t.texShape=l;var c=this.acquireTexture(e,l,i);t.texture=c,null!=n&&(this.gpgpu.uploadMatrixToTexture(c,l[0],l[1],typedArrayToFloat32(n,o)),t.values=null,u&&(this.uploadWaitMs+=performance.now()-s))},e.prototype.cacheOnCPU=function(e,t){var r=this.delayedStorage,n=this.texData.get(e),a=n.texture,o=n.texShape,i=n.dtype,s=n.usage;r&&null!=a&&(this.releaseTexture(e,a,o,s),n.texture=null,n.texShape=null),null!=t&&(n.values=float32ToTypedArray(t,i))},e.prototype.releaseTexture=function(e,t,r,n){var a=this.texData.get(e),o=a.shape,i=a.dtype,s=this.lruDataGPU.indexOf(e);s>=0&&this.lruDataGPU.splice(s,1),this.numBytesInGPU-=this.computeBytes(o,i),this.textureManager.releaseTexture(t,r,n)},e.prototype.acquireTexture=function(e,t,r){var n=this.texData.get(e),a=n.shape,o=n.dtype;return this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(a,o),this.textureManager.acquireTexture(t,r)},e.prototype.computeBytes=function(e,t){return sizeFromShape(e)*bytesPerElement(t)},e}();function float32ToTypedArray(e,t){if("float32"===t)return e;if("int32"===t||"bool"===t){for(var r="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),n=0;nd&&(d=m,h=f)}u[c]=h}return i},e.prototype.cumsum=function(e,t,r,n){if(t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=upcastType(e.dtype,"int32"),o=zeros(e.shape,a),i=o.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=n?function(e,t){return e+u-t-1}:function(e,t){return e+t},c=0;ct?1:0})},e.prototype.greaterEqual=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){for(var t=e.dataSync(),r=new Int32Array(t.length),n=0;n1||1===t.rank?1:t.shape[1],p=0;p=0&&t>=0?r:(r+t)%t})},e.prototype.max=function(e,t){assertAxesAreInnerMostDims("max",t,e.rank);for(var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=r[1],o=zeros(n,e.dtype),i=sizeFromShape(a),s=o.dataSync(),u=e.dataSync(),l=0;lp&&(p=h)}s[l]=p}return o},e.prototype.maximum=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){assertAxesAreInnerMostDims("all",t,e.rank);for(var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=r[1],o=zeros(n,e.dtype),i=sizeFromShape(a),s=o.dataSync(),u=e.dataSync(),l=0;l0?r[n]=1:r[n]=0;return Tensor.make(e.shape,{values:r})},e.prototype.round=function(e){for(var t=e.dataSync(),r=new Float32Array(t.length),n=0;n.5?r[n]=Math.ceil(t[n]):r[n]=a%2==0?a:a+1}return Tensor.make(e.shape,{values:r})},e.prototype.exp=function(e){for(var t=e.dataSync(),r=new Float32Array(t.length),n=0;n=0?a:Math.exp(a)-1}return Tensor.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){for(var r=new Float32Array(t.size),n=t.dataSync(),a=e.dataSync(),o=0;o=1?a[o]:a[o]*(i+1)}return Tensor.make(t.shape,{values:r})},e.prototype.selu=function(e){for(var t=SELU_SCALEALPHA,r=SELU_SCALE,n=new Float32Array(e.size),a=e.dataSync(),o=0;o=0?r*i:t*(Math.exp(i)-1)}return Tensor.make(e.shape,{values:n})},e.prototype.clip=function(e,t,r){for(var n=new Float32Array(e.size),a=e.dataSync(),o=0;o-t,s=n[a]0?1:t}return Tensor.make(e.shape,{values:r})},e.prototype.conv2d=function(e,t,r){for(var n=r.filterHeight,a=r.filterWidth,o=r.dilationHeight,i=r.dilationWidth,s=r.padInfo.left,u=r.padInfo.top,l=buffer(r.outShape,e.dtype),c=0;c=r.inHeight))for(var b=0;b=r.inWidth))for(var w=0;w=r.inHeight))for(var w=0;w=r.inWidth||(v+=e.get(p,x,S,d)*t.get(b,w,d,y))}}c.set(v,p,h,m,d*l+y)}return c.toTensor()},e.prototype.depthwiseConv2DDerInput=function(e,t,r){for(var n=buffer(r.inShape,"float32"),a=n.values,o=n.strides,i=o[0],s=o[1],u=o[2],l=e.dataSync(),c=e.strides,p=c[0],d=c[1],h=c[2],f=t.dataSync(),m=t.strides,g=m[0],y=m[1],v=m[2],b=r.batchSize,x=r.filterHeight,w=r.filterWidth,S=r.inChannels,T=r.inHeight,N=r.inWidth,E=r.outChannels,_=r.outHeight,A=r.outWidth,I=r.strideHeight,O=r.strideWidth,C=x-1-r.padInfo.top,P=w-1-r.padInfo.left,R=E/S,k=0;kx?x=E:"avg"===r&&(w+=E,S++)}if(isNaN(x))break}s.set("avg"===r?w/S:x,c,d,g,p)}return s.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var r=buffer(t.outShape,"int32"),n=t.strideHeight,a=t.strideWidth,o=t.filterHeight,i=t.filterWidth,s=t.padInfo.top,u=t.padInfo.left,l=0;lb&&(b=E,x=S*i+N)}r.set(x,l,p,m,c)}return r.toTensor()},e.prototype.maxPoolBackprop=function(e,t,r,n){for(var a=this.maxPoolPositions(t,n),o=n.strideHeight,i=n.strideWidth,s=n.filterHeight,u=n.filterWidth,l=u-1-n.padInfo.left,c=s-1-n.padInfo.top,p=buffer(t.shape,"float32"),d=0;d=n.outHeight||Math.floor(x)!==x))for(var w=0;w=n.outWidth||Math.floor(S)!==S)){var T=s*u-1-a.get(d,x,S,h)===b*u+w?1:0;0!==T&&(v+=e.get(d,x,S,h)*T)}}}p.set(v,d,f,m,h)}return p.toTensor()},e.prototype.avgPoolBackprop=function(e,t,r){for(var n=r.strideHeight,a=r.strideWidth,o=r.filterHeight,i=r.filterWidth,s=i-1-r.padInfo.left,u=o-1-r.padInfo.top,l=buffer(t.shape,"float32"),c=1/(o*i),p=0;p=r.outHeight||Math.floor(b)!==b))for(var x=0;x=r.outWidth||Math.floor(w)!==w||(y+=e.get(p,b,w,d))}}l.set(y*c,p,h,f,d)}return l.toTensor()},e.prototype.cast=function(e,t){return castTensor(e,t,this)},e.prototype.reshape=function(e,t){return reshapeTensor(e,t)},e.prototype.avgPool=function(e,t){return this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,r,n){for(var a=e.shape,o=a[0],i=a[1],s=a[2],u=a[3],l=buffer([o,t,r,u],e.dtype),c=[n&&t>1?i-1:i,n&&r>1?s-1:s],p=[n&&t>1?t-1:t,n&&r>1?r-1:r],d=0;d1?o-1:o,r&&c>1?i-1:i],h=[r&&l>1?l-1:l,r&&c>1?c-1:c],f=d[0]/h[0],m=d[1]/h[1],g=0;g1?i-1:i,n&&r>1?s-1:s],p=[n&&t>1?t-1:t,n&&r>1?r-1:r],d=0;d1?o-1:o,r&&c>1?i-1:i],h=[r&&l>1?l-1:l,r&&c>1?c-1:c],f=1/(d[0]/h[0]),m=1/(d[1]/h[1]),g=2*Math.ceil(f)+2,y=2*Math.ceil(m)+2,v=0;v=l))for(var O=0;O=c)){var P=d[0]*(I/h[0]),R=d[1]*(C/h[1]),k=Math.min(o-1,r?Math.round(P):Math.floor(P)),D=Math.min(i-1,r?Math.round(R):Math.floor(R));b===k&&x===D&&(_+=e.get(v,I,C,E))}}}p.set(_,v,b,x,E)}return p.toTensor()},e.prototype.batchNormalization=function(e,t,r,n,a,o){for(var i=e.dataSync(),s=t.dataSync(),u=r.dataSync(),l=a?a.dataSync():new Float32Array([1]),c=o?o.dataSync():new Float32Array([0]),p=new Float32Array(i.length),d=0;d=0&&e.get(o)0,"scheme must not be an empty string.");var n=e.getInstance();assert(null==n.managers[t],"A model store manager is already registered for scheme '"+t+"'."),n.managers[t]=r},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function parseURL(e){if(-1===e.indexOf(URL_SCHEME_SUFFIX))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ModelStoreManagerRegistry.getSchemes().join(","));return{scheme:e.split(URL_SCHEME_SUFFIX)[0],path:e.split(URL_SCHEME_SUFFIX)[1]}}function cloneModelInternal(e,t,r){return void 0===r&&(r=!1),__awaiter(this,void 0,void 0,function(){var n,a,o,i,s,u,l,c,p;return __generator(this,function(d){switch(d.label){case 0:return assert(e!==t,"Old path and new path are the same: '"+e+"'"),assert((n=IORouterRegistry.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),assert(n.length<2,"Copying failed because more than one ("+n.length+") load handlers for source URL "+e+"."),a=n[0],assert((o=IORouterRegistry.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),assert(o.length<2,"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."),i=o[0],s=parseURL(e).scheme,u=parseURL(e).path,l=s===parseURL(e).scheme,[4,a.load()];case 1:return c=d.sent(),r&&l?[4,ModelStoreManagerRegistry.getManager(s).removeModel(u)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,i.save(c)];case 4:return p=d.sent(),!r||l?[3,6]:[4,ModelStoreManagerRegistry.getManager(s).removeModel(u)];case 5:d.sent(),d.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var ModelManagement=function(){function e(){}return e.listModels=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a,o,i;return __generator(this,function(s){switch(s.label){case 0:e=ModelStoreManagerRegistry.getSchemes(),t={},r=0,n=e,s.label=1;case 1:return r0,"URL path for browserHTTPRequest must not be null, undefined or empty."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a;return __generator(this,function(o){switch(o.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,weightsManifest:r},t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,fetch(this.path,t)];case 1:if(200===(a=o.sent()).status)return[2,{modelArtifactsInfo:getModelArtifactsInfoForJSON(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a,o,i,s,u,l,c,p;return __generator(this,function(d){switch(d.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:return[4,d.sent().json()];case 2:if(e=d.sent(),t=e.modelTopology,r=e.weightsManifest,null==t&&null==r)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");if(null==r)return[3,4];for(o=e.weightsManifest,n=[],i=0,s=o;ir)}function expectValuesInRange(e,t,r){var n;n=e instanceof Tensor?e.dataSync():e;for(var a=0;ar)throw new Error("Value out of range:"+n[a]+" low: "+t+", high: "+r)}function expectArrayBuffersEqual(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var test_util=Object.freeze({WEBGL_ENVS:WEBGL_ENVS,CPU_ENVS:CPU_ENVS,CHROME_CPU_ENVS:CHROME_CPU_ENVS,NATIVE_ENV:NATIVE_ENV,BROWSER_ENVS:BROWSER_ENVS,ALL_ENVS:ALL_ENVS,expectArraysClose:expectArraysClose,expectPromiseToFail:expectPromiseToFail,expectArraysEqual:expectArraysEqual,expectNumbersClose:expectNumbersClose,expectValuesInRange:expectValuesInRange,expectArrayBuffersEqual:expectArrayBuffersEqual}),version="0.12.0",webgl=Object.freeze({gpgpu_util:gpgpu_util,webgl_util:webgl_util,MathBackendWebGL:MathBackendWebGL,GPGPUContext:GPGPUContext}),Optimizer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.minimize=function(e,t,r){void 0===t&&(t=!1);var n=this.computeGradients(e,r),a=n.value,o=n.grads;return this.applyGradients(o),Object.keys(o).forEach(function(e){return o[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return variableGrads(e,t)},__decorate([doc({heading:"Training",subheading:"Optimizers"})],t.prototype,"minimize",null),__decorate([doc({heading:"Training",subheading:"Classes",namespace:"train"})],t)}(Serializable),DEFAULT_FLOAT32_EPSILON=1e-8,DEFAULT_FLOAT16_EPSILON=1e-4;function getOptimizerDefaultEpsilonValue(){return ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?DEFAULT_FLOAT32_EPSILON:DEFAULT_FLOAT16_EPSILON}var AdadeltaOptimizer=function(e){function t(t,r,n){void 0===n&&(n=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=r,a.epsilon=n,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=keep(scalar(-t)),a.rhoScalar=keep(scalar(r)),a.oneMinusRho=keep(scalar(1-r)),null===n&&(n=getOptimizerDefaultEpsilonValue()),a.epsilonScalar=keep(scalar(n)),a}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedGrads[r]&&tidy(function(){t.accumulatedGrads[r]=zerosLike(a).variable(!1)}),null==n.accumulatedUpdates[r]&&tidy(function(){t.accumulatedUpdates[r]=zerosLike(a).variable(!1)});var o=e[r],i=n.accumulatedGrads[r],s=n.accumulatedUpdates[r];tidy(function(){var e=t.rhoScalar.mul(i).add(t.oneMinusRho.mul(o.square())),n=s.add(t.epsilonScalar).sqrt().div(i.add(t.epsilonScalar).sqrt()).mul(o),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(n.square()));t.accumulatedGrads[r].assign(e),t.accumulatedUpdates[r].assign(u);var l=t.c.mul(n).add(a);a.assign(l)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(Optimizer);SerializationMap.register(AdadeltaOptimizer);var AdagradOptimizer=function(e){function t(t,r){void 0===r&&(r=.1);var n=e.call(this)||this;n.learningRate=t,n.initialAccumulatorValue=r,n.accumulatedGrads={},n.c=keep(scalar(-t));var a=getOptimizerDefaultEpsilonValue();return n.epsilon=keep(scalar(a)),n}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedGrads[r]&&tidy(function(){t.accumulatedGrads[r]=fill(a.shape,t.initialAccumulatorValue).variable(!1)});var o=e[r],i=n.accumulatedGrads[r];tidy(function(){var e=i.add(o.square());t.accumulatedGrads[r].assign(e);var n=t.c.mul(o.div(e.add(t.epsilon).sqrt())).add(a);a.assign(n)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(Optimizer);SerializationMap.register(AdagradOptimizer);var AdamOptimizer=function(e){function t(t,r,n,a){void 0===a&&(a=null);var o=e.call(this)||this;return o.learningRate=t,o.beta1=r,o.beta2=n,o.epsilon=a,o.accumulatedFirstMoment={},o.accumulatedSecondMoment={},o.c=keep(scalar(-t)),o.beta1Scalar=keep(scalar(r)),o.beta2Scalar=keep(scalar(n)),tidy(function(){o.accBeta1=scalar(r).variable(),o.accBeta2=scalar(n).variable()}),o.oneMinusBeta1=keep(scalar(1-r)),o.oneMinusBeta2=keep(scalar(1-n)),o.one=keep(scalar(1)),null===a&&(a=getOptimizerDefaultEpsilonValue()),o.epsScalar=keep(scalar(a)),o}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;tidy(function(){var r=t.one.sub(t.accBeta1),n=t.one.sub(t.accBeta2);for(var a in e){var o=ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var i=!1;t.accumulatedFirstMoment[a]=zerosLike(o).variable(i)}null==t.accumulatedSecondMoment[a]&&(i=!1,t.accumulatedSecondMoment[a]=zerosLike(o).variable(i));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),p=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),d=c.div(r),h=p.div(n);t.accumulatedFirstMoment[a].assign(c),t.accumulatedSecondMoment[a].assign(p);var f=t.c.mul(d.div(t.epsScalar.add(h.sqrt()))).add(o);o.assign(f)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(Optimizer);SerializationMap.register(AdamOptimizer);var AdamaxOptimizer=function(e){function t(t,r,n,a,o){void 0===a&&(a=null),void 0===o&&(o=0);var i=e.call(this)||this;return i.learningRate=t,i.beta1=r,i.beta2=n,i.epsilon=a,i.decay=o,i.accumulatedFirstMoment={},i.accumulatedWeightedInfNorm={},i.c=keep(scalar(-t)),i.beta1Scalar=keep(scalar(r)),i.beta2Scalar=keep(scalar(n)),i.decayScalar=keep(scalar(o)),tidy(function(){i.iteration=scalar(0).variable(),i.accBeta1=scalar(r).variable()}),i.oneMinusBeta1=keep(scalar(1-r)),i.one=keep(scalar(1)),null===a&&(a=getOptimizerDefaultEpsilonValue()),i.epsScalar=keep(scalar(a)),i}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;tidy(function(){var r=t.one.sub(t.accBeta1),n=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var o=ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var i=!1;t.accumulatedFirstMoment[a]=zerosLike(o).variable(i)}null==t.accumulatedWeightedInfNorm[a]&&(i=!1,t.accumulatedWeightedInfNorm[a]=zerosLike(o).variable(i));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),p=t.beta2Scalar.mul(l),d=s.abs(),h=p.maximum(d);t.accumulatedFirstMoment[a].assign(c),t.accumulatedWeightedInfNorm[a].assign(h);var f=n.div(r).mul(c.div(t.epsScalar.add(h))).add(o);o.assign(f)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(Optimizer);SerializationMap.register(AdamaxOptimizer);var SGDOptimizer=function(e){function t(t){var r=e.call(this)||this;return r.learningRate=t,r.setLearningRate(t),r}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(r){var n=e[r],a=ENV.engine.registeredVariables[r];tidy(function(){var e=t.c.mul(n).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=keep(scalar(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(Optimizer);SerializationMap.register(SGDOptimizer);var MomentumOptimizer=function(e){function t(t,r,n){void 0===n&&(n=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=r,a.useNesterov=n,a.m=scalar(a.momentum),a.accumulations={},a}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulations[r]&&tidy(function(){t.accumulations[r]=zerosLike(a).variable(!1)});var o=n.accumulations[r],i=e[r];tidy(function(){var e,n=t.m.mul(o).add(i);e=t.useNesterov?t.c.mul(i.add(n.mul(t.m))).add(a):t.c.mul(n).add(a),t.accumulations[r].assign(n),a.assign(e)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(SGDOptimizer);SerializationMap.register(MomentumOptimizer);var RMSPropOptimizer=function(e){function t(t,r,n,a,o){void 0===r&&(r=.9),void 0===n&&(n=0),void 0===a&&(a=null),void 0===o&&(o=!1);var i=e.call(this)||this;return i.learningRate=t,i.decay=r,i.momentum=n,i.epsilon=a,i.accumulatedMeanSquares={},i.accumulatedMeanGrads={},i.accumulatedMoments={},i.c=keep(scalar(t)),i.decayScalar=keep(scalar(r)),i.momentumScalar=keep(scalar(n)),i.oneMinusDecay=keep(scalar(1-r)),i.centered=o,null===a&&(a=getOptimizerDefaultEpsilonValue()),i.epsilonScalar=keep(scalar(a)),i}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedMeanSquares[r]&&tidy(function(){t.accumulatedMeanSquares[r]=zerosLike(a).variable(!1)}),null==n.accumulatedMeanGrads[r]&&n.centered&&tidy(function(){t.accumulatedMeanGrads[r]=zerosLike(a).variable(!1)}),null==n.accumulatedMoments[r]&&tidy(function(){t.accumulatedMoments[r]=zerosLike(a).variable(!1)});var o=n.accumulatedMeanSquares[r],i=n.accumulatedMeanGrads[r],s=n.accumulatedMoments[r],u=e[r];tidy(function(){var e=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var n=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(n.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[r].assign(e),t.accumulatedMeanGrads[r].assign(n),t.accumulatedMoments[r].assign(l);var c=a.sub(l);a.assign(c)}else{var p=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(p.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[r].assign(p),t.accumulatedMoments[r].assign(l),c=a.sub(l),a.assign(c)}})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(Optimizer);SerializationMap.register(RMSPropOptimizer);var OptimizerConstructors=function(){function e(){}return e.sgd=function(e){return new SGDOptimizer(e)},e.momentum=function(e,t,r){return void 0===r&&(r=!1),new MomentumOptimizer(e,t,r)},e.rmsprop=function(e,t,r,n,a){return void 0===t&&(t=.9),void 0===r&&(r=0),void 0===n&&(n=null),void 0===a&&(a=!1),new RMSPropOptimizer(e,t,r,n,a)},e.adam=function(e,t,r,n){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===r&&(r=.999),void 0===n&&(n=null),new AdamOptimizer(e,t,r,n)},e.adadelta=function(e,t,r){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===r&&(r=null),new AdadeltaOptimizer(e,t,r)},e.adamax=function(e,t,r,n,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===r&&(r=.999),void 0===n&&(n=null),void 0===a&&(a=0),new AdamaxOptimizer(e,t,r,n,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new AdagradOptimizer(e,t)},__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"sgd",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"momentum",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"rmsprop",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adam",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adadelta",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adamax",null),__decorate([doc({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adagrad",null),e}(),train={sgd:OptimizerConstructors.sgd,momentum:OptimizerConstructors.momentum,adadelta:OptimizerConstructors.adadelta,adagrad:OptimizerConstructors.adagrad,rmsprop:OptimizerConstructors.rmsprop,adamax:OptimizerConstructors.adamax,adam:OptimizerConstructors.adam},setBackend=Environment.setBackend,getBackend=Environment.getBackend,disposeVariables=Environment.disposeVariables,memory=Environment.memory,nextFrame=BrowserUtil.nextFrame;setOpHandler(ops);var extendStatics$1=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};function __extends$1(e,t){function r(){this.constructor=e}extendStatics$1(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=0;s--)(a=e[s])&&(i=(o<3?a(i):o>3?a(t,r,i):a(t,r))||i);return o>3&&i&&Object.defineProperty(t,r,i),i}function __awaiter$1(e,t,r,n){return new(r||(r=Promise))(function(a,o){function i(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){e.done?a(e.value):new r(function(t){t(e.value)}).then(i,s)}u((n=n.apply(e,t||[])).next())})}function __generator$1(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=n[2&o[0]?"return":o[0]?"throw":"next"])&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[0,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]t?1:0}function reverseNumberCompare(e,t){return-1*numberCompare(e,t)}function stringToDType(e){switch(e){case"float32":return"float32";default:throw new ValueError("Invalid dtype: "+e)}}function unique(e){if(null==e)return e;for(var t=[],r=0,n=e;r=0),assert$1(n>=r),Array.isArray(e)&&e.length>=r&&e.length<=n&&e.every(function(e){return typeof e===t})}function calcL2Norms(e,t){return tidy(function(){return sqrt(sum(mulStrict(e,e),t,!0))})}var Constraint=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.getConfig=function(){return{}},__decorate$1([doc({heading:"Constraints",subheading:"Classes",namespace:"constraints"})],t)}(serialization.Serializable),MaxNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultMaxValue=2,r.defaultAxis=0,r.maxValue=null!=t.maxValue?t.maxValue:r.defaultMaxValue,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){var r=calcL2Norms(e,t.axis),n=clipByValue(r,0,t.maxValue);return mul(e,div(n,add(getScalar(epsilon()),r)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(Constraint);serialization.SerializationMap.register(MaxNorm);var UnitNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultAxis=0,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){return div(e,add(getScalar(epsilon()),calcL2Norms(e,t.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(Constraint);serialization.SerializationMap.register(UnitNorm);var NonNeg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return relu(e)},t.className="NonNeg",t}(Constraint);serialization.SerializationMap.register(NonNeg);var MinMaxNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultMinValue=0,r.defaultMaxValue=1,r.defaultRate=1,r.defaultAxis=0,r.minValue=null!=t.minValue?t.minValue:r.defaultMinValue,r.maxValue=null!=t.maxValue?t.maxValue:r.defaultMaxValue,r.rate=null!=t.rate?t.rate:r.defaultRate,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){var r=calcL2Norms(e,t.axis),n=add(mul(getScalar(t.rate),clipByValue(r,t.minValue,t.maxValue)),mul(getScalar(1-t.rate),r));return mul(e,div(n,add(getScalar(epsilon()),r)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(Constraint);serialization.SerializationMap.register(MinMaxNorm);var CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function serializeConstraint(e){return serializeKerasObject(e)}function deserializeConstraint(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"constraint")}function getConstraint(e){return null==e?null:"string"==typeof e?deserializeConstraint({className:e in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP?CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e,config:{}}):e instanceof Constraint?e:deserializeConstraint(e)}var nameMap=new Map,VALID_DATA_FORMAT_VALUES=["channelsFirst","channelsLast"];function checkDataFormat(e){checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES,"DataFormat",e)}var VALID_PADDING_MODE_VALUES=["valid","same","causal"];function checkPaddingMode(e){checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES,"PaddingMode",e)}var VALID_POOL_MODE_VALUES=["max","avg"];function checkPoolMode(e){checkStringTypeUnionValue(VALID_POOL_MODE_VALUES,"PoolMode",e)}var _nameScopeStack=[],_nameScopeDivider="/";function nameScope(e,t){_nameScopeStack.push(e);try{var r=t();return _nameScopeStack.pop(),r}catch(e){throw _nameScopeStack.pop(),e}}function currentNameScopePrefix(){return 0===_nameScopeStack.length?"":_nameScopeStack.join(_nameScopeDivider)+_nameScopeDivider}function getScopedTensorName(e){if(!isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");return currentNameScopePrefix()+e}function getUniqueTensorName(e){if(!isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");nameMap.has(e)||nameMap.set(e,0);var t=nameMap.get(e);if(nameMap.set(e,nameMap.get(e)+1),t>0){var r=e+"_"+t;return nameMap.set(r,1),r}return e}var tensorNameRegex=new RegExp(/^[A-Za-z][A-Za-z0-9\._\/]*$/);function isValidTensorName(e){return!!e.match(tensorNameRegex)}function deserialize(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"layer")}function isArrayItemInputOrOutputName(e,t,r){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof r}function convertPythonicToTs(e,t){if(null===e)return null;if("string"==typeof e)return toCamelCase(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var r=[],n=e.length,a=0;a1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" is not connected, no input to return.");return singletonOrArray(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return singletonOrArray(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this._trainableWeights:[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.assertInputCompatibility=function(e){if(e=toList(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=toList(this.inputSpec);if(e.length!==t.length)throw new ValueError("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var r=0;r=0?i[u]:i[i.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new ValueError("Input "+r+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+i+".")}}if(null!=a.shape)for(var p=0;p0&&Array.isArray(f[0])?f.map(function(n,a){return new SymbolicTensor(g,n,r,toList(e),t,r.name,a)}):new SymbolicTensor(g,f,r,toList(e),t,r.name),r.addInboundNode(e,m,null,null,h,f,t),null!=r.activityRegularizer)throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new AttributeError("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,r=this.inboundNodes;t1 nodes"),assert$1(0===l,"input layer has >1 tensors"),n.inputLayers.push(s),n.inputLayersNodeIndices.push(u),n.inputLayersTensorIndices.push(l);n.inputNames=[],n.outputNames=[],n.feedInputShapes=[],n.feedInputNames=[],n.feedOutputNames=[];for(var d=0;d=0;)a.splice(a.indexOf(u),1);x.push(u)}},S=[],T=[],N=0,E=n.outputs;Nn?1:0});for(var U=0,W=$;U0)throw new ValueError("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],t=0,r=this.layers;t1)for(var s=0,u=i;s0)){for(var h=[],f=0;f0&&e.apply(singletonOrArray(o),n)}function i(e){var n=e.name,o=deserialize(e,null!=t.customObjects?t.customObjects:{});r[n]=o;for(var i=0,s=e.inboundNodes;i0)&&(t=e.sourceLayer,r=e.nodeIndex),0===t.inboundNodes.length)return[e];var n=t.inboundNodes[r];if(0===n.inboundLayers.length)return n.inputTensors;for(var a=[],o=0;o0)throw new ValueError(p.length+" of "+n+" weights are not set: "+p);batchSetValue(l)}function loadWeightsFromJson(e,t,r){void 0===r&&(r=!1);for(var n=e.keras_version,a=e.backend,o=t.map(function(e){return e.name}),i={},s=0,u=t;s1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}n.push.apply(n,s)}if(t)for(var u=0,l=e.layers;u0&&(n=n.slice(0,n.length-1)+" "),n=(n+=e[a]).slice(0,t[a]),n+=" ".repeat(t[a]-n.length);r(n)}function printLayerSummary(e,t,r){var n;try{n=JSON.stringify(e.outputShape)}catch(e){n="multiple"}printRow([e.name+" ("+e.getClassName()+")",n,e.countParams().toString()],t,r)}function printLayerSummaryWithConnections(e,t,r,n){var a;try{a=JSON.stringify(e.outputShape)}catch(e){a="multiple"}for(var o=[],i=0,s=e.inboundNodes;i0&&-1===r.indexOf(u)))for(var l=0;l0)o=!0;else if(isDataDict(e)){for(var i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new ValueError("Error when checking model "+a+" expected no data, but got "+e)}return[]}if(null==e)return t.map(function(e){return null});var s;if(isDataDict(e)){e=e,s=[];for(var u=0,l=t;u1)throw new ValueError("The model "+a+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e]}for(var p=0;p=0&&f!==m)throw new ValueError("Error when checking "+a+": expected "+t[p]+" to have shape ["+r[p]+"], but got array with shape ["+d.shape+"].")}}return s}function checkArrayLengths(e,t,r){var n=unique(e.map(function(e){return e.shape[0]}));n.sort();var a=unique(t.map(function(e){return e.shape[0]}));if(a.sort(),n.length>1)throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(a.length>1)throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(n.length>0&&a.length>0&&!util.arraysEqual(n,a))throw new ValueError("Input Tensors should have the same number of samples as target Tensors. Found "+n[0]+" input sample(s) and "+a[0]+" target sample(s).")}function checkLossAndTargetCompatibility(e,t,r){for(var n=[meanSquaredError,binaryCrossentropy,categoricalCrossentropy],a=0;a=e&&(a=e),r.push([n,a]),n=a;return r}function sliceArrays(e,t,r){return null==e?[null]:Array.isArray(e)?e.map(function(e){return sliceAlongFirstAxis(e,t,r-t)}):sliceAlongFirstAxis(e,t,r-t)}function sliceArraysByIndices(e,t){return tidy(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return sliceArraysByIndices(e,t)}):gather$1(e,"int32"===t.dtype?t:t.toInt())})}function checkInputData(e,t,r,n,a){var o;if(void 0===n&&(n=!0),void 0===a&&(a=""),Array.isArray(e)){if(e.length!==t.length)throw new ValueError("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+t.length+" Tensor(s), but instead got "+e.length+" Tensors(s).");o=e}else{if(t.length>1)throw new ValueError("The model expects "+t.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");o=[e]}if(null!=r)for(var i=0;i1&&(t.metricsTensors.push([r,e]),t.metricsNames.push(t.outputNames[e]+"_loss"))}});var p=collectMetrics(e.metrics,this.outputNames);nameScope("metric",function(){for(var e=function(e){if(-1!==c.indexOf(e))return"continue";!function(r){for(var n,a,o,i=function(r){if(-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){var i=t.internalOutputShapes[e];1===i[i.length-1]||t.lossFunctions[e]===binaryCrossentropy?-1!==["accuracy","acc"].indexOf(r)?a=binaryAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=binaryCrossentropy$1):t.lossFunctions[e]===sparseCategoricalCrossentropy?-1!==["accuracy","acc"].indexOf(r)?a=sparseCategoricalAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=sparseCategoricalCrossentropy$1):-1!==["accuracy","acc"].indexOf(r)?a=categoricalAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=categoricalCrossentropy$1);var s=void 0;-1!==["accuracy","acc"].indexOf(r)?s="acc":-1!==["crossentropy","ce"].indexOf(r)&&(s="ce"),o=a,n=""+s}else{var u=get$1(r);o=u,n=""+r}var l;nameScope(n,function(){l=o}),function(e,r,n){t.outputNames.length>1&&(r=t.outputNames[e]+"_"+r),t.metricsNames.push(r),t.metricsTensors.push([n,e])}(e,n,l)},s=0,u=p[e];s0){var c=[];throw t.forEach(function(t,r){null==t&&c.push(e[r])}),new ValueError("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return t},t.prototype.predictLoop=function(e,t,r){var n=this;return void 0===t&&(t=32),void 0===r&&(r=!1),tidy(function(){var a=n.checkNumSamples(e);if(r)throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");for(var o=makeBatches(a,t),i=[],s=function(t){var r=tidy(function(){var r=o[t][0],a=o[t][1],i=sliceArrays(e,r,a),s=[];if(Array.isArray(i))for(var u=0;u0&&e[0].shape[0]%n!=0)throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+n+". Found: "+e[0].shape[0]+" sample(s).");return[e,t,null]},t.prototype.fitLoop=function(e,t,r,n,a,o,i,s,u,l,c,p,d,h){return void 0===p&&(p=0),__awaiter$1(this,void 0,void 0,function(){var f,m,g,y,v,b,x,w=this;return __generator$1(this,function(S){switch(S.label){case 0:if(null==n&&(n=32),null==a&&(a=1),null==l&&(l=!0),null==p&&(p=0),f=!1,null!=s&&null!=u&&(f=!0),null!=h&&(f=!0,null==d))throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");if(null!=(m=this.checkNumSamples(t,n,d,"steps_per_epoch"))&&(g=range$1(0,m)),this.history=new History,i=(i=null==i?[new BaseLogger]:[new BaseLogger].concat(i)).concat([this.history]),o>0)throw new NotImplementedError("Verbose mode is not implemented yet.");return(y=new CallbackList(i)).setModel(this),y.setParams({epochs:a,steps:d,verbose:o,doValidation:f,metrics:c}),[4,y.onTrainBegin()];case 1:S.sent(),this.stopTraining=!1,v=function(a){var o,i,c,p,h;return __generator$1(this,function(v){switch(v.label){case 0:return[4,y.onEpochBegin(a)];case 1:if(v.sent(),o={},null==d)return[3,2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===l)throw new NotImplementedError("batch shuffling is not implemneted yet");l&&util.shuffle(g),i=tensor1d(g),c=makeBatches(m,n),p=function(a){var l;return __generator$1(this,function(p){switch(p.label){case 0:return l={},[4,y.onBatchBegin(a,l)];case 1:return p.sent(),tidy(function(){var p=c[a][0],d=c[a][1],h=sliceAlongFirstAxis(i,p,d-p);l.batch=a,l.size=d-p;for(var m=sliceArraysByIndices(t,h),g=e(m),y=0;y1&&(a+="_"+count(e.slice(0,r),n)),t.push(a)}return t},t.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(t){return tidy(function(){for(var r,n=[],a=t.slice(0,e.inputs.length),o=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),i=[],s=0;s0){if(s=!0,2!==r.validationData.length)throw 3===r.validationData.length?new NotImplementedError("validationData including sample weights is not supported yet."):new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");u=r.validationData[0],l=r.validationData[1],d=this.standardizeUserData(u,l,!0,n),u=d[0],l=d[1],c=u.concat(l)}else null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(s=!0,h=Math.floor(o[0].shape[0]*(1-r.validationSplit)),f=o[0].shape[0],u=sliceArrays(o,h,f),o=sliceArrays(o,0,h),l=sliceArrays(i,h,f),i=sliceArrays(i,0,h),p=!0,c=u.concat(l)):null!=r.validationSteps&&(s=!0);return m=o.concat(i),this.checkTrainableWeightsConsistency(),g=function(e){var t=e.slice(0,S.inputs.length),r=e.slice(S.inputs.length,S.inputs.length+S.outputs.length),n=[],a=S.collectedTrainableWeights.map(function(e){return e.read()});return[S.optimizer.minimize(function(){for(var e=[],a=0;a1)throw new ValueError("Found more than one ("+r.length+") save handlers for URL '"+e+"'");e=r[0]}if(null==e.save)throw new ValueError("Model.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,io.encodeWeights(this.getNamedWeights(t))];case 1:return n=s.sent(),a=!1,o=null,i=this.toJSON(o,a),[2,e.save({modelTopology:i,weightData:n.data,weightSpecs:n.specs})]}})})},t.className="Model",__decorate$1([doc({heading:"Models",subheading:"Classes"})],t.prototype,"summary",null),__decorate$1([doc({heading:"Models",subheading:"Classes",configParamIndices:[0]})],t.prototype,"compile",null),__decorate$1([doc({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"evaluate",null),__decorate$1([doc({heading:"Models",subheading:"Classes",configParamIndices:[1]})],t.prototype,"predict",null),__decorate$1([doc({heading:"Models",subheading:"Classes"})],t.prototype,"predictOnBatch",null),__decorate$1([doc({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"fit",null),__decorate$1([doc({heading:"Models",subheading:"Classes",configParamIndices:[1]})],t.prototype,"save",null),__decorate$1([doc({heading:"Models",subheading:"Classes"})],t)}(Container);serialization.SerializationMap.register(Model);var VALID_FAN_MODE_VALUES=["fanIn","fanOut","fanAvg"];function checkFanMode(e){checkStringTypeUnionValue(VALID_FAN_MODE_VALUES,"FanMode",e)}var VALID_DISTRIBUTION_VALUES=["normal","uniform"];function checkDistribution(e){checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES,"Distribution",e)}var Initializer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},__decorate$1([doc({heading:"Initializers",subheading:"Classes",namespace:"initializers"})],t)}(serialization.Serializable),Zeros=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return zeros(e,t)},t.className="Zeros",t}(Initializer);serialization.SerializationMap.register(Zeros);var Ones=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return ones(e,t)},t.className="Ones",t}(Initializer);serialization.SerializationMap.register(Ones);var Constant=function(e){function t(t){var r=e.call(this)||this;return r.value=t.value,r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){return mul(scalar(r.value),ones(e,t))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(Initializer);serialization.SerializationMap.register(Constant);var RandomUniform=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MINVAL=-.05,r.DEFAULT_MAXVAL=.05,r.minval=t.minval||r.DEFAULT_MINVAL,r.maxval=t.maxval||r.DEFAULT_MAXVAL,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){return randomUniform(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(Initializer);serialization.SerializationMap.register(RandomUniform);var RandomNormal=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MEAN=0,r.DEFAULT_STDDEV=.05,r.mean=t.mean||r.DEFAULT_MEAN,r.stddev=t.stddev||r.DEFAULT_STDDEV,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){if("bool"===t)throw new NotImplementedError("randomNormal does not support dType bool.");return randomNormal$1(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(Initializer);serialization.SerializationMap.register(RandomNormal);var TruncatedNormal=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MEAN=0,r.DEFAULT_STDDEV=.05,r.mean=t.mean||r.DEFAULT_MEAN,r.stddev=t.stddev||r.DEFAULT_STDDEV,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){if("bool"===t)throw new NotImplementedError("truncatedNormal does not support dType bool.");return truncatedNormal(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(Initializer);serialization.SerializationMap.register(TruncatedNormal);var Identity=function(e){function t(t){var r=e.call(this)||this;return r.gain=null!=t.gain?scalar(t.gain):getScalar(1),r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){if(2!==e.length||e[0]!==e[1])throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.");return mul(r.gain,eye(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain.get()}},t.className="Identity",t}(Initializer);function computeFans(e,t){var r,n;if(void 0===t&&(t="channelsLast"),checkDataFormat(t),2===e.length)r=e[0],n=e[1];else if(-1!==[3,4,5].indexOf(e.length))if("channelsFirst"===t){var a=arrayProd(e,2);r=e[1]*a,n=e[0]*a}else"channelsLast"===t&&(a=arrayProd(e,0,e.length-2),r=e[e.length-2]*a,n=e[e.length-1]*a);else{var o=arrayProd(e);r=Math.sqrt(o),n=Math.sqrt(o)}return[r,n]}serialization.SerializationMap.register(Identity);var VarianceScaling=function(e){function t(t){var r=e.call(this)||this;if(t.scale<0)throw new ValueError("scale must be a positive float. Got: "+t.scale);return r.scale=null==t.scale?1:t.scale,r.mode=t.mode,checkFanMode(r.mode),r.distribution=t.distribution,checkDistribution(r.distribution),r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=computeFans(e),n=r[0],a=r[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,n):"fanOut"===this.mode?o/=Math.max(1,a):o/=Math.max(1,(n+a)/2),"normal"===this.distribution){var i=Math.sqrt(o);if("bool"===t)throw new NotImplementedError(this.getClassName()+" does not support dType bool.");return truncatedNormal(e,0,i,t,this.seed)}var s=Math.sqrt(3*o);return randomUniform(e,-s,s,t)},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(Initializer);serialization.SerializationMap.register(VarianceScaling);var GlorotUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t}(VarianceScaling),GlorotNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t}(VarianceScaling),HeNormal=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t}(VarianceScaling),LeCunNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t}(VarianceScaling),Orthogonal=function(e){function t(t){var r=e.call(this)||this;if(r.DEFAULT_GAIN=1,r.gain=null==t.gain?r.DEFAULT_GAIN:t.gain,r.seed=t.seed,null!=r.seed)throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){if(2!==e.length)throw new NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=randomNormal$1(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),n=linalg.gramSchmidt(t);return e[0]>e[1]&&(n=n.transpose()),mul(getScalar(r.gain),n)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(Initializer);serialization.SerializationMap.register(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function deserializeInitializer(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"initializer")}function serializeInitializer(e){return serializeKerasObject(e)}function getInitializer(e){if("string"==typeof e){var t=e in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e;return"GlorotUniform"===t?new GlorotUniform:"GlorotNormal"===t?new GlorotNormal:"HeNormal"===t?new HeNormal:"LeCunNormal"===t?new LeCunNormal:deserializeInitializer({className:t,config:{}})}return e instanceof Initializer?e:deserializeInitializer(e)}var Activation=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.getConfig=function(){return{}},t}(serialization.Serializable),Elu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=1),elu$1(e,t)},t.className="elu",t}(Activation);serialization.SerializationMap.register(Elu);var Selu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return selu(e)},t.className="selu",t}(Activation);serialization.SerializationMap.register(Selu);var Relu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return relu(e)},t.className="relu",t}(Activation);serialization.SerializationMap.register(Relu);var Relu6=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return tidy(function(){return minimum(getScalar(6),relu(e))})},t.className="relu6",t}(Activation);serialization.SerializationMap.register(Relu6);var Linear=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return e},t.className="linear",t}(Activation);serialization.SerializationMap.register(Linear);var Sigmoid=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return sigmoid(e)},t.className="sigmoid",t}(Activation);serialization.SerializationMap.register(Sigmoid);var HardSigmoid=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return hardSigmoid(e)},t.className="hardSigmoid",t}(Activation);serialization.SerializationMap.register(HardSigmoid);var Softplus=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return softplus(e)},t.className="softplus",t}(Activation);serialization.SerializationMap.register(Softplus);var Softsign=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return softsign(e)},t.className="softsign",t}(Activation);serialization.SerializationMap.register(Softsign);var Tanh=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return tanh$1(e)},t.className="tanh",t}(Activation);serialization.SerializationMap.register(Tanh);var Softmax=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=-1),softmax(e,t)},t.className="softmax",t}(Activation);function serializeActivation(e){return e.getClassName()}function deserializeActivation(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"activation")}function getActivation(e){return null==e?deserializeActivation({className:"linear",config:{}}):"string"==typeof e?deserializeActivation({className:e,config:{}}):e instanceof Activation?e:deserializeActivation(e)}serialization.SerializationMap.register(Softmax);var LeakyReLU=function(e){function t(t){var r=e.call(this,null==t?{}:t)||this;return r.DEFAULT_ALPHA=.3,null==t&&(t={}),r.alpha=null==t.alpha?r.DEFAULT_ALPHA:t.alpha,r}return __extends$1(t,e),t.prototype.call=function(e,t){var r=getExactlyOneTensor(e);return leakyRelu(r,this.alpha)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={alpha:this.alpha},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="LeakyReLU",t}(Layer);serialization.SerializationMap.register(LeakyReLU);var ELU$1=function(e){function t(t){var r=e.call(this,null==t?{}:t)||this;if(r.DEFAULT_ALPHA=1,null==t&&(t={}),null!=t.alpha&&t.alpha!==r.DEFAULT_ALPHA)throw new NotImplementedError("Non-default alpha value ("+t.alpha+") is not supported by the ELU layer yet.");return r.alpha=null==t.alpha?r.DEFAULT_ALPHA:t.alpha,r}return __extends$1(t,e),t.prototype.call=function(e,t){var r=getExactlyOneTensor(e);return elu(r)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={alpha:this.alpha},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="ELU",t}(Layer);serialization.SerializationMap.register(ELU$1);var ThresholdedReLU=function(e){function t(t){var r=e.call(this,null==t?{}:t)||this;return r.DEFAULT_THETA=1,null==t&&(t={}),r.theta=null==t.theta?r.DEFAULT_THETA:t.theta,r.thetaTensor=getScalar(r.theta),r}return __extends$1(t,e),t.prototype.call=function(e,t){var r=getExactlyOneTensor(e);return r.mul(cast$1(r.greater(this.thetaTensor),"float32"))},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={theta:this.theta},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="ThresholdedReLU",t}(Layer);serialization.SerializationMap.register(ThresholdedReLU);var Softmax$1=function(e){function t(t){var r=e.call(this,null==t?{}:t)||this;return r.DEFAULT_AXIS=1,null==t&&(t={}),r.softmax=(new Softmax).apply,r.axis=null==t.axis?r.DEFAULT_AXIS:t.axis,r}return __extends$1(t,e),t.prototype.call=function(e,t){var r=getExactlyOneTensor(e);return this.softmax(r,this.axis)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={axis:this.axis},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="Softmax",t}(Layer);serialization.SerializationMap.register(Softmax$1);var Regularizer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t}(serialization.Serializable),L1L2=function(e){function t(t){var r=e.call(this)||this,n=null==t||null==t.l1?.01:t.l1,a=null==t||null==t.l2?.01:t.l2;return r.hasL1=0!==n,r.hasL2=0!==a,r.l1=getScalar(n),r.l2=getScalar(a),r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){var r=zeros([1]);return t.hasL1&&(r=add(r,sum(mul(t.l1,abs(e))))),t.hasL2&&(r=add(r,sum(mul(t.l2,square$1(e))))),r.asScalar()})},t.prototype.getConfig=function(){return{l1:this.l1.dataSync()[0],l2:this.l2.dataSync()[0]}},t.fromConfig=function(e,t){return new e({l1:t.l1,l2:t.l2})},t.className="L1L2",__decorate$1([doc({heading:"Regularizers",namespace:"regularizers"})],t)}(Regularizer);function l1(e){return new L1L2({l1:null!=e?e.l1:null,l2:0})}function l2(e){return new L1L2({l2:null!=e?e.l2:null,l1:0})}serialization.SerializationMap.register(L1L2);var REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={l1l2:"L1L2"};function serializeRegularizer(e){return serializeKerasObject(e)}function deserializeRegularizer(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"regularizer")}function getRegularizer(e){return null==e?null:"string"==typeof e?deserializeRegularizer({className:e in REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e,config:{}}):e instanceof Regularizer?e:deserializeRegularizer(e)}function normalizeArray(e,t,r){if("number"==typeof e)return pyListRepeat(e,t);if(e.length!==t)throw new ValueError("The "+r+" argument must be a tuple of "+t+" integers. Received: "+e.length+" elements.");for(var n=0;n 0 but got "+JSON.stringify(e.filters))},t}(BaseConv),Conv2D=function(e){function t(r){var n=e.call(this,2,r)||this;return t.verifyConfig(r),n}return __extends$1(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyConfig=function(e){if("number"!=typeof e.kernelSize&&!checkArrayTypeAndLength(e.kernelSize,"number",1,2))throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(Conv);serialization.SerializationMap.register(Conv2D);var Conv2DTranspose=function(e){function t(t){var r=e.call(this,t)||this;if(r.inputSpec=[new InputSpec({ndim:4})],"same"!==r.padding&&"valid"!==r.padding)throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+r.padding);return r}return __extends$1(t,e),t.prototype.build=function(e){if(4!==(e=getExactlyOneShape(e)).length)throw new ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(e));var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");var r,n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new InputSpec({ndim:4,axes:(r={},r[t]=n,r)})],this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);if(4!==t.shape.length)throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var n,a,o=t.shape,i=o[0];"channelsFirst"===r.dataFormat?(n=2,a=3):(n=1,a=2);var s=o[n],u=o[a],l=r.kernelSize[0],c=r.kernelSize[1],p=r.strides[0],d=r.strides[1],h=[i,deconvLength(s,p,l,r.padding),deconvLength(u,d,c,r.padding),r.filters];"channelsLast"!==r.dataFormat&&(t=transpose(t,[0,2,3,1]));var f=conv2dTranspose(t,r.kernel.read(),h,r.strides,r.padding);return"channelsLast"!==r.dataFormat&&(f=transpose(f,[0,3,1,2])),null!=r.bias&&(f=biasAdd(f,r.bias.read(),r.dataFormat)),null!=r.activation&&(f=r.activation.apply(f)),f})},t.prototype.computeOutputShape=function(e){var t,r,n,a=(e=getExactlyOneShape(e)).slice();"channelsFirst"===this.dataFormat?(t=1,r=2,n=3):(t=3,r=1,n=2);var o=this.kernelSize[0],i=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[t]=this.filters,a[r]=deconvLength(a[r],s,o,this.padding),a[n]=deconvLength(a[n],u,i,this.padding),a},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(Conv2D);serialization.SerializationMap.register(Conv2DTranspose);var SeparableConv=function(e){function t(t,r){var n=e.call(this,t,r)||this;if(n.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",n.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",n.depthwiseKernel=null,n.pointwiseKernel=null,null==r.filters)throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=r.kernelInitializer||null!=r.kernelRegularizer||null!=r.kernelConstraint)throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=r.padding&&"same"!==r.padding&&"valid"!==r.padding)throw new ValueError("SeparableConv"+n.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(r.padding));return n.depthMultiplier=null==r.depthMultiplier?1:r.depthMultiplier,n.depthwiseInitializer=getInitializer(r.depthwiseInitializer||n.DEFAULT_DEPTHWISE_INITIALIZER),n.depthwiseRegularizer=getRegularizer(r.depthwiseRegularizer),n.depthwiseConstraint=getConstraint(r.depthwiseConstraint),n.pointwiseInitializer=getInitializer(r.depthwiseInitializer||n.DEFAULT_POINTWISE_INITIALIZER),n.pointwiseRegularizer=getRegularizer(r.pointwiseRegularizer),n.pointwiseConstraint=getConstraint(r.pointwiseConstraint),n}return __extends$1(t,e),t.prototype.build=function(e){if((e=getExactlyOneShape(e)).length1)throw new ValueError("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var a=null==e[0]?null:e[0].slice(1),o=1;o1){var y=range$1(1,s).concat([0]);t.push(transpose(d,y)),l=!0}else t.push(d)}var v=r.mergeFunction(t),b=v.rank;if(l)if(null==b){var x=v.shape;m=[f=x[x.length-1]].concat(x.slice(0,x.length-1)),v=transpose(v.reshape([-1,f]),[1,0]).reshape(m)}else b>1&&(y=[b-1].concat(range$1(0,b-1)),v=transpose(v,y));return v}return r.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var r=1;r1)throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return tidy(function(){return concatenate(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,r=t[0].slice(),n=this.axis<0?r.length+this.axis:this.axis,a=0,o=t.slice(1);a=0?this.axis:this.axis+e.length,r=e[t];if(null==r)throw new ValueError("Axis "+t+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new InputSpec({ndim:e.length,axes:(n={},n[t]=r,n)})];var n,a=[r];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){var n=null!=t.training&&t.training,a=getExactlyOneTensor(e),o=a.shape,i=o.length,s=range$1(0,i),u=r.axis>=0?r.axis:r.axis+i;s.splice(u,1);var l=pyListRepeat(1,i);l[u]=o[u];var c=s.slice();c.sort();var p=!util.arraysEqual(c,range$1(0,i).slice(0,i-1));if(!n)return function(){if(p){var e=r.movingMean.read().reshape(l),t=r.movingVariance.read().reshape(l),n=r.center?r.beta.read().reshape(l):null,o=r.scale?r.gamma.read().reshape(l):null;return batchNormalization$1(a,e,t,n,o,r.epsilon)}return batchNormalization$1(a,r.movingMean.read(),r.movingVariance.read(),null==r.beta?null:r.beta.read(),null==r.gamma?null:r.gamma.read(),r.epsilon)}();var d=normalizeBatchInTraining(a,r.gamma.read(),r.beta.read(),s,r.epsilon),h=d[0],f=d[1],m=d[2],g=arrayProd(s.map(function(e){return a.shape[e]})),y=m.mul(getScalar(g/(g-(1+r.epsilon))));return function(){r.stepCount++;var e=movingAverage(r.movingMean.read(),f,r.momentum,r.stepCount);r.movingMean.write(e);var t=movingAverage(r.movingVariance.read(),y,r.momentum,r.stepCount);r.movingVariance.write(t)}(),h})},t.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:serializeInitializer(this.betaInitializer),gammaInitializer:serializeInitializer(this.gammaInitializer),movingMeanInitializer:serializeInitializer(this.movingMeanInitializer),movingVarianceInitializer:serializeInitializer(this.movingVarianceInitializer),betaRegularizer:serializeRegularizer(this.betaRegularizer),gammaRegularizer:serializeRegularizer(this.gammaRegularizer),betaConstraint:serializeConstraint(this.betaConstraint),gammaConstraint:serializeConstraint(this.gammaConstraint)},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="BatchNormalization",t}(Layer);function spatial2dPadding(e,t,r){return tidy(function(){if(4!==e.rank)throw new ValueError("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r=imageDataFormat()),"channelsLast"!==r&&"channelsFirst"!==r)throw new ValueError("Unknown data format: "+r+". Supported data formats are 'channelsLast' and 'channelsFirst.");var n;return n="channelsFirst"===r?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],pad(e,n)})}serialization.SerializationMap.register(BatchNormalization);var ZeroPadding2D=function(e){function t(t){var r=this;if(null==t&&(t={}),(r=e.call(this,t)||this).dataFormat=null==t.dataFormat?imageDataFormat():t.dataFormat,null==t.padding)r.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)r.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new ValueError("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var n=void 0,a=void 0;if("number"==typeof t.padding[0])n=[t.padding[0],t.padding[0]],a=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new ValueError("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(n=t.padding[0],2!==t.padding[1].length)throw new ValueError("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");a=t.padding[1]}r.padding=[n,a]}return r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){var t,r;return e=getExactlyOneShape(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,r]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,r,e[3]])},t.prototype.call=function(e,t){var r=this;return tidy(function(){return spatial2dPadding(getExactlyOneTensor(e),r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="ZeroPadding2D",t}(Layer);function pool2d(e,t,r,n,a,o){return tidy(function(){var i;checkDataFormat(a),checkPoolMode(o),checkPaddingMode(n),null==r&&(r=[1,1]),null==n&&(n="valid"),null==a&&(a=imageDataFormat()),null==o&&(o="max"),e=preprocessConv2DInput(e,a);var s="same"===n?"same":"valid";return i="max"===o?maxPool(e,t,r,s):avgPool(e,t,r,s),"channelsFirst"===a&&(i=transpose(i,[0,3,1,2])),i})}serialization.SerializationMap.register(ZeroPadding2D);var Pooling1D=function(e){function t(t){var r=this;if(null==t.poolSize&&(t.poolSize=2),r=e.call(this,t)||this,"number"==typeof t.poolSize)r.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));r.poolSize=t.poolSize}if(null==t.strides)r.strides=r.poolSize;else if("number"==typeof t.strides)r.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));r.strides=t.strides}return r.padding=null==t.padding?"valid":t.padding,checkPaddingMode(r.padding),r.inputSpec=[new InputSpec({ndim:3})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){var t=convOutputLength((e=getExactlyOneShape(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]},t.prototype.call=function(e,t){var r=this;return tidy(function(){r.invokeCallHook(e,t),e=expandDims$1(getExactlyOneTensor(e),2);var n=r.poolingFunction(getExactlyOneTensor(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return squeeze(n,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),MaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"max")},t.className="MaxPooling1D",t}(Pooling1D);serialization.SerializationMap.register(MaxPooling1D);var AveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"avg")},t.className="AveragePooling1D",t}(Pooling1D);serialization.SerializationMap.register(AveragePooling1D);var Pooling2D=function(e){function t(t){var r=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(r=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)r.strides=r.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");r.strides=t.strides}else r.strides=[t.strides,t.strides];return r.padding=null==t.padding?"valid":t.padding,r.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(r.dataFormat),checkPaddingMode(r.padding),r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){e=getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],r="channelsFirst"===this.dataFormat?e[3]:e[2];return t=convOutputLength(t,this.poolSize[0],this.padding,this.strides[0]),r=convOutputLength(r,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,r]:[e[0],t,r,e[3]]},t.prototype.call=function(e,t){var r=this;return tidy(function(){return r.invokeCallHook(e,t),r.poolingFunction(getExactlyOneTensor(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),MaxPooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"max")},t.className="MaxPooling2D",t}(Pooling2D);serialization.SerializationMap.register(MaxPooling2D);var AveragePooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"avg")},t.className="AveragePooling2D",t}(Pooling2D);serialization.SerializationMap.register(AveragePooling2D);var GlobalPooling1D=function(e){function t(t){var r=e.call(this,t)||this;return r.inputSpec=[new InputSpec({ndim:3})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,t){throw new NotImplementedError},t}(Layer),GlobalAveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(e,t){return tidy(function(){var t=getExactlyOneTensor(e);return mean(t,1)})},t.className="GlobalAveragePooling1D",t}(GlobalPooling1D);serialization.SerializationMap.register(GlobalAveragePooling1D);var GlobalMaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(e,t){return tidy(function(){var t=getExactlyOneTensor(e);return max(t,1)})},t.className="GlobalMaxPooling1D",t}(GlobalPooling1D);serialization.SerializationMap.register(GlobalMaxPooling1D);var GlobalPooling2D=function(e){function t(t){var r=e.call(this,t)||this;return r.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(r.dataFormat),r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new NotImplementedError},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),GlobalAveragePooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);return"channelsLast"===r.dataFormat?mean(t,[1,2]):mean(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(GlobalPooling2D);serialization.SerializationMap.register(GlobalAveragePooling2D);var GlobalMaxPooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);return"channelsLast"===r.dataFormat?max(t,[1,2]):max(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(GlobalPooling2D);function rnn(e,t,r,n,a,o,i,s){void 0===n&&(n=!1),void 0===i&&(i=!1);var u=t.shape.length;if(u<3)throw new ValueError("Input should be at least 3D, but is "+u+"D.");var l,c,p=[1,0].concat(range$1(2,u));if(t=transpose(t,p),null!=a)throw new NotImplementedError("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=o)throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),n&&(t=reverse(t,0));for(var d=r,h=t.shape[0],f=0;f1&&(t=e.slice(1,e.length)),e=e[0]}function n(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=n(t),constants:r=n(r)}},t.prototype.apply=function(t,r){var n=null==r?null:r.initialState,a=null==r?null:r.constants;null==r&&(r={});var o=this.standardizeArgs(t,n,a);t=o.inputs,n=o.initialState,a=o.constants;var i=[],s=[];if(null!=n){r.initialState=n,i=i.concat(n),this.stateSpec=[];for(var u=0,l=n;u1?tile$1(r,[1,e]):r}):t.cell.stateSize>1?[tile$1(r,[1,t.cell.stateSize])]:[r]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var r=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:r};var n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="RNN",t}(Layer);serialization.SerializationMap.register(RNN);var RNNCell=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),__decorate$1([doc({heading:"Layers",subheading:"Classes"})],t)}(Layer),SimpleRNNCell=function(e){function t(t){var r=e.call(this,t)||this;return r.DEFAULT_ACTIVATION="tanh",r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_RECURRENT_INITIALIZER="orthogonal",r.DEFAULT_BIAS_INITIALIZER="zeros",r.units=t.units,r.activation=getActivation(null==t.activation?r.DEFAULT_ACTIVATION:t.activation),r.useBias=null==t.useBias||t.useBias,r.kernelInitializer=getInitializer(t.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.recurrentInitializer=getInitializer(t.recurrentInitializer||r.DEFAULT_RECURRENT_INITIALIZER),r.biasInitializer=getInitializer(t.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.kernelRegularizer=getRegularizer(t.kernelRegularizer),r.recurrentRegularizer=getRegularizer(t.recurrentRegularizer),r.biasRegularizer=getRegularizer(t.biasRegularizer),r.kernelConstraint=getConstraint(t.kernelConstraint),r.recurrentConstraint=getConstraint(t.recurrentConstraint),r.biasConstraint=getConstraint(t.biasConstraint),r.dropout=min$1([1,max$1([0,null==t.dropout?0:t.dropout])]),r.recurrentDropout=min$1([1,max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),r.stateSize=r.units,r}return __extends$1(t,e),t.prototype.build=function(e){e=getExactlyOneShape(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){if(2!==(e=e).length)throw new ValueError("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var t=e[1];if(e=e[0],0!==r.dropout||0!==r.recurrentDropout)throw new NotImplementedError("Dropout is not implemented for SimpleRNNCell yet");var n=dot$1(e,r.kernel.read());null!=r.bias&&(n=biasAdd(n,r.bias.read()));var a=add(n,dot$1(t,r.recurrentKernel.read()));return null!=r.activation&&(a=r.activation.apply(a)),[a,a]})},t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="SimpleRNNCell",t}(RNNCell);serialization.SerializationMap.register(SimpleRNNCell);var SimpleRNN=function(e){function t(t){return t.cell=new SimpleRNNCell(t),e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(t,r){var n=this;return tidy(function(){var a=null==r?null:r.mask,o=null==r?null:r.training,i=null==r?null:r.initialState;return e.prototype.call.call(n,t,{mask:a,training:o,initialState:i})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},r=e.prototype.getConfig.call(this);return delete r.cell,Object.assign(t,r),t},t.className="SimpleRNN",t}(RNN);serialization.SerializationMap.register(SimpleRNN);var GRUCell=function(e){function t(t){var r=e.call(this,t)||this;return r.DEFAULT_ACTIVATION="tanh",r.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_RECURRENT_INITIALIZER="orthogonal",r.DEFAULT_BIAS_INITIALIZER="zeros",r.units=t.units,r.activation=getActivation(void 0===t.activation?r.DEFAULT_ACTIVATION:t.activation),r.recurrentActivation=getActivation(void 0===t.recurrentActivation?r.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),r.useBias=null==t.useBias||t.useBias,r.kernelInitializer=getInitializer(t.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.recurrentInitializer=getInitializer(t.recurrentInitializer||r.DEFAULT_RECURRENT_INITIALIZER),r.biasInitializer=getInitializer(t.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.kernelRegularizer=getRegularizer(t.kernelRegularizer),r.recurrentRegularizer=getRegularizer(t.recurrentRegularizer),r.biasRegularizer=getRegularizer(t.biasRegularizer),r.kernelConstraint=getConstraint(t.kernelConstraint),r.recurrentConstraint=getConstraint(t.recurrentConstraint),r.biasConstraint=getConstraint(t.biasConstraint),r.dropout=min$1([1,max$1([0,null==t.dropout?0:t.dropout])]),r.recurrentDropout=min$1([1,max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),r.implementation=t.implementation,r.stateSize=r.units,r}return __extends$1(t,e),t.prototype.build=function(e){var t=(e=getExactlyOneShape(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){if(0!==r.dropout||0!==r.recurrentDropout)throw new NotImplementedError("Dropout is not implemented for GRUCell yet");if(2!==(e=e).length)throw new ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got "+e.length+".");var t,n,a,o=e[1];if(e=e[0],1===r.implementation){var i=sliceAlongLastAxis(r.kernel.read(),0,r.units),s=sliceAlongLastAxis(r.kernel.read(),r.units,r.units),u=sliceAlongLastAxis(r.kernel.read(),2*r.units,r.units),l=sliceAlongLastAxis(r.recurrentKernel.read(),0,r.units),c=sliceAlongLastAxis(r.recurrentKernel.read(),r.units,r.units),p=sliceAlongLastAxis(r.recurrentKernel.read(),2*r.units,r.units),d=e,h=e,f=dot$1(e,i),m=dot$1(d,s),g=dot$1(h,u);if(r.useBias){var y=sliceAlongFirstAxis(r.bias.read(),0,r.units),v=sliceAlongFirstAxis(r.bias.read(),r.units,r.units),b=sliceAlongFirstAxis(r.bias.read(),2*r.units,r.units);f=biasAdd(f,y),m=biasAdd(m,v),g=biasAdd(g,b)}var x=o,w=o,S=o;t=r.recurrentActivation.apply(add(f,dot$1(x,l))),n=r.recurrentActivation.apply(add(m,dot$1(w,c))),a=r.activation.apply(add(g,dot$1(mul(n,S),p)))}else{var T=dot$1(e,r.kernel.read());r.useBias&&(T=biasAdd(T,r.bias.read()));var N=dot$1(o,sliceAlongLastAxis(r.recurrentKernel.read(),0,2*r.units)),E=(f=sliceAlongLastAxis(T,0,r.units),m=sliceAlongLastAxis(T,r.units,r.units),sliceAlongLastAxis(N,0,r.units)),_=sliceAlongLastAxis(N,r.units,r.units);t=r.recurrentActivation.apply(add(f,E)),n=r.recurrentActivation.apply(add(m,_)),g=sliceAlongLastAxis(T,2*r.units,r.units);var A=dot$1(mul(n,o),sliceAlongLastAxis(r.recurrentKernel.read(),2*r.units,r.units));a=r.activation.apply(add(g,A))}var I=add(mul(t,o),mul(add(getScalar(1),neg(t)),a));return[I,I]})},t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="GRUCell",t}(RNNCell);serialization.SerializationMap.register(GRUCell);var GRU=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new GRUCell(t),e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(t,r){var n=this;return tidy(function(){var a=null==r?null:r.mask,o=null==r?null:r.training,i=null==r?null:r.initialState;return e.prototype.call.call(n,t,{mask:a,training:o,initialState:i})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},r=e.prototype.getConfig.call(this);return delete r.cell,Object.assign(t,r),t},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)},t.className="GRU",t}(RNN);serialization.SerializationMap.register(GRU);var LSTMCell=function(e){function t(t){var r=e.call(this,t)||this;return r.DEFAULT_ACTIVATION="tanh",r.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_RECURRENT_INITIALIZER="orthogonal",r.DEFAULT_BIAS_INITIALIZER="zeros",r.units=t.units,r.activation=getActivation(void 0===t.activation?r.DEFAULT_ACTIVATION:t.activation),r.recurrentActivation=getActivation(void 0===t.recurrentActivation?r.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),r.useBias=null==t.useBias||t.useBias,r.kernelInitializer=getInitializer(t.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.recurrentInitializer=getInitializer(t.recurrentInitializer||r.DEFAULT_RECURRENT_INITIALIZER),r.biasInitializer=getInitializer(t.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.unitForgetBias=t.unitForgetBias,r.kernelRegularizer=getRegularizer(t.kernelRegularizer),r.recurrentRegularizer=getRegularizer(t.recurrentRegularizer),r.biasRegularizer=getRegularizer(t.biasRegularizer),r.kernelConstraint=getConstraint(t.kernelConstraint),r.recurrentConstraint=getConstraint(t.recurrentConstraint),r.biasConstraint=getConstraint(t.biasConstraint),r.dropout=min$1([1,max$1([0,null==t.dropout?0:t.dropout])]),r.recurrentDropout=min$1([1,max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),r.implementation=t.implementation,r.stateSize=[r.units,r.units],r}return __extends$1(t,e),t.prototype.build=function(e){var t,r,n=(e=getExactlyOneShape(e))[e.length-1];if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var a=this.biasInitializer,o=this.units;t=new((r=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=a.apply([o]),n=(new Ones).apply([o]),i=a.apply([2*o]);return concatAlongFirstAxis(concatAlongFirstAxis(r,n),i)},t}(Initializer)).className="CustomInit",r)}else t=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,t,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){if(0!==r.dropout||0!==r.recurrentDropout)throw new NotImplementedError("Dropout is not implemented for LSTMCell yet");if(3!==(e=e).length)throw new ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got "+e.length+".");var t,n,a,o,i=e[1],s=e[2];if(e=e[0],1===r.implementation){var u=sliceAlongLastAxis(r.kernel.read(),0,r.units),l=sliceAlongLastAxis(r.kernel.read(),r.units,r.units),c=sliceAlongLastAxis(r.kernel.read(),2*r.units,r.units),p=sliceAlongLastAxis(r.kernel.read(),3*r.units,r.units),d=sliceAlongLastAxis(r.recurrentKernel.read(),0,r.units),h=sliceAlongLastAxis(r.recurrentKernel.read(),r.units,r.units),f=sliceAlongLastAxis(r.recurrentKernel.read(),2*r.units,r.units),m=sliceAlongLastAxis(r.recurrentKernel.read(),3*r.units,r.units),g=e,y=e,v=e,b=dot$1(e,u),x=dot$1(g,l),w=dot$1(y,c),S=dot$1(v,p);if(r.useBias){var T=sliceAlongFirstAxis(r.bias.read(),0,r.units),N=sliceAlongFirstAxis(r.bias.read(),r.units,r.units),E=sliceAlongFirstAxis(r.bias.read(),2*r.units,r.units),_=sliceAlongFirstAxis(r.bias.read(),3*r.units,r.units);b=biasAdd(b,T),x=biasAdd(x,N),w=biasAdd(w,E),S=biasAdd(S,_)}var A=i,I=i,O=i,C=i;t=r.recurrentActivation.apply(add(b,dot$1(A,d))),n=r.recurrentActivation.apply(add(x,dot$1(I,h))),a=add(mul(n,s),mul(t,r.activation.apply(add(w,dot$1(O,f))))),o=r.recurrentActivation.apply(add(S,dot$1(C,m)))}else{var P=dot$1(e,r.kernel.read());P=add(P,dot$1(i,r.recurrentKernel.read())),r.useBias&&(P=biasAdd(P,r.bias.read()));var R=sliceAlongLastAxis(P,0,r.units),k=sliceAlongLastAxis(P,r.units,r.units),D=sliceAlongLastAxis(P,2*r.units,r.units),z=sliceAlongLastAxis(P,3*r.units,r.units);t=r.recurrentActivation.apply(R),n=r.recurrentActivation.apply(k),a=add(mul(n,s),mul(t,r.activation.apply(D))),o=r.recurrentActivation.apply(z)}var L=mul(o,r.activation.apply(a));return[L,L,a]})},t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="LSTMCell",t}(RNNCell);serialization.SerializationMap.register(LSTMCell);var LSTM=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new LSTMCell(t),e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(t,r){var n=this;return tidy(function(){var a=null==r?null:r.mask,o=null==r?null:r.training,i=null==r?null:r.initialState;return e.prototype.call.call(n,t,{mask:a,training:o,initialState:i})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},r=e.prototype.getConfig.call(this);return delete r.cell,Object.assign(t,r),t},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)},t.className="LSTM",t}(RNN);serialization.SerializationMap.register(LSTM);var StackedRNNCells=function(e){function t(t){var r=e.call(this,t)||this;return r.cells=t.cells,r}return __extends$1(t,e),Object.defineProperty(t.prototype,"stateSize",{get:function(){for(var e=[],t=0,r=this.cells.slice().reverse();t= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var r=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(r),this.layer.built=!0),e.prototype.build.call(this,t)},t.prototype.computeOutputShape=function(e){var t=[(e=getExactlyOneShape(e))[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),n=e[1];return[r[0],n].concat(r.slice(1))},t.prototype.call=function(e,t){var r=this;return tidy(function(){return rnn(function(e,n){return[r.layer.call(e,t),[]]},e=getExactlyOneTensor(e),[],!1,null,null,!1,e.shape[1])[1]})},t.className="TimeDistributed",t}(Wrapper);serialization.SerializationMap.register(TimeDistributed);var VALID_BIDIRECTIONAL_MERGE_MODES=["sum","mul","concat","ave"];function checkBidirectionalMergeMode(e){checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES,"BidirectionalMergeMode",e)}var Bidirectional=function(e){function t(t){var r=e.call(this,t)||this,n=t.layer.getConfig();if(r.forwardLayer=deserialize({className:t.layer.getClassName(),config:n}),n.goBackwards=!0!==n.goBackwards,r.backwardLayer=deserialize({className:t.layer.getClassName(),config:n}),r.forwardLayer.name="forward_"+r.forwardLayer.name,r.backwardLayer.name="backward_"+r.backwardLayer.name,checkBidirectionalMergeMode(t.mergeMode),r.mergeMode=t.mergeMode,t.weights)throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return r._stateful=t.layer.stateful,r.returnSequences=t.layer.returnSequences,r.returnState=t.layer.returnState,r.supportsMasking=!0,r._trainable=!0,r.inputSpec=t.layer.inputSpec,r}return __extends$1(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))},t.prototype.computeOutputShape=function(e){var t,r,n,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(n=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,r=[t]):r=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?r.concat(n).concat(n.slice()):[t].concat(n).concat(n.slice()):singletonOrArray(r)},t.prototype.apply=function(t,r){var n=null;if(null!=r&&(n=r.initialState),Array.isArray(t)&&(n=t.slice(1),t=t[0]),null==n||0===n.length)return e.prototype.apply.call(this,t,r);throw new NotImplementedError("The support for initial states is not implemented for Bidirectional layers yet.")},t.prototype.call=function(e,t){var r=this;return tidy(function(){if(null!=t.mask)throw new NotImplementedError("The support for masking is not implemented for Bidirectional layers yet.");if(null!=t.initialState)throw new NotImplementedError("The support for initial states is not implemented for Bidirectional layers yet.");var n,a,o=r.forwardLayer.call(e,t),i=r.backwardLayer.call(e,t);return r.returnState&&(Array.isArray(o)&&(n=o.slice(1).concat(i.slice(1))),o=o[0],i=i[0]),r.returnSequences&&(i=reverse(i,1)),"concat"===r.mergeMode?a=concatenate([o,i]):"sum"===r.mergeMode?a=add(o,i):"ave"===r.mergeMode?a=mul(getScalar(.5),add(o,i)):"mul"===r.mergeMode?a=mul(o,i):null==r.mergeMode&&(a=[o,i]),r.returnState?null==r.mergeMode?a.concat(n):[a].concat(n):a})},t.prototype.resetStates=function(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},t.prototype.build=function(e){var t=this;nameScope(this.forwardLayer.name,function(){t.forwardLayer.build(e)}),nameScope(this.backwardLayer.name,function(){t.backwardLayer.build(e)}),this.built=!0},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={mergeMode:this.mergeMode},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.fromConfig=function(e,t){var r=deserialize(t.layer);if(delete t.layer,null!=t.numConstants)throw new NotImplementedError("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var n=t;return n.layer=r,new e(n)},t.className="Bidirectional",t}(Wrapper);function loadModelInternal(e){return __awaiter$1(this,void 0,void 0,function(){var t;return __generator$1(this,function(r){if("string"==typeof e){if(0===(t=io.getLoadHandlers(e)).length)t.push(io.browserHTTPRequest(e));else if(t.length>1)throw new ValueError("Found more than one ("+t.length+") load handlers for URL '"+e+"'");e=t[0]}return[2,loadModelFromIOHandler(e)]})})}function loadModelFromIOHandler(e,t){return __awaiter$1(this,void 0,void 0,function(){var r,n,a,o,i;return __generator$1(this,function(s){switch(s.label){case 0:if(null==e.load)throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(r=s.sent(),null!=(n=r.modelTopology).model_config&&(n=n.model_config),a=deserialize(convertPythonicToTs(n),t),null!=r.weightData){if(null==r.weightSpecs)throw new ValueError("Model artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");o=!1,i=!0,a.loadWeights(io.decodeWeights(r.weightData,r.weightSpecs),o,i)}return[2,a]}})})}serialization.SerializationMap.register(Bidirectional);var Sequential=function(e){function t(t){var r=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},r.trainable=!0,r._updatable=!0,r.built=!1,r.name=null!=t.name?t.name:getUid("sequential_"),null!=t.layers)for(var n=0,a=t.layers;n= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=l-c,S=Math.floor,T=String.fromCharCode;function N(e){throw RangeError(x[e])}function E(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function _(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+E((e=e.replace(b,".")).split("."),t).join(".")}function A(e){for(var t,r,n=[],a=0,o=e.length;a=55296&&t<=56319&&a65535&&(t+=T((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=T(e)}).join("")}function O(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function C(e,t,r){var n=0;for(e=r?S(e/h):e>>1,e+=S(e/t);e>w*p>>1;n+=l)e=S(e/w);return S(n+(w+1)*e/(e+d))}function P(e){var t,r,n,a,o,i,s,d,h,y,v,b=[],x=e.length,w=0,T=m,E=f;for((r=e.lastIndexOf(g))<0&&(r=0),n=0;n=128&&N("not-basic"),b.push(e.charCodeAt(n));for(a=r>0?r+1:0;a=x&&N("invalid-input"),((d=(v=e.charCodeAt(a++))-48<10?v-22:v-65<26?v-65:v-97<26?v-97:l)>=l||d>S((u-w)/i))&&N("overflow"),w+=d*i,!(d<(h=s<=E?c:s>=E+p?p:s-E));s+=l)i>S(u/(y=l-h))&&N("overflow"),i*=y;E=C(w-o,t=b.length+1,0==o),S(w/t)>u-T&&N("overflow"),T+=S(w/t),w%=t,b.splice(w++,0,T)}return I(b)}function R(e){var t,r,n,a,o,i,s,d,h,y,v,b,x,w,E,_=[];for(b=(e=A(e)).length,t=m,r=0,o=f,i=0;i=t&&vS((u-r)/(x=n+1))&&N("overflow"),r+=(s-t)*x,t=s,i=0;iu&&N("overflow"),v==t){for(d=r,h=l;!(d<(y=h<=o?c:h>=o+p?p:h-o));h+=l)E=d-y,w=l-y,_.push(T(O(y+E%w,0))),d=S(E/w);_.push(T(O(d,0))),o=C(r,x,n==a),r=0,++n}++r,++t}return _.join("")}if(i={version:"1.3.2",ucs2:{decode:A,encode:I},decode:P,encode:R,toASCII:function(e){return _(e,function(e){return v.test(e)?"xn--"+R(e):e})},toUnicode:function(e){return _(e,function(e){return y.test(e)?P(e.slice(4).toLowerCase()):e})}},n&&a)if(e.exports==n)a.exports=i;else for(s in i)i.hasOwnProperty(s)&&(n[s]=i[s]);else r.punycode=i}(commonjsGlobal$1)}),util$1={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}};function hasOwnProperty(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var decode=function(e,t,r,n){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var o=/\+/g;e=e.split(t);var i=1e3;n&&"number"==typeof n.maxKeys&&(i=n.maxKeys);var s=e.length;i>0&&s>i&&(s=i);for(var u=0;u=0?(l=h.substr(0,f),c=h.substr(f+1)):(l=h,c=""),p=decodeURIComponent(l),d=decodeURIComponent(c),hasOwnProperty(a,p)?Array.isArray(a[p])?a[p].push(d):a[p]=[a[p],d]:a[p]=d}return a},stringifyPrimitive=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},encode=function(e,t,r,n){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(n){var a=encodeURIComponent(stringifyPrimitive(n))+r;return Array.isArray(e[n])?e[n].map(function(e){return a+encodeURIComponent(stringifyPrimitive(e))}).join(t):a+encodeURIComponent(stringifyPrimitive(e[n]))}).join(t):n?encodeURIComponent(stringifyPrimitive(n))+r+encodeURIComponent(stringifyPrimitive(e)):""},querystring=createCommonjsModule$1(function(e,t){t.decode=t.parse=decode,t.encode=t.stringify=encode}),querystring_1=querystring.decode,querystring_2=querystring.parse,querystring_3=querystring.encode,querystring_4=querystring.stringify,parse=urlParse,format=urlFormat;function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function urlParse(e,t,r){if(e&&util$1.isObject(e)&&e instanceof Url)return e;var n=new Url;return n.parse(e,t,r),n}function urlFormat(e){return util$1.isString(e)&&(e=urlParse(e)),e instanceof Url?e.format():Url.prototype.format.call(e)}Url.prototype.parse=function(e,t,r){if(!util$1.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var n=e.indexOf("?"),a=-1!==n&&n127?x+="x":x+=b[w];if(!x.match(hostnamePartPattern)){var T=y.slice(0,f),N=y.slice(f+1),E=b.match(hostnamePartStart);E&&(T.push(E[1]),N.unshift(E[2])),N.length&&(i="/"+N.join(".")+i),this.hostname=T.join(".");break}}}this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),g||(this.hostname=punycode.toASCII(this.hostname));var _=this.port?":"+this.port:"",A=this.hostname||"";this.host=A+_,this.href+=this.host,g&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==i[0]&&(i="/"+i))}if(!unsafeProtocol[l])for(f=0,v=autoEscape.length;f0)&&r.host.split("@"))&&(r.auth=E.shift(),r.host=r.hostname=E.shift());return r.search=e.search,r.query=e.query,util$1.isNull(r.pathname)&&util$1.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!b.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var w=b.slice(-1)[0],S=(r.host||e.host||b.length>1)&&("."===w||".."===w)||""===w,T=0,N=b.length;N>=0;N--)"."===(w=b[N])?b.splice(N,1):".."===w?(b.splice(N,1),T++):T&&(b.splice(N,1),T--);if(!y&&!v)for(;T--;T)b.unshift("..");!y||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),S&&"/"!==b.join("/").substr(-1)&&b.push("");var E,_=""===b[0]||b[0]&&"/"===b[0].charAt(0);x&&(r.hostname=r.host=_?"":b.length?b.shift():"",(E=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=E.shift(),r.host=r.hostname=E.shift()));return(y=y||r.host&&b.length)&&!_&&b.unshift(""),b.length?r.pathname=b.join("/"):(r.pathname=null,r.path=null),util$1.isNull(r.pathname)&&util$1.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},Url.prototype.parseHost=function(){var e=this.host,t=portPattern.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var aspromise=asPromise;function asPromise(e,t){for(var r=new Array(arguments.length-1),n=0,a=2,o=!0;a1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),a=new Array(123),o=0;o<64;)a[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var a,o=null,i=[],s=0,u=0;t>2],a=(3&l)<<4,u=1;break;case 1:i[s++]=n[a|l>>4],a=(15&l)<<2,u=2;break;case 2:i[s++]=n[a|l>>6],i[s++]=n[63&l],u=0}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0)}return u&&(i[s++]=n[a],i[s++]=61,1===u&&(i[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))};r.decode=function(e,t,r){for(var n,o=r,i=0,s=0;s1)break;if(void 0===(u=a[u]))throw Error("invalid encoding");switch(i){case 0:n=u,i=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,i=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,i=3;break;case 3:t[r++]=(3&n)<<6|u,i=0}}if(1===i)throw Error("invalid encoding");return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}),eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},EventEmitter.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>3.4028234663852886e38)e((a<<31|2139095040)>>>0,r,n);else if(t<1.1754943508222875e-38)e((a<<31|Math.round(t/1.401298464324817e-45))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((a<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function r(e,t,r){var n=e(t,r),a=2*(n>>31)+1,o=n>>>23&255,i=8388607&n;return 255===o?i?NaN:a*(1/0):0===o?1.401298464324817e-45*a*i:a*Math.pow(2,o-150)*(i+8388608)}e.writeFloatLE=t.bind(null,writeUintLE),e.writeFloatBE=t.bind(null,writeUintBE),e.readFloatLE=r.bind(null,readUintLE),e.readFloatBE=r.bind(null,readUintBE)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function a(e,n,a){t[0]=e,n[a]=r[0],n[a+1]=r[1],n[a+2]=r[2],n[a+3]=r[3],n[a+4]=r[4],n[a+5]=r[5],n[a+6]=r[6],n[a+7]=r[7]}function o(e,n,a){t[0]=e,n[a]=r[7],n[a+1]=r[6],n[a+2]=r[5],n[a+3]=r[4],n[a+4]=r[3],n[a+5]=r[2],n[a+6]=r[1],n[a+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function s(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?a:o,e.writeDoubleBE=n?o:a,e.readDoubleLE=n?i:s,e.readDoubleBE=n?s:i}():function(){function t(e,t,r,n,a,o){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,a,o+t),e(1/n>0?0:2147483648,a,o+r);else if(isNaN(n))e(0,a,o+t),e(2146959360,a,o+r);else if(n>1.7976931348623157e308)e(0,a,o+t),e((i<<31|2146435072)>>>0,a,o+r);else{var s;if(n<2.2250738585072014e-308)e((s=n/5e-324)>>>0,a,o+t),e((i<<31|s/4294967296)>>>0,a,o+r);else{var u=Math.floor(Math.log(n)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(s=n*Math.pow(2,-u))>>>0,a,o+t),e((i<<31|u+1023<<20|1048576*s&1048575)>>>0,a,o+r)}}}function r(e,t,r,n,a){var o=e(n,a+t),i=e(n,a+r),s=2*(i>>31)+1,u=i>>>20&2047,l=4294967296*(1048575&i)+o;return 2047===u?l?NaN:s*(1/0):0===u?5e-324*s*l:s*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,writeUintLE,0,4),e.writeDoubleBE=t.bind(null,writeUintBE,4,0),e.readDoubleLE=r.bind(null,readUintLE,0,4),e.readDoubleBE=r.bind(null,readUintBE,4,0)}(),e}function writeUintLE(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function writeUintBE(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}var utf8_1=createCommonjsModule$1(function(e,t){var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?o[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(n>>10),o[i++]=56320+(1023&n)):o[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),i=0);return a?(i&&a.push(String.fromCharCode.apply(String,o.slice(0,i))),a.join("")):String.fromCharCode.apply(String,o.slice(0,i))},r.write=function(e,t,r){for(var n,a,o=r,i=0;i>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(a=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&a),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}}),pool_1=pool;function pool(e,t,r){var n=r||8192,a=n>>>1,o=null,i=n;return function(r){if(r<1||r>a)return e(r);i+r>n&&(o=e(n),i=0);var s=t.call(o,i,i+=r);return 7&i&&(i=1+(7|i)),s}}var longbits=LongBits;function LongBits(e,t){this.lo=e>>>0,this.hi=t>>>0}var zero=LongBits.zero=new LongBits(0,0);zero.toNumber=function(){return 0},zero.zzEncode=zero.zzDecode=function(){return this},zero.length=function(){return 1};var zeroHash=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function(e){if(0===e)return zero;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new LongBits(r,n)},LongBits.from=function(e){if("number"==typeof e)return LongBits.fromNumber(e);if(minimal.isString(e)){if(!minimal.Long)return LongBits.fromNumber(parseInt(e,10));e=minimal.Long.fromString(e)}return e.low||e.high?new LongBits(e.low>>>0,e.high>>>0):zero},LongBits.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},LongBits.prototype.toLong=function(e){return minimal.Long?new minimal.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var charCodeAt=String.prototype.charCodeAt;LongBits.fromHash=function(e){return e===zeroHash?zero:new LongBits((charCodeAt.call(e,0)|charCodeAt.call(e,1)<<8|charCodeAt.call(e,2)<<16|charCodeAt.call(e,3)<<24)>>>0,(charCodeAt.call(e,4)|charCodeAt.call(e,5)<<8|charCodeAt.call(e,6)<<16|charCodeAt.call(e,7)<<24)>>>0)},LongBits.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},LongBits.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},LongBits.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},LongBits.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10};var minimal=createCommonjsModule$1(function(e,t){var r=t;function n(e,t,r){for(var n=Object.keys(t),a=0;a0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=commonjsGlobal$1.dcodeIO&&commonjsGlobal$1.dcodeIO.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=n,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=a,r.ProtocolError=a("ProtocolError"),r.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},r.oneOfSetter=function(e){return function(t){for(var r=0;r127;)t[r++]=127&e|128,e>>>=7;t[r]=e}function VarintOp(e,t){this.len=e,this.next=void 0,this.val=t}function writeVarint64(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function writeFixed32(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}Writer.create=minimal.Buffer?function(){return(Writer.create=function(){return new BufferWriter})()}:function(){return new Writer},Writer.alloc=function(e){return new minimal.Array(e)},minimal.Array!==Array&&(Writer.alloc=minimal.pool(Writer.alloc,minimal.Array.prototype.subarray)),Writer.prototype._push=function(e,t,r){return this.tail=this.tail.next=new Op(e,t,r),this.len+=t,this},VarintOp.prototype=Object.create(Op.prototype),VarintOp.prototype.fn=writeVarint32,Writer.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new VarintOp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},Writer.prototype.int32=function(e){return e<0?this._push(writeVarint64,10,LongBits$1.fromNumber(e)):this.uint32(e)},Writer.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},Writer.prototype.uint64=function(e){var t=LongBits$1.from(e);return this._push(writeVarint64,t.length(),t)},Writer.prototype.int64=Writer.prototype.uint64,Writer.prototype.sint64=function(e){var t=LongBits$1.from(e).zzEncode();return this._push(writeVarint64,t.length(),t)},Writer.prototype.bool=function(e){return this._push(writeByte,1,e?1:0)},Writer.prototype.fixed32=function(e){return this._push(writeFixed32,4,e>>>0)},Writer.prototype.sfixed32=Writer.prototype.fixed32,Writer.prototype.fixed64=function(e){var t=LongBits$1.from(e);return this._push(writeFixed32,4,t.lo)._push(writeFixed32,4,t.hi)},Writer.prototype.sfixed64=Writer.prototype.fixed64,Writer.prototype.float=function(e){return this._push(minimal.float.writeFloatLE,4,e)},Writer.prototype.double=function(e){return this._push(minimal.float.writeDoubleLE,8,e)};var writeBytes=minimal.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(writeByte,1,0);if(minimal.isString(e)){var r=Writer.alloc(t=base64.length(e));base64.decode(e,r,0),e=r}return this.uint32(t)._push(writeBytes,t,e)},Writer.prototype.string=function(e){var t=utf8.length(e);return t?this.uint32(t)._push(utf8.write,t,e):this._push(writeByte,1,0)},Writer.prototype.fork=function(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this},Writer.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop,0,0),this.len=0),this},Writer.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},Writer.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},Writer._configure=function(e){BufferWriter=e};var writer_buffer=BufferWriter$1;(BufferWriter$1.prototype=Object.create(writer.prototype)).constructor=BufferWriter$1;var Buffer=minimal.Buffer;function BufferWriter$1(){writer.call(this)}BufferWriter$1.alloc=function(e){return(BufferWriter$1.alloc=minimal._Buffer_allocUnsafe)(e)};var writeBytesBuffer=Buffer&&Buffer.prototype instanceof Uint8Array&&"set"===Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(writeBytesBuffer,t,e),this},BufferWriter$1.prototype.string=function(e){var t=Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this};var reader=Reader,BufferReader,LongBits$2=minimal.LongBits,utf8$1=minimal.utf8;function indexOutOfRange(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Reader(e){this.buf=e,this.pos=0,this.len=e.length}var create_array="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Reader(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Reader(e);throw Error("illegal buffer")},value;function readLongVarint(){var e=new LongBits$2(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits$2(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader.create=minimal.Buffer?function(e){return(Reader.create=function(e){return minimal.Buffer.isBuffer(e)?new BufferReader(e):create_array(e)})(e)}:create_array,Reader.prototype._slice=minimal.Array.prototype.subarray||minimal.Array.prototype.slice,Reader.prototype.uint32=(value=4294967295,function(){if(value=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return value;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return value}),Reader.prototype.int32=function(){return 0|this.uint32()},Reader.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},Reader.prototype.bool=function(){return 0!==this.uint32()},Reader.prototype.fixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.sfixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.float=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var e=minimal.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Reader.prototype.double=function(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var e=minimal.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Reader.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw indexOutOfRange(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},Reader.prototype.string=function(){var e=this.bytes();return utf8$1.read(e,0,e.length)},Reader.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw indexOutOfRange(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(128&this.buf[this.pos++]);return this},Reader.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;;){if(4==(e=7&this.uint32()))break;this.skipType(e)}break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},Reader._configure=function(e){BufferReader=e;var t=minimal.Long?"toLong":"toNumber";minimal.merge(Reader.prototype,{int64:function(){return readLongVarint.call(this)[t](!1)},uint64:function(){return readLongVarint.call(this)[t](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function(){return readFixed64.call(this)[t](!0)},sfixed64:function(){return readFixed64.call(this)[t](!1)}})};var reader_buffer=BufferReader$1;function BufferReader$1(e){reader.call(this,e)}(BufferReader$1.prototype=Object.create(reader.prototype)).constructor=BufferReader$1,minimal.Buffer&&(BufferReader$1.prototype._slice=minimal.Buffer.prototype.slice),BufferReader$1.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len))};var service=Service;function Service(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");minimal.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(Service.prototype=Object.create(minimal.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function e(t,r,n,a,o){if(!a)throw TypeError("request must be specified");var i=this;if(!o)return minimal.asPromise(e,i,t,r,n,a);if(i.rpcImpl)try{return i.rpcImpl(t,r[i.requestDelimited?"encodeDelimited":"encode"](a).finish(),function(e,r){if(e)return i.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof n))try{r=n[i.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return i.emit("error",e,t),o(e)}return i.emit("data",r,t),o(null,r)}i.end(!0)})}catch(e){return i.emit("error",e,t),void setTimeout(function(){o(e)},0)}else setTimeout(function(){o(Error("already ended"))},0)},Service.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};var rpc_1=createCommonjsModule$1(function(e,t){t.Service=service}),roots={},indexMinimal=createCommonjsModule$1(function(e,t){var r=t;function n(){r.Reader._configure(r.BufferReader),r.util._configure()}r.build="minimal",r.Writer=writer,r.BufferWriter=writer_buffer,r.Reader=reader,r.BufferReader=reader_buffer,r.util=minimal,r.rpc=rpc_1,r.roots=roots,r.configure=n,r.Writer._configure(r.BufferWriter),n()}),minimal$1=indexMinimal,minimal_1=minimal$1.roots,minimal_2=minimal$1.Reader,minimal_3=minimal$1.util;const $Reader=minimal_2,$util=minimal_3,$root=minimal_1.default||(minimal_1.default={}),tensorflow=$root.tensorflow=function(){const e={};return e.Any=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.typeUrl=e.string();break;case 2:n.value=e.bytes();break;default:e.skipType(7&a)}}return n},e}(),e.DataType=function(){const e={},t=Object.create(e);return t[e[0]="DT_INVALID"]=0,t[e[1]="DT_FLOAT"]=1,t[e[2]="DT_DOUBLE"]=2,t[e[3]="DT_INT32"]=3,t[e[4]="DT_UINT8"]=4,t[e[5]="DT_INT16"]=5,t[e[6]="DT_INT8"]=6,t[e[7]="DT_STRING"]=7,t[e[8]="DT_COMPLEX64"]=8,t[e[9]="DT_INT64"]=9,t[e[10]="DT_BOOL"]=10,t[e[11]="DT_QINT8"]=11,t[e[12]="DT_QUINT8"]=12,t[e[13]="DT_QINT32"]=13,t[e[14]="DT_BFLOAT16"]=14,t[e[101]="DT_FLOAT_REF"]=101,t[e[102]="DT_DOUBLE_REF"]=102,t[e[103]="DT_INT32_REF"]=103,t[e[104]="DT_UINT8_REF"]=104,t[e[105]="DT_INT16_REF"]=105,t[e[106]="DT_INT8_REF"]=106,t[e[107]="DT_STRING_REF"]=107,t[e[108]="DT_COMPLEX64_REF"]=108,t[e[109]="DT_INT64_REF"]=109,t[e[110]="DT_BOOL_REF"]=110,t[e[111]="DT_QINT8_REF"]=111,t[e[112]="DT_QUINT8_REF"]=112,t[e[113]="DT_QINT32_REF"]=113,t[e[114]="DT_BFLOAT16_REF"]=114,t}(),e.TensorShape=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),r=0;r>>3){case 2:n.dim&&n.dim.length||(n.dim=[]),n.dim.push($root.tensorflow.TensorShape.Dim.decode(e,e.uint32()));break;case 3:n.unknownRank=e.bool();break;default:e.skipType(7&a)}}return n},e.Dim=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.size=e.int64();break;case 2:n.name=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),e.Tensor=function(){function e(e){if(this.floatVal=[],this.doubleVal=[],this.intVal=[],this.stringVal=[],this.scomplexVal=[],this.int64Val=[],this.boolVal=[],this.uint32Val=[],this.uint64Val=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.dtype=e.int32();break;case 2:n.tensorShape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;case 3:n.versionNumber=e.int32();break;case 4:n.tensorContent=e.bytes();break;case 5:if(n.floatVal&&n.floatVal.length||(n.floatVal=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.list=$root.tensorflow.AttrValue.ListValue.decode(e,e.uint32());break;case 2:n.s=e.bytes();break;case 3:n.i=e.int64();break;case 4:n.f=e.float();break;case 5:n.b=e.bool();break;case 6:n.type=e.int32();break;case 7:n.shape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;case 8:n.tensor=$root.tensorflow.Tensor.decode(e,e.uint32());break;case 9:n.placeholder=e.string();break;case 10:n.func=$root.tensorflow.NameAttrList.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.ListValue=function(){function e(e){if(this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[],e)for(var t=Object.keys(e),r=0;r