// @tensorflow/tfjs Copyright 2018 Google !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.tf=e.tf||{})}(this,function(exports){"use strict";var extendStatics=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(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __decorate(e,t,r,n){var a,o=arguments.length,i=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=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(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(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=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&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]0;)n=Math.random()*t|0,r=e[--t],e[t]=e[n],e[n]=r}function clamp(e,t,r){return Math.max(e,Math.min(t,r))}function randUniform(e,t){return Math.random()*(t-e)+e}function distSquared(e,t){for(var r=0,n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),assert(e.length===t[0],function(){return"Element arr["+r.join("][")+"] should have "+t[0]+" elements, but has "+e.length+" elements"});for(var n=t.slice(1),a=0;a1;--t)if(e%t==0)return[t,e/t];return[1,e]}function createShuffledIndices(e){for(var t=new Uint32Array(e),r=0;r=r?a():setTimeout(i,s)}};i()})}function getQueryParams(e){var t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var r=[],n=1;n0)r*=e[a];else if(-1===e[a]){if(-1!==n)throw Error("Shapes can only have 1 implicit size. Found - 1 at dim "+n+" and dim "+a);n=a}else if(e[a]<=0)throw Error("Shapes can not be <= 0. Found "+e[a]+" at dim "+a);if(-1===n){if(t>0&&t!==r)throw Error("Size("+t+") must match the product of shape "+e);return e}if(t%r!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+r);var o=e.slice();return o[n]=t/r,o}function squeezeShape(e,t){for(var r=[],n=[],a=0,o=0;o1)throw new Error("Can't squeeze axis "+o+" since its dim '"+e[o]+"' is not 1");(null==t[a]||t[a]>o)&&1===e[o]&&(r.push(e[o]),n.push(o)),t[a]<=o&&a++}e[o]>1&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}}function getTypedArrayFromDType(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(t)}return r}function checkForNaN(e,t,r){if("float32"===t)for(var n=0;n=0;--n)r[n]=r[n+1]*e[n+1];return r}function toTypedArray(e,t){return noConversionNeeded(e,t)?e:(Array.isArray(e)&&(e=flatten(e)),copyTypedArray(e,t))}function noConversionNeeded(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}function makeOnesTypedArray(e,t){for(var r=makeZerosTypedArray(e,t),n=0;n1)for(var i=0;iFORMAT_LIMIT_NUM_VALS){var s=Array.from(e.subarray(0,FORMAT_NUM_FIRST_LAST_VALS)),u=Array.from(e.subarray(o-FORMAT_NUM_FIRST_LAST_VALS,o));return["["+s.map(function(e,t){return valToString(e,n[t])}).join(", ")+", ..., "+u.map(function(e,t){return valToString(e,n[o-FORMAT_NUM_FIRST_LAST_VALS+t])}).join(", ")+"]"]}return["["+Array.from(e).map(function(e,t){return valToString(e,n[t])}).join(", ")+"]"]}var l=t.slice(1),c=r.slice(1),p=r[0],d=[];if(o>FORMAT_LIMIT_NUM_VALS){for(var h=0;h1)return e.zeros([0],a);var o=makeZerosTypedArray(Math.abs(Math.ceil((r-t)/n)),a);r=0;o--){i=(m=e[o]).inputs;var h=[];for(h.push(m.output),c=0;c=0;r--){var n=t[r],a=e[n.output.id];if(null==n.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+n.name+".");var o=n.gradient(a);for(var i in n.inputs){if(!(i in o))throw new Error("Cannot backprop through input "+i+". Available gradients found: "+Object.keys(o)+".");var s=o[i](),u=n.inputs[i];if(!arraysEqual(s.shape,u.shape))throw new Error("Error in gradient for op "+n.name+". The gradient of input '"+i+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}}}var Type,Engine=function(){function e(e,t,r){this.backend=e,this.safeMode=t,this.debugMode=r,this.registeredVariables={},this.refCounter=new WeakMap,this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numDataBuffers=0,this.gradientScopeCount=0,this.customGradientDepth=0,this.keepTensors=new Set,this.activeScope={track:[]},this.scopeStack=[this.activeScope],this.profiler=new Profiler(e)}return e.prototype.tidy=function(e,t,r){void 0===r&&(r=!1);var n=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}this.startScope(n,r);var a=t();return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),this.endScope(a,r),a},e.prototype.runKernel=function(e,t,r){var n,a=this,o=[],i=function(e){return o.push(e),e},s=this.activeScope.name;if(this.customGradientDepth++,n=this.debugMode?this.profiler.profileKernel(s,function(){return e(a.backend,i)}):e(this.backend,i),this.customGradientDepth--,this.shouldRecord()){var u={id:this.nextTapeNodeId++,name:s,inputs:t,output:n};null!=r&&(u.gradient=function(e){return r(e,o)}),this.activeTape.push(u)}return n},e.prototype.registerTensor=function(e){var t=this.refCounter.has(e.dataId)?this.refCounter.get(e.dataId):0;this.numTensors++,0===t&&(this.numDataBuffers++,this.numBytes+=sizeFromShape(e.shape)*bytesPerElement(e.dtype),this.backend.register(e.dataId,e.shape,e.dtype)),this.refCounter.set(e.dataId,t+1),e instanceof Variable||this.track(e)},e.prototype.registerVariable=function(e){if(null!=this.registeredVariables[e.name])throw new Error("Variable with name "+e.name+" was already registered");this.registeredVariables[e.name]=e},e.prototype.disposeTensor=function(e){if(this.refCounter.has(e.dataId)){this.keepTensors.has(e.id)&&this.keepTensors.delete(e.id),this.numTensors--;var t=this.refCounter.get(e.dataId);t<=1?(this.refCounter.delete(e.dataId),this.backend.disposeData(e.dataId),this.numDataBuffers--,this.numBytes-=sizeFromShape(e.shape)*bytesPerElement(e.dtype)):this.refCounter.set(e.dataId,t-1)}},e.prototype.disposeVariables=function(){for(var e in this.registeredVariables){var t=this.registeredVariables[e];this.disposeTensor(t),delete this.registeredVariables[e]}},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.numTensors,e.numDataBuffers=this.numDataBuffers,e.numBytes=this.numBytes,e},e.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},e.prototype.addTapeNode=function(e,t,r){var n={};e.forEach(function(e,t){n[t]=e});var a={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:n,output:t,gradient:function(e){var t={};return r(e).forEach(function(e,r){t[r]=function(){return e}}),t}};this.activeTape.push(a)},e.prototype.keep=function(e){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var r={track:[]};e&&(r.name=e),this.scopeStack.push(r),this.activeScope=r},e.prototype.endScope=function(e,t){var r=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var n=new Set(this.keepTensors),a=getTensorsInContainer(e);a.forEach(function(e){return n.add(e.id)});for(var o=0;o0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var o=e();assert(o instanceof Tensor,"The result y returned by f() must be a tensor.");var i=getFilteredNodesXToY(a.activeTape,t,o);if(!n&&0===i.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var s={};return s[o.id]=null==r?TensorOps.ones(o.shape):r,backpropagateGradients(s,i),{value:o,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return assert(isFunction(e),"The f passed in customGrad(f) must be a function."),function(){for(var r,n=[],a=0;a {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e},e}(),e;e=Type||(Type={}),e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING";var URL_PROPERTIES=[{name:"DEBUG",type:Type.BOOLEAN},{name:"IS_BROWSER",type:Type.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:Type.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:Type.BOOLEAN},{name:"WEBGL_VERSION",type:Type.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED",type:Type.BOOLEAN},{name:"BACKEND",type:Type.STRING}];function isWebGLVersionEnabled(e,t){var r;try{r=getWebGLRenderingContext(e,t)}catch(e){return!1}return null!=r&&(loseContext(r),!0)}function getWebGLDisjointQueryTimerVersion(e,t){if(0===e)return 0;var r,n=getWebGLRenderingContext(e,t);return r=hasExtension(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:hasExtension(n,"EXT_disjoint_timer_query")?1:0,null!=n&&loseContext(n),r}function isRenderToFloatTextureEnabled(e,t){if(0===e)return!1;var r=getWebGLRenderingContext(e,t);if(1===e){if(!hasExtension(r,"OES_texture_float"))return!1}else if(!hasExtension(r,"EXT_color_buffer_float"))return!1;createFloatTextureAndBindToFramebuffer(r,e);var n=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return loseContext(r),n}function isDownloadFloatTextureEnabled(e,t){if(0===e)return!1;var r=getWebGLRenderingContext(e,t);if(1===e){if(!hasExtension(r,"OES_texture_float"))return!1}else if(!hasExtension(r,"EXT_color_buffer_float"))return!1;createFloatTextureAndBindToFramebuffer(r,e),r.readPixels(0,0,1,1,r.RGBA,r.FLOAT,new Float32Array(4));var n=r.getError()===r.NO_ERROR;return loseContext(r),n}function isWebGLGetBufferSubDataAsyncExtensionEnabled(e,t){if(e>0)return!1;if(2!==e)return!1;var r=getWebGLRenderingContext(e,t),n=hasExtension(r,"WEBGL_get_buffer_sub_data_async");return loseContext(r),n}function isChrome(){return null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}var TENSORFLOWJS_FLAGS_PREFIX="tfjsflags";function getFeaturesFromURL(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=getQueryParams(window.location.search);if(TENSORFLOWJS_FLAGS_PREFIX in t){var r={};t[TENSORFLOWJS_FLAGS_PREFIX].split(",").forEach(function(e){var t=e.split(":"),n=t[0],a=t[1];r[n]=a}),URL_PROPERTIES.forEach(function(t){t.name in r&&(console.log("Setting feature override from URL "+t.name+": "+r[t.name]),t.type===Type.NUMBER?e[t.name]=+r[t.name]:t.type===Type.BOOLEAN?e[t.name]="true"===r[t.name]:t.type===Type.STRING?e[t.name]=r[t.name]:console.warn("Unknown URL param: "+t.name+"."))})}return e}function hasExtension(e,t){return null!=e.getExtension(t)}function getWebGLRenderingContext(e,t){if(0===e||!t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var r=document.createElement("canvas");return 1===e?r.getContext("webgl")||r.getContext("experimental-webgl"):r.getContext("webgl2")}function loseContext(e){if(null!=e){var t=e.getExtension("WEBGL_lose_context");if(null==t)throw new Error("Extension WEBGL_lose_context not supported on this browser.");t.loseContext()}}function createFloatTextureAndBindToFramebuffer(e,t){var r=e.createFramebuffer(),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);var a=2===t?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,a,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}var TEST_EPSILON_FLOAT32_ENABLED=.001,TEST_EPSILON_FLOAT32_DISABLED=.1,Environment=function(){function e(e){this.features={},this.registry={},null!=e&&(this.features=e),this.get("DEBUG")&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}return e.setBackend=function(e,t){if(void 0===t&&(t=!1),!(e in ENV.registry))throw new Error("Backend type '"+e+"' not found in registry");ENV.initBackend(e,t)},e.getBackend=function(){return ENV.initDefaultBackend(),ENV.currentBackend},e.disposeVariables=function(){ENV.engine.disposeVariables()},e.memory=function(){return ENV.engine.memory()},e.tidy=function(e,t,r){return void 0===r&&(r=!1),ENV.engine.tidy(e,t,r)},e.dispose=function(e){getTensorsInContainer(e).forEach(function(e){return e.dispose()})},e.keep=function(e){return ENV.engine.keep(e)},e.time=function(e){return ENV.engine.time(e)},e.prototype.get=function(e){return e in this.features?this.features[e]:(this.features[e]=this.evaluateFeature(e),this.features[e])},e.prototype.getFeatures=function(){return this.features},e.prototype.set=function(e,t){this.features[e]=t},e.prototype.getBestBackendType=function(){var e=this;if(0===Object.keys(this.registry).length)throw new Error("No backend found in registry.");return Object.keys(this.registry).map(function(t){return{name:t,entry:e.registry[t]}}).sort(function(e,t){return t.entry.priority-e.entry.priority})[0].name},e.prototype.evaluateFeature=function(e){if("DEBUG"===e)return!1;if("IS_BROWSER"===e)return"undefined"!=typeof window;if("IS_NODE"===e)return"undefined"!=typeof process&&void 0!==process.versions.node;if("IS_CHROME"===e)return isChrome();if("BACKEND"===e)return this.getBestBackendType();if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"===e){var t=this.get("WEBGL_VERSION");return 0===t?0:getWebGLDisjointQueryTimerVersion(t,this.get("IS_BROWSER"))}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===e)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!isMobile();if("WEBGL_VERSION"===e)return isWebGLVersionEnabled(2,this.get("IS_BROWSER"))?2:isWebGLVersionEnabled(1,this.get("IS_BROWSER"))?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===e)return isRenderToFloatTextureEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===e)return isDownloadFloatTextureEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED"===e)return isWebGLGetBufferSubDataAsyncExtensionEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("TEST_EPSILON"===e)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?TEST_EPSILON_FLOAT32_ENABLED:TEST_EPSILON_FLOAT32_DISABLED;throw new Error("Unknown feature "+e+".")},e.prototype.setFeatures=function(e){this.features=e},e.prototype.reset=function(){this.features=getFeaturesFromURL(),null!=this.globalEngine&&(this.globalEngine=null)},e.prototype.initBackend=function(e,t){void 0===t&&(t=!1),this.currentBackend=e;var r=this.findBackend(e);this.globalEngine=new Engine(r,t,this.get("DEBUG"))},e.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},e.prototype.registerBackend=function(e,t,r,n){var a=this;if(void 0===r&&(r=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=n&&n(function(){return a.engine}),!1;try{var o=t();return this.registry[e]={backend:o,priority:r},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},e.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e]},Object.defineProperty(e.prototype,"engine",{get:function(){return this.initDefaultBackend(),this.globalEngine},enumerable:!0,configurable:!0}),e.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(this.get("BACKEND"),!1)},__decorate([doc({heading:"Environment"})],e,"setBackend",null),__decorate([doc({heading:"Environment"})],e,"getBackend",null),__decorate([doc({heading:"Environment"})],e,"disposeVariables",null),__decorate([doc({heading:"Performance",subheading:"Memory"})],e,"memory",null),__decorate([doc({heading:"Performance",subheading:"Memory"})],e,"tidy",null),__decorate([doc({heading:"Performance",subheading:"Memory"})],e,"dispose",null),__decorate([doc({heading:"Performance",subheading:"Memory"})],e,"keep",null),__decorate([doc({heading:"Performance",subheading:"Timing"})],e,"time",null),e}();function getGlobalNamespace(){var e;if("undefined"!=typeof window)e=window;else{if("undefined"==typeof process)throw new Error("Could not find a global object");e=process}return e}function getOrMakeEnvironment(){var e=getGlobalNamespace();return null==e.ENV&&(e.ENV=new Environment(getFeaturesFromURL()),setTensorTracker(function(){return e.ENV.engine})),e.ENV}var DType,UpcastInt32AndMap,UpcastBoolAndMap,UpcastFloat32AndMap,ENV=getOrMakeEnvironment(),environment=Object.freeze({Environment:Environment,ENV:ENV});function axesAreInnerMostDims(e,t){for(var r=0;r=-r&&e=0&&r=1,"Pass at least one tensor to concat");var r=convertToTensorArray(e,"tensors","concat"),n=r[0];if(1===r.length)return n;for(var a=parseAxisParam(t,n.shape),o=1;o>>0,t=(n*=t)>>>0,t+=4294967296*(n-=t)}return 2.3283064365386963e-10*(t>>>0)});r.next=function(){var e=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=e-(r.c=0|e)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(e),r.s0<0&&(r.s0+=1),r.s1-=n(e),r.s1<0&&(r.s1+=1),r.s2-=n(e),r.s2<0&&(r.s2+=1),n=null}(e),a=t&&t.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),xor128=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var r=new function(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),xorwow=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:r+=e;for(var n=0;n>>4),t.next()}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),xorshift7=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.x,a=t.i;return e=n[a],r=(e^=e>>>7)^e<<24,r^=(e=n[a+1&7])^e>>>10,r^=(e=n[a+3&7])^e>>>3,r^=(e=n[a+4&7])^e<<7,e=n[a+7&7],r^=(e^=e<<13)^e<<9,n[a]=r,t.i=a+1&7,r},function(e,t){var r,n=[];if(t===(0|t))n[0]=t;else for(t=""+t,r=0;r0;--r)e.next()}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.x&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),xor4096=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.w,a=t.X,o=t.i;return t.w=n=n+1640531527|0,r=a[o+34&127],e=a[o=o+1&127],r^=r<<13,e^=e<<17,r^=r>>>15,e^=e>>>12,r=a[o]=r^e,t.i=o,r+(n^n>>>16)|0},function(e,t){var r,n,a,o,i,s=[],u=128;for(t===(0|t)?(n=t,t=null):(t+="\0",n=0,u=Math.max(u,t.length)),a=0,o=-32;o>>15,n^=n<<4,n^=n>>>13,o>=0&&(i=i+1640531527|0,a=0==(r=s[127&o]^=n+i)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,o=512;o>0;--o)n=s[a+34&127],r=s[a=a+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[a]=n^r;e.w=i,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.X&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),tychei=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.b,r=t.c,n=t.d,a=t.a;return e=e<<25^e>>>7^r,r=r-n|0,n=n<<24^n>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^r,t.c=r=r-n|0,t.d=n<<16^r>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),seedrandom=createCommonjsModule(function(e){!function(t,r){var n,a=this,o=256,i=6,s="random",u=r.pow(o,i),l=r.pow(2,52),c=2*l,p=o-1;function d(e,d,g){var y=[],v=f(function e(t,r){var n,a=[],o=typeof t;if(r&&"object"==o)for(n in t)try{a.push(e(t[n],r-1))}catch(e){}return a.length?a:"string"==o?t:t+"\0"}((d=1==d?{entropy:!0}:d||{}).entropy?[e,m(t)]:null==e?function(){try{var e;return n&&(e=n.randomBytes)?e=e(o):(e=new Uint8Array(o),(a.crypto||a.msCrypto).getRandomValues(e)),m(e)}catch(e){var r=a.navigator,i=r&&r.plugins;return[+new Date,a,i,a.screen,m(t)]}}():e,3),y),b=new function(e){var t,r=e.length,n=this,a=0,i=n.i=n.j=0,s=n.S=[];for(r||(e=[r++]);a=c;)e/=2,t/=2,r>>>=1;return(e+r)/t};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,f(m(b.S),t),(d.pass||g||function(e,t,n,a){return a&&(a.S&&h(a,b),e.state=function(){return h(b,{})}),n?(r[s]=e,t):e})(x,v,"global"in d?d.global:this==r,d.state)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){for(var r,n=e+"",a=0;a=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*a*s,r=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(t)||(n=!0)}return this.truncated&&!this.isValidTruncated(r)||(this.nextVal=this.convertValue(r)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),ArrayOps=function(){function e(){}return e.clone=function(e){var t=convertToTensor(e,"x","clone");return ENV.engine.runKernel(function(e){return Tensor.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})},e.eye=function(t,r,n,a){void 0===a&&(a="float32"),null==r&&(r=t);for(var o=e.buffer([t,r],a),i=t<=r?t:r,s=0;s2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);r=r||Math.random();var s=1===i?a.as2D(1,-1):a,u=ENV.engine.runKernel(function(e){return e.multinomial(s,n,t,r)},{logits2D:s});return 1===i?u.as1D():u},e.oneHot=function(e,t,r,n){void 0===r&&(r=1),void 0===n&&(n=0);var a=convertToTensor(e,"indices","oneHot","int32");if(assert("int32"===a.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return ENV.engine.runKernel(function(e){return e.oneHot(a,t,r,n)},{$indices:a})},e.fromPixels=function(e,t){if(void 0===t&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return ENV.engine.fromPixels(e,t)},e.toPixels=function(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,o,i,s,u,l,c,p,d,h,f,m,g,y,v,b,x,w;return __generator(this,function(S){switch(S.label){case 0:if(2!==(r=convertToTensor(e,"img","toPixels","int32")).rank&&3!==r.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+r.rank+".");if(n=r.shape.slice(0,2),a=n[0],o=n[1],(i=2===r.rank?1:r.shape[2])>4||2===i)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return s=r.min(),u=r.max(),[4,s.data()];case 1:return l=S.sent()[0],[4,u.data()];case 2:if(c=S.sent()[0],s.dispose(),u.dispose(),"float32"===r.dtype){if(l<0||c>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+c+"].")}else{if("int32"!==r.dtype)throw new Error("Unsupported type for toPixels: "+r.dtype+". Please use float32 or int32 tensors.");if(l<0||c>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+c+"].")}return[4,r.data()];case 3:for(p=S.sent(),d="float32"===r.dtype?255:1,h=new Uint8ClampedArray(o*a*4),f=0;f=1,"Pass at least one tensor to tf.stack"),1===r.length)return r[0].expandDims(t);var n=r[0].rank,a=r[0].shape,o=r[0].dtype;assert(t<=n,"Axis must be <= rank of the tensor"),r.forEach(function(e){assertShapesMatch(a,e.shape,"All tensors passed to stack must have matching shapes")}),r.forEach(function(e){assert(o===e.dtype,"All tensors passed to stack must have matching dtypes")});var i=r.map(function(e){return e.expandDims(t)});return ConcatOps.concat(i,t)},e.unstack=function(e,t){void 0===t&&(t=0);for(var r,n=convertToTensor(e,"x","unstack"),a=n.shape[t],o=Array(n.rank-1).fill(0),i=0,s=0;s1&&1===i&&n.unshift(o)}return n}function getReductionAxes(e,t){for(var r=[],n=0;n1)&&r.unshift(o)}return r}function broadcastDimsAreOuter(e){for(var t=0;t1&&s>1&&i!==s)throw Error(n);r.unshift(Math.max(i,s))}return r}var UnaryOps=function(){function e(){}return e.neg=function(e){var t=convertToTensor(e,"x","neg");return ENV.engine.runKernel(function(e){return e.neg(t)},{$x:t},function(e){return{$x:function(){return e.neg()}}})},e.ceil=function(e){var t=convertToTensor(e,"x","ceil");return ENV.engine.runKernel(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return TensorOps.zerosLike(e)}}})},e.floor=function(e){var t=convertToTensor(e,"x","floor");return ENV.engine.runKernel(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return TensorOps.zerosLike(e)}}})},e.sign=function(e){var t=convertToTensor(e,"x","sign");return ENV.engine.runKernel(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return TensorOps.zerosLike(e)}}})},e.round=function(e){var t=convertToTensor(e,"x","round");return ENV.engine.runKernel(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return TensorOps.zerosLike(e)}}})},e.exp=function(e){var t=convertToTensor(e,"x","exp");return ENV.engine.runKernel(function(e,r){return r(e.exp(t))},{$x:t},function(e,t){var r=t[0];return{$x:function(){return e.mulStrict(r)}}})},e.expm1=function(e){var t=convertToTensor(e,"x","expm1");return ENV.engine.runKernel(function(e){return e.expm1(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.exp())}}})},e.log=function(e){var t=convertToTensor(e,"x","log");return ENV.engine.runKernel(function(e){return e.log(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat())}}})},e.log1p=function(e){var t=convertToTensor(e,"x","log1p");return ENV.engine.runKernel(function(e){return e.log1p(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.add(TensorOps.scalar(1)))}}})},e.sqrt=function(e){var t=convertToTensor(e,"x","sqrt");return ENV.engine.runKernel(function(e){return e.sqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().sqrt().mul(TensorOps.scalar(2)))}}})},e.rsqrt=function(e){var t=convertToTensor(e,"x","rsqrt");return ENV.engine.runKernel(function(e){return e.rsqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.pow(TensorOps.scalar(1.5)).mul(TensorOps.scalar(2))).neg()}}})},e.square=function(e){var t=convertToTensor(e,"x","square");return ENV.engine.runKernel(function(e){return e.square(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().mul(TensorOps.scalar(2)))}}})},e.reciprocal=function(e){var t=convertToTensor(e,"x","reciprocal");return ENV.engine.runKernel(function(e){return e.reciprocal(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.square().neg())}}})},e.abs=function(e){var t=convertToTensor(e,"x","abs");return ENV.engine.runKernel(function(e){return e.abs(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().step(-1))}}})},e.clipByValue=function(e,t,r){var n=convertToTensor(e,"x","clipByValue");return assert(t<=r,"Error in clip: min ("+t+") must be less than or equal to max ("+r+")."),ENV.engine.runKernel(function(e){return e.clip(n,t,r)},{$x:n},function(e){return{$x:function(){return e.where(n.greaterEqual(TensorOps.scalar(t)).logicalAnd(n.lessEqual(TensorOps.scalar(r))),TensorOps.zerosLike(e))}}})},e.sigmoid=function(e){var t=convertToTensor(e,"x","sigmoid");return ENV.engine.runKernel(function(e,r){return r(e.sigmoid(t))},{$x:t},function(e,t){var r=t[0];return{$x:function(){return e.mulStrict(r.mul(TensorOps.scalar(1).sub(r)))}}})},e.logSigmoid=function(e){var t=convertToTensor(e,"x","logSigmoid");return ENV.engine.runKernel(function(e){return e.softplus(t.neg()).neg()},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.neg().sigmoid())}}})},e.softplus=function(e){var t=convertToTensor(e,"x","softplus");return ENV.engine.runKernel(function(e){return e.softplus(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.sigmoid())}}})},e.sin=function(e){var t=convertToTensor(e,"x","sin");return ENV.engine.runKernel(function(e){return e.sin(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cos().mulStrict(e)}}})},e.cos=function(e){var t=convertToTensor(e,"x","cos");return ENV.engine.runKernel(function(e){return e.cos(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sin().neg().mulStrict(e)}}})},e.tan=function(e){var t=convertToTensor(e,"x","tan");return ENV.engine.runKernel(function(e){return e.tan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.cos().square())}}})},e.asin=function(e){var t=convertToTensor(e,"x","asin");return ENV.engine.runKernel(function(e){return e.asin(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(TensorOps.scalar(1).sub(t.toFloat().square()).sqrt())}}})},e.acos=function(e){var t=convertToTensor(e,"x","acos");return ENV.engine.runKernel(function(e){return e.acos(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(TensorOps.scalar(1).sub(t.toFloat().square()).sqrt()).neg()}}})},e.atan=function(e){var t=convertToTensor(e,"x","atan");return ENV.engine.runKernel(function(e){return e.atan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(TensorOps.scalar(1).add(t.toFloat().square()))}}})},e.sinh=function(e){var t=convertToTensor(e,"x","sinh");return ENV.engine.runKernel(function(e){return e.sinh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cosh().mulStrict(e)}}})},e.cosh=function(e){var t=convertToTensor(e,"x","cosh");return ENV.engine.runKernel(function(e){return e.cosh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sinh().mulStrict(e)}}})},e.tanh=function(e){var t=convertToTensor(e,"x","tanh");return ENV.engine.runKernel(function(e,r){return r(e.tanh(t))},{$x:t},function(e,t){var r=t[0];return{$x:function(){return TensorOps.scalar(1).sub(r.square()).mulStrict(e)}}})},e.asinh=function(e){var t=convertToTensor(e,"x","asinh");return ENV.engine.runKernel(function(e){return e.asinh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(TensorOps.scalar(1).add(t.toFloat().square()).sqrt())}}})},e.acosh=function(e){var t=convertToTensor(e,"x","acosh");return ENV.engine.runKernel(function(e){return e.acosh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().square().sub(TensorOps.scalar(1)).sqrt())}}})},e.atanh=function(e){var t=convertToTensor(e,"x","atanh");return ENV.engine.runKernel(function(e){return e.atanh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(TensorOps.scalar(1).sub(t.toFloat().square()))}}})},e.erf=function(e){var t=convertToTensor(e,"x","erf");return assert("int32"===t.dtype||"float32"===t.dtype,"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=t.toFloat()),ENV.engine.runKernel(function(e){return e.erf(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(TensorOps.scalar(2/Math.sqrt(Math.PI)).mul(t.square().neg().exp()))}}})},e.step=function(e,t){void 0===t&&(t=0);var r=convertToTensor(e,"x","step");return ENV.engine.runKernel(function(e){return e.step(r,t)},{$x:r},function(e){return{$x:function(){return TensorOps.zerosLike(e)}}})},__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"neg",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"ceil",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"floor",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"sign",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"round",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"exp",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"expm1",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"log",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"log1p",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"sqrt",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"rsqrt",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"square",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"reciprocal",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"abs",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"clipByValue",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"sigmoid",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"logSigmoid",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"softplus",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"sin",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"cos",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"tan",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"asin",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"acos",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"atan",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"sinh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"cosh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"tanh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"asinh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"acosh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"atanh",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"erf",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"step",null),e}(),BatchNormOps=function(){function e(){}return e.batchNormalization2d=function(t,r,n,a,o,i){void 0===a&&(a=.001);var s,u,l=convertToTensor(t,"x","batchNormalization"),c=convertToTensor(r,"mean","batchNormalization"),p=convertToTensor(n,"variance","batchNormalization");return null!=o&&(s=convertToTensor(o,"scale","batchNormalization")),null!=i&&(u=convertToTensor(i,"offset","batchNormalization")),assert(2===l.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+l.rank+"."),assert(2===c.rank||1===c.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."),assert(2===p.rank||1===p.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+p.rank+"."),null!=s&&assert(2===s.rank||1===s.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+s.rank+"."),null!=u&&assert(2===u.rank||1===u.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+u.rank+"."),e.batchNormalization(l,c,p,a,s,u)},e.batchNormalization3d=function(t,r,n,a,o,i){void 0===a&&(a=.001);var s,u,l=convertToTensor(t,"x","batchNormalization"),c=convertToTensor(r,"mean","batchNormalization"),p=convertToTensor(n,"variance","batchNormalization");return null!=o&&(s=convertToTensor(o,"scale","batchNormalization")),null!=i&&(u=convertToTensor(i,"offset","batchNormalization")),assert(3===l.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+l.rank+"."),assert(3===c.rank||1===c.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."),assert(3===p.rank||1===p.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+p.rank+"."),null!=s&&assert(3===s.rank||1===s.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+s.rank+"."),null!=u&&assert(3===u.rank||1===u.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+u.rank+"."),e.batchNormalization(l,c,p,a,s,u)},e.batchNormalization4d=function(t,r,n,a,o,i){void 0===a&&(a=.001);var s,u,l=convertToTensor(t,"x","batchNormalization"),c=convertToTensor(r,"mean","batchNormalization"),p=convertToTensor(n,"variance","batchNormalization");return null!=o&&(s=convertToTensor(o,"scale","batchNormalization")),null!=i&&(u=convertToTensor(i,"offset","batchNormalization")),assert(4===l.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+l.rank+"."),assert(4===c.rank||1===c.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."),assert(4===p.rank||1===p.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+p.rank+"."),null!=s&&assert(4===s.rank||1===s.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+s.rank+"."),null!=u&&assert(4===u.rank||1===u.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+u.rank+"."),e.batchNormalization(l,c,p,a,s,u)},e.batchNormalization=function(e,t,r,n,a,o){void 0===n&&(n=.001);var i,s,u,l=convertToTensor(e,"x","batchNormalization"),c=convertToTensor(t,"mean","batchNormalization"),p=convertToTensor(r,"variance","batchNormalization");return null!=a&&(i=convertToTensor(a,"scale","batchNormalization")),null!=o&&(s=convertToTensor(o,"offset","batchNormalization")),assert(c.rank===p.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),assert(null==s||c.rank===s.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),assert(null==i||c.rank===i.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,ENV.engine.runKernel(function(e){return e.batchNormalization(u,batchnormReshape4D(c),batchnormReshape4D(p),n,batchnormReshape4D(i),batchnormReshape4D(s))},{$x:l,$mean:c,$variance:p,$scale:i,$offset:s},function(e){var t=null==i?TensorOps.scalar(1):i,r=getReductionAxes(c.shape,u.shape),a=[];if(1===c.rank){for(var o=0;o0&&(t=t.sum(n)),t.reshape(r.shape)},$b:function(){var t=e,r=getReductionAxes(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)}}})},e.addStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in addStrict: "),e.add(t)},e.sub=function(e,t){var r=convertToTensor(e,"a","sub"),n=convertToTensor(t,"b","sub");assertTypesMatch(r,n);var a=assertAndGetBroadcastShape(r.shape,n.shape);return ENV.engine.runKernel(function(e){return e.subtract(r,n)},{$a:r,$b:n},function(e){return{$a:function(){var t=e,n=getReductionAxes(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},$b:function(){var t=e,r=getReductionAxes(n.shape,a);return r.length>0&&(t=t.sum(r)),t.neg().reshape(n.shape)}}})},e.subStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in subStrict: "),e.sub(t)},e.pow=function(e,t){var r=convertToTensor(e,"base","pow"),n=convertToTensor(t,"exp","pow"),a=assertAndGetBroadcastShape(r.shape,n.shape);return e=r.cast(upcastType(r.dtype,n.dtype)),t=n.cast(upcastType(r.dtype,n.dtype)),ENV.engine.runKernel(function(e,t){return t(e.pow(r,n))},{$base:r,$exp:n},function(e,t){var o=t[0];return{$base:function(){var t=e.mul(n.toFloat().mul(o.div(r))),i=getReductionAxes(r.shape,a);return i.length>0&&(t=t.sum(i)),t.reshape(r.shape)},$exp:function(){var t=e.mul(o.mul(r.log()).toFloat()),i=getReductionAxes(n.shape,a);return i.length>0&&(t=t.sum(i)),t.reshape(n.shape)}}})},e.powStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in powStrict: "),e.pow(t)},e.mul=function(e,t){var r=convertToTensor(e,"a","mul"),n=convertToTensor(t,"b","mul");assertTypesMatch(r,n);var a=assertAndGetBroadcastShape(r.shape,n.shape);return ENV.engine.runKernel(function(e){return e.multiply(r,n)},{$a:r,$b:n},function(e){return{$a:function(){var t=e.mul(n.toFloat()),o=getReductionAxes(r.shape,a);return o.length>0?t.sum(o).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),o=getReductionAxes(n.shape,a);return o.length>0?t.sum(o).reshape(n.shape):t}}})},e.mulStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)},e.div=function(t,r){var n,a=convertToTensor(t,"a","div"),o=convertToTensor(r,"b","div");if(assertTypesMatch(a,o),"int32"===a.dtype&&"int32"===o.dtype)return e.floorDiv(a,o);n=function(e){return e.realDivide(a,o)};var i=assertAndGetBroadcastShape(a.shape,o.shape);return ENV.engine.runKernel(n,{$a:a,$b:o},function(e){return{$a:function(){var t=e.div(o.toFloat()),r=getReductionAxes(a.shape,i);return r.length>0?t.sum(r).reshape(a.shape):t},$b:function(){var t=e.mul(a.toFloat()),r=getReductionAxes(o.shape,i);r.length>0&&(t=t.sum(r).reshape(o.shape));var n=o.square();return t.div(n.toFloat()).neg()}}})},e.floorDiv=function(e,t){var r=convertToTensor(e,"a","floorDiv"),n=convertToTensor(t,"b","floorDiv");assertTypesMatch(r,n);var a=assertAndGetBroadcastShape(r.shape,n.shape);return ENV.engine.runKernel(function(e){return e.floorDiv(r,n)},{$a:r,$b:n},function(e){return{$a:function(){var t=e.div(n.toFloat()),o=getReductionAxes(r.shape,a);return o.length>0?t.sum(o).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),o=getReductionAxes(n.shape,a);o.length>0&&(t=t.sum(o).reshape(n.shape));var i=n.square();return t.div(i.toFloat()).neg()}}})},e.divStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in divideStrict: "),e.div(t)},e.mod=function(e,t){var r=convertToTensor(e,"a","mod"),n=convertToTensor(t,"b","mod");assertTypesMatch(r,n);var a=assertAndGetBroadcastShape(r.shape,n.shape);return ENV.engine.runKernel(function(e){return e.mod(r,n)},{$a:r,$b:n},function(e){return{$a:function(){var t=getReductionAxes(r.shape,a);return t.length>0?e.sum(t).reshape(r.shape):e},$b:function(){var t=e.mul(r.div(n).floor().neg()),o=getReductionAxes(n.shape,a);return o.length>0?t.sum(o).reshape(n.shape):t}}})},e.modStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in modStrict: "),e.mod(t)},e.minimum=function(e,t){var r=convertToTensor(e,"a","minimum"),n=convertToTensor(t,"b","minimum");return assertTypesMatch(r,n),"bool"===r.dtype&&(r=r.toInt()),"bool"===n.dtype&&(n=n.toInt()),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.minimum(r,n)},{$a:r,$b:n},function(e){return{$a:function(){return e.mul(r.lessEqual(n).toFloat())},$b:function(){return e.mul(r.greater(n).toFloat())}}})},e.minimumStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)},e.maximum=function(e,t){var r=convertToTensor(e,"a","maximum"),n=convertToTensor(t,"b","maximum");return assertTypesMatch(r,n),"bool"===r.dtype&&(r=r.toInt()),"bool"===n.dtype&&(n=n.toInt()),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.maximum(r,n)},{$a:r,$b:n},function(e){return{$a:function(){return e.mul(r.greaterEqual(n).toFloat())},$b:function(){return e.mul(r.less(n).toFloat())}}})},e.maximumStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in minimumStrict: "),e.maximum(t)},e.squaredDifference=function(e,t){var r=convertToTensor(e,"a","squaredDifference"),n=convertToTensor(t,"b","squaredDifference");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.squaredDifference(r,n)},{$a:r,$b:n},function(e){var t=TensorOps.scalar(2);return{$a:function(){return e.mul(r.sub(n).mul(t))},$b:function(){return e.mul(n.sub(r).mul(t))}}})},e.squaredDifferenceStrict=function(e,t){return assertShapesMatch(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)},e.atan2=function(t,r){var n=convertToTensor(t,"a","atan2"),a=convertToTensor(r,"b","atan2");assertTypesMatch(n,a);var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.atan2(n,a)},{$a:n,$b:a},function(t){return{$a:function(){var r=e.add(n.square(),a.square()),i=t.mul(a.div(r)),s=getReductionAxes(n.shape,o);return s.length>0&&(i=i.sum(s)),i.reshape(n.shape)},$b:function(){var r=e.add(n.square(),a.square()),i=UnaryOps.neg(t.mul(n.div(r))),s=getReductionAxes(a.shape,o);return s.length>0&&(i=i.sum(s)),i.reshape(a.shape)}}})},__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"add",null),__decorate([operation],e,"addStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"sub",null),__decorate([operation],e,"subStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"pow",null),__decorate([operation],e,"powStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"mul",null),__decorate([operation],e,"mulStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"div",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"floorDiv",null),__decorate([operation],e,"divStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"mod",null),__decorate([operation],e,"modStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"minimum",null),__decorate([operation],e,"minimumStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"maximum",null),__decorate([operation],e,"maximumStrict",null),__decorate([doc({heading:"Operations",subheading:"Arithmetic"}),operation],e,"squaredDifference",null),__decorate([operation],e,"squaredDifferenceStrict",null),__decorate([doc({heading:"Operations",subheading:"Basic math"}),operation],e,"atan2",null),e}(),CompareOps=function(){function e(){}return e.notEqual=function(e,t){var r=convertToTensor(e,"a","notEqual"),n=convertToTensor(t,"b","notEqual");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.notEqual(r,n)},{$a:r,$b:n})},e.notEqualStrict=function(e,t){var r=convertToTensor(e,"a","notEqualStrict"),n=convertToTensor(t,"b","notEqualStrict");return assertShapesMatch(r.shape,n.shape,"Error in notEqualStrict: "),r.notEqual(n)},e.less=function(e,t){var r=convertToTensor(e,"a","less"),n=convertToTensor(t,"b","less");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.less(r,n)},{$a:r,$b:n})},e.lessStrict=function(e,t){var r=convertToTensor(e,"a","lessStrict"),n=convertToTensor(t,"b","lessStrict");return assertShapesMatch(r.shape,n.shape,"Error in lessStrict: "),r.less(n)},e.equal=function(e,t){var r=convertToTensor(e,"a","equal"),n=convertToTensor(t,"b","equal");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.equal(r,n)},{$a:r,$b:n})},e.equalStrict=function(e,t){var r=convertToTensor(e,"a","equalStrict"),n=convertToTensor(t,"b","equalStrict");return assertShapesMatch(r.shape,n.shape,"Error in equalStrict: "),r.equal(n)},e.lessEqual=function(e,t){var r=convertToTensor(e,"a","lessEqual"),n=convertToTensor(t,"b","lessEqual");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.lessEqual(r,n)},{$a:r,$b:n})},e.lessEqualStrict=function(e,t){var r=convertToTensor(e,"a","lessEqualStrict"),n=convertToTensor(t,"b","lessEqualStrict");return assertShapesMatch(r.shape,n.shape,"Error in lessEqualStrict: "),r.lessEqual(n)},e.greater=function(e,t){var r=convertToTensor(e,"a","greater"),n=convertToTensor(t,"b","greater");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.greater(r,n)},{$a:r,$b:n})},e.greaterStrict=function(e,t){var r=convertToTensor(e,"a","greaterStrict"),n=convertToTensor(t,"b","greaterStrict");return assertShapesMatch(r.shape,n.shape,"Error in greaterStrict: "),r.greater(n)},e.greaterEqual=function(e,t){var r=convertToTensor(e,"a","greaterEqual"),n=convertToTensor(t,"b","greaterEqual");return assertTypesMatch(r,n),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.greaterEqual(r,n)},{$a:r,$b:n})},e.greaterEqualStrict=function(e,t){var r=convertToTensor(e,"a","greaterEqualStrict"),n=convertToTensor(t,"b","greaterEqualStrict");return assertShapesMatch(r.shape,n.shape,"Error in greaterEqualStrict: "),r.greaterEqual(n)},__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"notEqual",null),__decorate([operation],e,"notEqualStrict",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"less",null),__decorate([operation],e,"lessStrict",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"equal",null),__decorate([operation],e,"equalStrict",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"lessEqual",null),__decorate([operation],e,"lessEqualStrict",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"greater",null),__decorate([operation],e,"greaterStrict",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"greaterEqual",null),__decorate([operation],e,"greaterEqualStrict",null),e}();function computePool2DInfo(e,t,r,n,a,o){void 0===o&&(o="channelsLast");var i,s=parseTupleParam(t),u=s[0],l=s[1];if("channelsLast"===o)i=[u,l,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);i=[u,l,e[1],e[1]]}return computeConv2DInfo(e,i,r,1,n,a,!1,o)}function computeConv2DInfo(e,t,r,n,a,o,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],p=u[2],d=u[3];if("channelsLast"===s)l=e[0],c=e[1],p=e[2],d=e[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=e[0],d=e[1],c=e[2],p=e[3]}var h,f=t[0],m=t[1],g=t[3],y=parseTupleParam(r),v=y[0],b=y[1],x=parseTupleParam(n),w=x[0],S=x[1],T=getPadAndOutInfo(a,c,p,v,b,getEffectiveFilterSize(f,w),getEffectiveFilterSize(m,S),o),N=T.padInfo,E=T.outHeight,_=T.outWidth,A=i?g*d:g;return"channelsFirst"===s?h=[l,A,E,_]:"channelsLast"===s&&(h=[l,E,_,A]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:p,inChannels:d,outHeight:E,outWidth:_,outChannels:A,padInfo:N,strideHeight:v,strideWidth:b,filterHeight:f,filterWidth:m,dilationHeight:w,dilationWidth:S,inShape:e,outShape:h,filterShape:t}}function computeOutputShape3D(e,t,r,n,a,o){null==a&&(a=computeDefaultPad(e,t,n));var i=e[0],s=e[1],u=conditionalRound((i-t+2*a)/n+1,o);assert(isInt(u),"The output # of rows ("+u+") must be an integer. Change the stride and/or zero pad parameters");var l=conditionalRound((s-t+2*a)/n+1,o);return assert(isInt(l),"The output # of columns ("+l+") must be an integer. Change the stride and/or zero pad parameters"),[u,l,r]}function computeDefaultPad(e,t,r,n){void 0===n&&(n=1);var a=getEffectiveFilterSize(t,n);return Math.floor((e[0]*(r-1)-r+a)/2)}function parseTupleParam(e){return"number"==typeof e?[e,e]:e}function getEffectiveFilterSize(e,t){return t<=1?e:e+(e-1)*(t-1)}function getPadAndOutInfo(e,t,r,n,a,o,i,s){var u,l,c;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};var p=computeOutputShape3D([t,r,1],o,1,n,e,s);l=p[0],c=p[1]}else if("same"===e){var d=((l=Math.ceil(t/n))-1)*n+o-t,h=((c=Math.ceil(r/a))-1)*a+i-r,f=Math.floor(d/2),m=d-f,g=Math.floor(h/2);u={top:f,bottom:m,left:g,right:h-g,type:"SAME"}}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);u={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-o+1)/n),c=Math.ceil((r-i+1)/a)}return{padInfo:u,outHeight:l,outWidth:c}}function conditionalRound(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error("Unknown roundingMode "+t)}}var ConvOps=function(){function e(){}return e.conv1d=function(t,r,n,a,o,i,s){void 0===o&&(o="NWC"),void 0===i&&(i=1);var u=convertToTensor(t,"x","conv1d"),l=convertToTensor(r,"filter","conv1d"),c=u,p=!1;2===u.rank&&(p=!0,c=u.as3D(1,u.shape[0],u.shape[1])),assert(3===c.rank,"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."),assert(3===l.rank,"Error in conv1d: filter must be rank 3, but got rank "+l.rank+"."),null!=s&&assert(isInt(a),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."),assert(c.shape[2]===l.shape[1],"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+l.shape[1]+"."),assert(eitherStridesOrDilationsAreOne(n,i),"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"),assert("NWC"===o,"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported.");var d=l.as4D(1,l.shape[0],l.shape[1],l.shape[2]),h=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),f=[1,n],m=[1,i],g=e.conv2d(h,d,f,a,"NHWC",m,s);return p?g.as2D(g.shape[2],g.shape[3]):g.as3D(g.shape[0],g.shape[2],g.shape[3])},e.conv2d=function(t,r,n,a,o,i,s){void 0===o&&(o="NHWC"),void 0===i&&(i=[1,1]);var u=convertToTensor(t,"x","conv2d"),l=convertToTensor(r,"filter","conv2d"),c=u,p=!1;3===u.rank&&(p=!0,c=u.as4D(1,u.shape[0],u.shape[1],u.shape[2])),assert(4===c.rank,"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."),assert(4===l.rank,"Error in conv2d: filter must be rank 4, but got rank "+l.rank+"."),null!=s&&assert(isInt(a),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."),assert(c.shape[3]===l.shape[2],"Error in conv2d: depth of input ("+c.shape[3]+") must match input depth for filter "+l.shape[2]+"."),assert(eitherStridesOrDilationsAreOne(n,i),"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),assert("NHWC"===o,"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported.");var d=computeConv2DInfo(c.shape,l.shape,n,i,a,s),h=ENV.engine.runKernel(function(e){return e.conv2d(c,l,d)},{x:c,$filter:l},function(t){return assert(tupleValuesAreOne(i),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+i+"'"),{x:function(){return e.conv2dDerInput(c.shape,t,l,n,a)},$filter:function(){return e.conv2dDerFilter(c,t,l.shape,n,a)}}});return p?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h},e.conv2dDerInput=function(e,t,r,n,a,o){assert(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var i=e,s=t,u=!1;3===t.rank&&(u=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),i=[1,e[0],e[1],e[2]]);var l=i[3],c=s.shape[3];assert(4===i.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+i.length+"."),assert(4===s.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank),assert(4===r.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+r.rank),assert(l===r.shape[2],"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+r.shape[2]+"."),assert(c===r.shape[3],"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+r.shape[3]+"."),null!=o&&assert(isInt(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var p=computeConv2DInfo(i,r.shape,n,1,a,o),d=ENV.engine.runKernel(function(e){return e.conv2dDerInput(s,r,p)},{dy4D:s});return u?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d},e.conv2dDerFilter=function(e,t,r,n,a,o){var i=e;3===e.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t;3===s.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),assert(4===i.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+i.shape+"."),assert(4===s.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."),assert(4===r.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+r+"."),assert(i.shape[3]===r[2],"Error in conv2dDerFilter: depth of input "+i.shape[3]+") must match input depth in filter ("+r[2]+"."),assert(s.shape[3]===r[3],"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+r[3]+")."),null!=o&&assert(isInt(a),"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var u=computeConv2DInfo(i.shape,r,n,1,a,o);return ENV.engine.runKernel(function(e){return e.conv2dDerFilter(i,s,u)},{x4D:i,dy4D:s})},e.conv2dTranspose=function(t,r,n,a,o,i){var s=convertToTensor(t,"x","conv2dTranspose"),u=convertToTensor(r,"filter","conv2dTranspose");return e.conv2dDerInput(n,s,u,a,o,i)},e.depthwiseConv2d=function(e,t,r,n,a,o,i){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1]);var s=convertToTensor(e,"x","depthwiseConv2d"),u=convertToTensor(t,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),assert(4===l.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."),assert(4===u.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),assert(l.shape[3]===u.shape[2],"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."),null==o&&(o=[1,1]),assert(eitherStridesOrDilationsAreOne(r,o),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"),null!=i&&assert(isInt(n),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+".");var p=computeConv2DInfo(l.shape,u.shape,r,o,n,i,!0),d=ENV.engine.runKernel(function(e){return e.depthwiseConv2D(l,u,p)},{x:l,$filter:u},function(e){return assert(tupleValuesAreOne(o),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"),{x:function(){return depthwiseConv2dDerInput(l.shape,e,u,p)},$filter:function(){return depthwiseConv2dDerFilter(l,e,u.shape,p)}}});return c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d},e.separableConv2d=function(t,r,n,a,o,i,s){void 0===i&&(i=[1,1]),void 0===s&&(s="NHWC");var u=convertToTensor(t,"x","separableConv2d"),l=convertToTensor(r,"depthwiseFilter","separableConv2d"),c=convertToTensor(n,"pointwiseFilter","separableConv2d"),p=u,d=!1;if(3===u.rank&&(d=!0,p=u.as4D(1,u.shape[0],u.shape[1],u.shape[2])),"NCHW"===s)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");assert(4===p.rank,"Error in separableConv2d: input must be rank 4, but got rank "+p.rank+"."),assert(4===l.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+l.rank+"."),assert(4===c.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+l.rank+"."),assert(1===c.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."),assert(1===c.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+".");var h=l.shape[2],f=l.shape[3];assert(c.shape[2]===h*f,"Error in separableConv2d: the third dimension of pointwise filter must be "+h*f+", but got "+c.shape[2]+".");var m=e.depthwiseConv2d(p,l,a,o,s,i),g=e.conv2d(m,c,1,"valid",s);return d?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g},__decorate([doc({heading:"Operations",subheading:"Convolution"}),operation],e,"conv1d",null),__decorate([doc({heading:"Operations",subheading:"Convolution"}),operation],e,"conv2d",null),__decorate([operation],e,"conv2dDerInput",null),__decorate([operation],e,"conv2dDerFilter",null),__decorate([doc({heading:"Operations",subheading:"Convolution"}),operation],e,"conv2dTranspose",null),__decorate([doc({heading:"Operations",subheading:"Convolution"}),operation],e,"depthwiseConv2d",null),__decorate([doc({heading:"Operations",subheading:"Convolution"}),operation],e,"separableConv2d",null),e}();function parseTupleParam$1(e){return"number"==typeof e?[e,e]:e}function tupleValuesAreOne(e){var t=parseTupleParam$1(e),r=t[0],n=t[1];return 1===r&&1===n}function eitherStridesOrDilationsAreOne(e,t){return tupleValuesAreOne(e)||tupleValuesAreOne(t)}function depthwiseConv2dDerInput(e,t,r,n){var a=t,o=!1;3===t.rank&&(o=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,r,n)},{dy4D:a});return o?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}function depthwiseConv2dDerFilter(e,t,r,n){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=t;return 3===o.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,o,n)},{x4D:a,dy4D:o})}var ImageOps=function(){function e(){}return e.resizeBilinear=function(e,t,r){void 0===r&&(r=!1);var n=convertToTensor(e,"images","resizeBilinear");assert(3===n.rank||4===n.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."),assert(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=n,o=!1;3===n.rank&&(o=!0,a=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=ENV.engine.runKernel(function(e,t){return e.resizeBilinear(a,i,s,r)},{batchImages:a},function(e,t){return{batchImages:function(){return ENV.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,r)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u},e.resizeNearestNeighbor=function(e,t,r){void 0===r&&(r=!1);var n=convertToTensor(e,"images","resizeNearestNeighbor");assert(3===n.rank||4===n.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."),assert(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),assert("float32"===n.dtype||"int32"===n.dtype,"`images` must have `int32` or `float32` as dtype");var a=n,o=!1;3===n.rank&&(o=!0,a=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=ENV.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,i,s,r)},{batchImages:a},function(e,t){return{batchImages:function(){return ENV.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,r)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u},__decorate([doc({heading:"Operations",subheading:"Images",namespace:"image"}),operation],e,"resizeBilinear",null),__decorate([doc({heading:"Operations",subheading:"Images",namespace:"image"}),operation],e,"resizeNearestNeighbor",null),e}(),Gradients=function(){function e(){}return e.gradScope=function(e,t){return ENV.engine.tidy(e,t,!0)},e.grad=function(e){return assert(isFunction(e),"The f passed in grad(f) must be a function"),function(t,r){return assert(t instanceof Tensor,"The x passed in grad(f)(x) must be a tensor"),assert(null==r||r instanceof Tensor,"The dy passed in grad(f)(x, dy) must be a tensor"),ENV.engine.tidy(function(){var n=ENV.engine.gradients(function(){return e(t)},[t],r),a=n.value,o=n.grads;return null!=r&&assertShapesMatch(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),checkGrads(o),o[0]})}},e.grads=function(e){return assert(isFunction(e),"The f passed in grads(f) must be a function"),function(t,r){return assert(Array.isArray(t)&&t.every(function(e){return e instanceof Tensor}),"The args passed in grads(f)(args) must be an array of tensors"),assert(null==r||r instanceof Tensor,"The dy passed in grads(f)(args, dy) must be a tensor"),ENV.engine.tidy(function(){var n=ENV.engine.gradients(function(){return e.apply(void 0,t)},t,r),a=n.value,o=n.grads;return null!=r&&assertShapesMatch(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(o),o})}},e.valueAndGrad=function(e){return assert(isFunction(e),"The f passed in valueAndGrad(f) must be a function"),function(t,r){assert(t instanceof Tensor,"The x passed in valueAndGrad(f)(x) must be a tensor"),assert(null==r||r instanceof Tensor,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var n=ENV.engine.gradients(function(){return e(t)},[t],r),a=n.grads,o=n.value;return checkGrads(a),{grad:a[0],value:o}}},e.valueAndGrads=function(e){return assert(isFunction(e),"The f passed in valueAndGrads(f) must be a function"),function(t,r){assert(Array.isArray(t)&&t.every(function(e){return e instanceof Tensor}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),assert(null==r||r instanceof Tensor,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var n=ENV.engine.gradients(function(){return e.apply(void 0,t)},t,r);return null!=r&&assertShapesMatch(n.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(n.grads),n}},e.variableGrads=function(e,t){if(assert(isFunction(e),"The f passed in variableGrads(f) must be a function"),assert(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof Variable}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var r in t=[],ENV.engine.registeredVariables)t.push(ENV.engine.registeredVariables[r]);var n=t.length;assert((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+n+" variables is trainable.");var a=ENV.engine.gradients(e,t,null,!0),o=a.value,i=a.grads;assert(i.some(function(e){return null!=e}),"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),assert(0===o.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+o.rank+" tensor");var s={};return t.forEach(function(e,t){null!=i[t]&&(s[e.name]=i[t])}),{value:o,grads:s}},e.customGrad=function(e){return ENV.engine.customGrad(e)},__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"grad",null),__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"grads",null),__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"valueAndGrad",null),__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"valueAndGrads",null),__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"variableGrads",null),__decorate([doc({heading:"Training",subheading:"Gradients"})],e,"customGrad",null),e}();function checkGrads(e){if(e.filter(function(e){return null==e}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var tidy=Environment.tidy,keep=Environment.keep,dispose=Environment.dispose,time=Environment.time,grad=Gradients.grad,valueAndGrad=Gradients.valueAndGrad,grads=Gradients.grads,valueAndGrads=Gradients.valueAndGrads,variableGrads=Gradients.variableGrads,customGrad=Gradients.customGrad,NormOps=function(){function e(){}return e.norm=function(e,t,r,n){void 0===t&&(t="euclidean"),void 0===r&&(r=null),void 0===n&&(n=!1);var a=normImpl(e=convertToTensor(e,"x","norm"),t,r),o=a.shape;if(n){var i=parseAxisParam(r,e.shape);o=expandShapeToKeepDim(a.shape,i)}return a.reshape(o)},__decorate([doc({heading:"Operations",subheading:"Matrices"}),operation],e,"norm",null),e}();function normImpl(e,t,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return normImpl(e.reshape([-1]),t,r);if(1===e.rank||"number"==typeof r||r instanceof Array&&1===r.length){if(1===t)return e.abs().sum(r);if(t===1/0)return e.abs().max(r);if(t===-1/0)return e.abs().min(r);if("euclidean"===t||2===t)return e.abs().pow(TensorOps.scalar(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+t)}if(r instanceof Array&&2===r.length){if(1===t)return e.abs().sum(r[0]).max(r[1]-1);if(t===1/0)return e.abs().sum(r[1]).max(r[0]);if(t===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===t||"euclidean"===t)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+t)}throw new Error("Error in norm: invalid axis: "+r)}var ReductionOps=function(){function e(){}return e.logSumExp=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","logSumExp"),a=parseAxisParam(t,n.shape),o=n.max(a,!0),i=n.sub(o).exp().sum(a).log(),s=o.reshape(i.shape).add(i);if(r){var u=expandShapeToKeepDim(s.shape,a);return s.reshape(u)}return s},e.sum=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","sum");"bool"===n.dtype&&(n=n.toInt());var a=parseAxisParam(t,n.shape);return customGrad(function(e){var t=getAxesPermutation(a,e.rank),n=a,o=e;null!=t&&(o=e.transpose(t),n=getInnerMostAxes(n.length,e.rank));var i=ENV.engine.runKernel(function(e){return e.sum(o,n)},{permutedX:o});if(r){var s=expandShapeToKeepDim(i.shape,a);i=i.reshape(s)}return{value:i,gradFunc:function(t){var r=e.shape.slice();return a.forEach(function(e){r[e]=1}),t.reshape(r).mul(TensorOps.ones(e.shape,"float32"))}}})(n)},e.mean=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","mean"),a=parseAxisParam(t,n.shape),o=sizeFromShape(computeOutAndReduceShapes(n.shape,a)[1]);return customGrad(function(e){var n=TensorOps.scalar(o);return{value:(n.dtype===e.dtype?e:e.cast(n.dtype)).div(n).sum(t,r),gradFunc:function(t){var r=e.shape.slice();return a.forEach(function(e){r[e]=1}),t.reshape(r).mul(TensorOps.ones(e.shape,"float32")).div(n)}}})(n)},e.min=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","min"),a=parseAxisParam(t,n.shape),o=a,i=getAxesPermutation(o,n.rank);null!=i&&(n=n.transpose(i),o=getInnerMostAxes(o.length,n.rank));var s=ENV.engine.runKernel(function(e){return e.min(n,o)},{$x:n});if(r){var u=expandShapeToKeepDim(s.shape,a);return s.reshape(u)}return s},e.max=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","max"),a=parseAxisParam(t,n.shape),o=a,i=getAxesPermutation(o,n.rank);null!=i&&(n=n.transpose(i),o=getInnerMostAxes(o.length,n.rank));var s=ENV.engine.runKernel(function(e){return e.max(n,o)},{$x:n});if(r){var u=expandShapeToKeepDim(s.shape,a);return s.reshape(u)}return s},e.argMin=function(e,t){void 0===t&&(t=0);var r=convertToTensor(e,"x","argMin");null==t&&(t=0);var n=parseAxisParam(t,r.shape),a=getAxesPermutation(n,r.rank);return null!=a&&(r=r.transpose(a),n=getInnerMostAxes(n.length,r.rank)),ENV.engine.runKernel(function(e){return e.argMin(r,n[0])},{$x:r})},e.argMax=function(e,t){void 0===t&&(t=0);var r=convertToTensor(e,"x","argMax");null==t&&(t=0);var n=parseAxisParam(t,r.shape),a=getAxesPermutation(n,r.rank);return null!=a&&(r=r.transpose(a),n=getInnerMostAxes(n.length,r.rank)),ENV.engine.runKernel(function(e){return e.argMax(r,n[0])},{$x:r})},e.all=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","all","bool");assert("bool"===n.dtype,"Error Tensor must be of type bool. Got: "+n.dtype);var a=parseAxisParam(t,n.shape),o=a,i=getAxesPermutation(o,n.rank);null!=i&&(n=n.transpose(i),o=getInnerMostAxes(o.length,n.rank));var s=ENV.engine.runKernel(function(e){return e.all(n,o)},{$x:n});if(r){var u=expandShapeToKeepDim(s.shape,a);return s.reshape(u)}return s},e.any=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=convertToTensor(e,"x","any","bool");assert("bool"===n.dtype,"Error Tensor must be of type bool. Got: "+n.dtype);var a=parseAxisParam(t,n.shape),o=a,i=getAxesPermutation(o,n.rank);null!=i&&(n=n.transpose(i),o=getInnerMostAxes(o.length,n.rank));var s=ENV.engine.runKernel(function(e){return e.any(n,o)},{$x:n});if(r){var u=expandShapeToKeepDim(s.shape,a);return s.reshape(u)}return s},e.moments=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r=!1);var n=parseAxisParam(t,(e=convertToTensor(e,"x","moments")).shape),a=e.mean(n,r),o=a.shape;return r||(o=expandShapeToKeepDim(a.shape,n)),{mean:a,variance:e.toFloat().sub(a.reshape(o)).square().mean(n,r)}},__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"logSumExp",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"sum",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"mean",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"min",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"max",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"argMin",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"argMax",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"all",null),__decorate([doc({heading:"Operations",subheading:"Reduction"}),operation],e,"any",null),__decorate([doc({heading:"Operations",subheading:"Normalization"}),operation],e,"moments",null),e}(),LinalgOps=function(){function e(){}return e.gramSchmidt=function(e){var t;if(Array.isArray(e)){t=!1,assert(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var r=e[0].shape[0],n=1;n0)for(var r=0;r= 2, but got rank "+e.rank);if(2===e.rank)return qr2d(e,t);var r=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),n=[],a=[];return ArrayOps.unstack(e.reshape([r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var r=qr2d(e,t),o=r[0],i=r[1];n.push(o),a.push(i)}),[ArrayOps.stack(n,0).reshape(e.shape),ArrayOps.stack(a,0).reshape(e.shape)]},__decorate([doc({heading:"Operations",subheading:"Linear Algebra"}),operation],e,"gramSchmidt",null),__decorate([doc({heading:"Operations",subheading:"Linear Algebra"}),operation],e,"qr",null),e}();function qr2d(e,t){return void 0===t&&(t=!1),ENV.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var r=e.shape[0],n=e.shape[1],a=ArrayOps.eye(r),o=e.clone(),i=TensorOps.tensor2d([[1]],[1,1]),s=i.clone(),u=r>=n?n:r,l=function(e){var t,u=o,l=s,c=a;t=ENV.engine.tidy(function(){var t=o.slice([e,e],[r-e,1]),u=t.norm(),l=o.slice([e,e],[1,1]),c=l.sign().neg(),p=l.sub(c.mul(u)),d=t.div(p);s=1===d.shape[0]?i.clone():i.concat(d.slice([1,0],[d.shape[0]-1,d.shape[1]]),0);var h=c.matMul(p).div(u).neg(),f=o.slice([e,0],[r-e,n]),m=h.mul(s);o=0===e?f.sub(m.matMul(s.transpose().matMul(f))):o.slice([0,0],[e,n]).concat(f.sub(m.matMul(s.transpose().matMul(f))),0);var g=a.slice([0,e],[r,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[r,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,o,a]}),s=t[0],o=t[1],a=t[2],dispose([u,l,c])},c=0;cn&&(a=a.slice([0,0],[r,n]),o=o.slice([0,0],[n,n])),[a,o]})}var LogicalOps=function(){function e(){}return e.logicalNot=function(e){var t=convertToTensor(e,"x","logicalNot","bool");return assert("bool"===t.dtype,"Error Array must be of type bool."),ENV.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})},e.logicalAnd=function(e,t){var r=convertToTensor(e,"a","logicalAnd","bool"),n=convertToTensor(t,"b","logicalAnd","bool");return assert("bool"===r.dtype&&"bool"===n.dtype,"Error Array must be of type bool."),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.logicalAnd(r,n)},{$a:r,$b:n})},e.logicalOr=function(e,t){var r=convertToTensor(e,"a","logicalOr","bool"),n=convertToTensor(t,"b","logicalOr","bool");return assert("bool"===r.dtype&&"bool"===n.dtype,"Error Array must be of type bool."),assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.logicalOr(r,n)},{$a:r,$b:n})},e.logicalXor=function(t,r){var n=convertToTensor(t,"a","logicalXor","bool"),a=convertToTensor(r,"b","logicalXor","bool");return assert("bool"===n.dtype&&"bool"===a.dtype,"Error Array must be of type bool."),assertAndGetBroadcastShape(n.shape,a.shape),e.logicalOr(t,r).logicalAnd(e.logicalAnd(t,r).logicalNot())},e.where=function(e,t,r){var n=convertToTensor(t,"a","where"),a=convertToTensor(r,"b","where"),o=convertToTensor(e,"condition","where","bool");assert("bool"===o.dtype,"Error Condition must be of type bool."),assertShapesMatch(n.shape,a.shape,"Error in where: "),1===o.rank?assert(o.shape[0]===n.shape[0],"The first dimension of `a` must match the size of `condition`."):assertShapesMatch(o.shape,a.shape,"Error in where: ");var i=upcastType(n.dtype,a.dtype);return ENV.engine.runKernel(function(e){return e.where(o,n,a,i)},{$condition:o,$a:n,$b:a},function(e){return{$condition:function(){return TensorOps.zerosLike(o)},$a:function(){return e.mul(o.cast(n.dtype))},$b:function(){return e.mul(o.logicalNot().cast(a.dtype))}}})},__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"logicalNot",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"logicalAnd",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"logicalOr",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"logicalXor",null),__decorate([doc({heading:"Operations",subheading:"Logical"}),operation],e,"where",null),e}();!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(exports.Reduction||(exports.Reduction={}));var LossOps=function(){function e(){}return e.computeWeightedLoss=function(e,t,r){void 0===r&&(r=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var n=convertToTensor(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=convertToTensor(t,"weights","computeWeightedLoss"));var o=null==a?n:n.mul(a);if(r===exports.Reduction.NONE)return o;if(r===exports.Reduction.SUM)return o.sum();if(r===exports.Reduction.MEAN)return null==a?o.mean():o.sum().div(a.sum());if(r===exports.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(TensorOps.scalar(n.size));var i=a.mul(TensorOps.ones(n.shape)).notEqual(TensorOps.scalar(0)).sum().toFloat();return o.sum().div(i)}throw Error("Unknown reduction: "+r)},e.absoluteDifference=function(t,r,n,a){void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(t,"labels","absoluteDifference"),i=convertToTensor(r,"predictions","absoluteDifference"),s=null;null!=n&&(s=convertToTensor(n,"weights","absoluteDifference")),assertShapesMatch(o.shape,i.shape,"Error in absoluteDifference: ");var u=o.sub(i).abs();return e.computeWeightedLoss(u,s,a)},e.meanSquaredError=function(t,r,n,a){void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(t,"labels","meanSquaredError"),i=convertToTensor(r,"predictions","meanSquaredError"),s=null;null!=n&&(s=convertToTensor(n,"weights","meanSquaredError")),assertShapesMatch(o.shape,i.shape,"Error in meanSquaredError: ");var u=o.squaredDifference(i);return e.computeWeightedLoss(u,s,a)},e.cosineDistance=function(t,r,n,a,o){void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=convertToTensor(t,"labels","cosineDistance"),s=convertToTensor(r,"predictions","cosineDistance"),u=null;null!=a&&(u=convertToTensor(a,"weights","cosineDistance")),assertShapesMatch(i.shape,s.shape,"Error in cosineDistance: ");var l=TensorOps.scalar(1).sub(i.mul(s).sum(n,!0));return e.computeWeightedLoss(l,u,o)},e.hingeLoss=function(t,r,n,a){void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(t,"labels","hingeLoss"),i=convertToTensor(r,"predictions","hingeLoss"),s=null;null!=n&&(s=convertToTensor(n,"weights","hingeLoss")),assertShapesMatch(o.shape,i.shape,"Error in hingeLoss: ");var u=TensorOps.scalar(1);o=TensorOps.scalar(2).mul(o).sub(u);var l=u.sub(o.mul(i)).relu();return e.computeWeightedLoss(l,s,a)},e.logLoss=function(t,r,n,a,o){void 0===a&&(a=1e-7),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=convertToTensor(t,"labels","logLoss"),s=convertToTensor(r,"predictions","logLoss"),u=null;null!=n&&(u=convertToTensor(n,"weights","logLoss")),assertShapesMatch(i.shape,s.shape,"Error in logLoss: ");var l=TensorOps.scalar(1),c=TensorOps.scalar(a),p=i.mul(s.add(c).log()).neg().sub(l.sub(i).mul(l.sub(s).add(c).log()));return e.computeWeightedLoss(p,u,o)},e.huberLoss=function(t,r,n,a,o){void 0===a&&(a=1),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=convertToTensor(t,"labels","huberLoss"),s=convertToTensor(r,"predictions","huberLoss"),u=null;null!=n&&(u=convertToTensor(n,"weights","huberLoss")),assertShapesMatch(i.shape,s.shape,"Error in huberLoss: ");var l=TensorOps.scalar(a),c=s.sub(i).abs(),p=BinaryOps.minimum(c,l),d=c.sub(p),h=TensorOps.scalar(.5).mul(p.square()).add(l.mul(d));return e.computeWeightedLoss(h,u,o)},__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"computeWeightedLoss",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"absoluteDifference",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"meanSquaredError",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"cosineDistance",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"hingeLoss",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"logLoss",null),__decorate([doc({heading:"Training",subheading:"Losses",namespace:"losses"}),operation],e,"huberLoss",null),e}(),LRNOps=function(){function e(){}return e.localResponseNormalization=function(e,t,r,n,a){void 0===t&&(t=5),void 0===r&&(r=1),void 0===n&&(n=1),void 0===a&&(a=.5);var o=convertToTensor(e,"x","localResponseNormalization");assert(4===o.rank||3===o.rank,"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+o.rank+"."),assert(isInt(t),"Error in localResponseNormalization: depthRadius must be an integer\n but got depthRadius "+t+".");var i=o,s=!1;3===o.rank&&(s=!0,i=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]));var u=ENV.engine.runKernel(function(e){return e.localResponseNormalization4D(i,t,r,n,a)},{x4D:i});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u},__decorate([doc({heading:"Operations",subheading:"Normalization"}),operation],e,"localResponseNormalization",null),e}(),LSTMOps=function(){function e(){}return e.multiRNNCell=function(e,t,r,n){for(var a=convertToTensor(t,"data","multiRNNCell"),o=convertToTensorArray(r,"c","multiRNNCell"),i=convertToTensorArray(n,"h","multiRNNCell"),s=a,u=[],l=0;l0?a>=s[t]:a<=s[t]);a+=n[t])r+=1;return r}),[i,l]}function startForAxis(e,t,r,n,a){var o=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var i=n[a];return o<0&&(o+=i),clamp(0,o,i-1)}function stopForAxis(e,t,r,n,a){var o=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var i=n[a];return o<0&&(o+=i),r[a]>0?clamp(0,o,i):clamp(-1,o,i-1)}var SliceOps=function(){function e(){}return e.slice1d=function(t,r,n){var a=convertToTensor(t,"x","slice1d");return assert(1===a.rank,"slice1d expects a rank-1 tensor, but got a rank-"+a.rank+" tensor"),e.slice(a,[r],[n])},e.slice2d=function(t,r,n){var a=convertToTensor(t,"x","slice2d");return assert(2===a.rank,"slice1d expects a rank-2 tensor, but got a rank-"+a.rank+" tensor"),e.slice(a,r,n)},e.slice3d=function(t,r,n){var a=convertToTensor(t,"x","slice3d");return assert(3===a.rank,"slice1d expects a rank-3 tensor, but got a rank-"+a.rank+" tensor"),e.slice(a,r,n)},e.slice4d=function(t,r,n){var a=convertToTensor(t,"x","slice4d");return assert(4===a.rank,"slice1d expects a rank-4 tensor, but got a rank-"+a.rank+" tensor"),e.slice(a,r,n)},e.slice=function(e,t,r){var n,a,o=convertToTensor(e,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");n="number"==typeof t?[t].concat(new Array(o.rank-1).fill(0)):t.length=0?e:(assert(-1===e,"Bad value in size"),o.shape[t]-n[t])}),assertParamsValid(o,n,a);var i=o.shape;return ENV.engine.runKernel(function(e){return e.slice(o,n,a)},{$x:o},function(e){for(var t=[],r=0;r=0&&et||r===e){n=!0;break}r=nearestDivisor(e,r+1)}return r}function computeOutShape$1(e,t,r){for(var n=[],a=e.length,o=0;o":"<",u=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n int bestIndex = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < "+n+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "},AvgPool2DBackpropProgram=function(e){this.variableNames=["dy"],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=1/(t*r);this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n const float avgMultiplier = float("+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},BatchNormProgram=function(e,t,r,n,a,o){this.outputShape=[],this.supportsBroadcasting=!0,this.variableNames=["x","mean","variance"],assertAndGetBroadcastShape(e,t),assertAndGetBroadcastShape(e,r);var i="0.0";null!=n&&(assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=a&&(assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput((x - mean) * inv + offset);\n }\n "},CHECK_NAN_SNIPPET="\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n",ADD="return a + b;",SUB="return a - b;",MUL="return a * b;",DIV="if (a == b) return 1.0;\n return a / b;",INT_DIV="\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",POW="\n return (round(mod(b, 2.0)) == 0 || round(mod(b, 2.0)) == 2) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",SQUARED_DIFFERENCE="return (a - b) * (a - b);",EQUAL="return float(a == b);",NOT_EQUAL="return float(a != b);",LESS="return float(a < b);",LESS_EQUAL="return float(a <= b);",GREATER="return float(a > b);",GREATER_EQUAL="return float(a >= b);",LOGICAL_AND="return float(a >= 1.0 && b >= 1.0);",LOGICAL_OR="return float(a >= 1.0 || b >= 1.0);",MAX=CHECK_NAN_SNIPPET+"\n return max(a, b);\n",MIN=CHECK_NAN_SNIPPET+"\n return min(a, b);\n",MOD="if (b == 0.0) return NAN;\n return mod(a, b);",ATAN2=CHECK_NAN_SNIPPET+"\n return atan(a, b);\n",ELU_DER="return (b >= 1.0) ? a : a * (b + 1.0);",BinaryOpProgram=function(){function e(e,t,r){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.outputShape=assertAndGetBroadcastShape(t,r),this.userCode="\n uniform float NAN;\n float binaryOperation(float a, float b) {\n "+e+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "}return e.prototype.getCustomSetupFunc=function(){var e=this;return function(t,r){null==e.startLoc&&(e.startLoc=t.getUniformLocationNoThrow(r,"NAN"),null==e.startLoc)||t.gl.uniform1f(e.startLoc,NaN)}},e}(),ClipProgram=function(e,t,r){this.variableNames=["A"],this.outputShape=e;var n=t.toFixed(20),a=r.toFixed(20);this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, "+n+", "+a+"));\n }\n "},ConcatProgram=function(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=computeOutShape(e,t,1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "},Conv2DDerFilterProgram=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+n+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv2DDerInputProgram=function(e){this.variableNames=["dy","W"],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;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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 int wRPerm = "+t+" - 1 - wR;\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 int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DDerFilterProgram=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+n+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DDerInputProgram=function(e){this.variableNames=["dy","W"],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=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+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 int wRPerm = "+t+" - 1 - wR;\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 int wCPerm = "+r+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv2DProgram=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,r=e.padInfo.left,n=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,i=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),c=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+n+", "+a+");\n const ivec2 pads = ivec2("+t+", "+r+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+"; wR++) {\n int xR = xRCorner + wR * "+o+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DProgram=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,r=e.inWidth,n=e.padInfo.top,a=e.padInfo.left,o=e.strideHeight,i=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,p=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+n+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+r+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "};function makeShader(e,t,r,n){var a=e.map(function(e){var t=sizeFromShape(e.shapeInfo.logicalShape);return e.shapeInfo.isUniform?"uniform float "+e.name+(t>1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});a=a.join("\n");var o=e.map(function(e){return getInputSamplingSnippet(e,t,n)}).join("\n"),i=t.texShape,s=getOutputSamplingSnippet(t.logicalShape,i);return[SHADER_PREFIX,FLOAT_TEXTURE_SAMPLE_SNIPPET,FLOAT_TEXTURE_SETOUTPUT_SNIPPET,a,s,o,r].join("\n")}function getSamplerFromInInfo(e){var t=e.shapeInfo.logicalShape;switch(t.length){case 0:return getSamplerScalar(e);case 1:return getSampler1D(e);case 2:return getSampler2D(e);case 3:return getSampler3D(e);case 4:return getSampler4D(e);case 5:return getSampler5D(e);case 6:return getSampler6D(e);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function getInputSamplingSnippet(e,t,r){var n=getSamplerFlat(e);return n+=getSamplerFromInInfo(e),(r||arraysEqual(e.shapeInfo.logicalShape,t.logicalShape))&&(n+=getSamplerAtOutputCoords(e,t,r)),n}function getOutputSamplingSnippet(e,t){switch(e.length){case 0:return getOutputScalarCoords();case 1:return getOutput1DCoords(e,t);case 2:return getOutput2DCoords(e,t);case 3:return getOutput3DCoords(e,t);case 4:return getOutput4DCoords(e,t);case 5:return getOutput5DCoords(e,t);case 6:return getOutput6DCoords(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}var SAMPLE_1D_SNIPPET="\nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_2D_SNIPPET="\nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_3D_SNIPPET="\nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_4D_SNIPPET="\nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_5D_SNIPPET="\nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_6D_SNIPPET="\nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",FLOAT_TEXTURE_SAMPLE_SNIPPET="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",FLOAT_TEXTURE_SETOUTPUT_SNIPPET="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",SHADER_PREFIX="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n bool isNaN(float val) {\n return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+SAMPLE_1D_SNIPPET+"\n "+SAMPLE_2D_SNIPPET+"\n "+SAMPLE_3D_SNIPPET+"\n "+SAMPLE_4D_SNIPPET+"\n "+SAMPLE_5D_SNIPPET+"\n "+SAMPLE_6D_SNIPPET+"\n";function getOutputScalarCoords(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function getOutput1DCoords(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}function getOutput3DCoords(e,t){var r=e[1]*e[2],n=e[2];return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+r+";\n index -= r * "+r+";\n int c = index / "+n+";\n int d = index - c * "+n+";\n return ivec3(r, c, d);\n }\n "}function getOutput4DCoords(e,t){var r=e[3],n=e[2]*r,a=e[1]*n;return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+a+";\n index -= r * "+a+";\n\n int c = index / "+n+";\n index -= c * "+n+";\n\n int d = index / "+r+";\n int d2 = index - d * "+r+";\n\n return ivec4(r, c, d, d2);\n }\n "}function getOutput5DCoords(e,t){var r=e[4],n=e[3]*r,a=e[2]*n,o=e[1]*a;return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+o+";\n index -= r * "+o+";\n\n int c = index / "+a+";\n index -= c * "+a+";\n\n int d = index / "+n+";\n index -= d * "+n+";\n\n int d2 = index / "+r+";\n int d3 = index - d2 * "+r+";\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}function getOutput6DCoords(e,t){var r=e[5],n=e[4]*r,a=e[3]*n,o=e[2]*a,i=e[1]*o;return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+i+";\n index -= r * "+i+";\n\n int c = index / "+o+";\n index -= c * "+o+";\n\n int d = index / "+a+";\n index -= d * "+a+";\n\n int d2 = index / "+n+";\n index -= d2 * "+n+";\n\n int d3 = index / "+r+";\n int d4 = index - d3 * "+r+";\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}function getOutput2DCoords(e,t){return arraysEqual(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}function getSamplerScalar(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+r+"() {return "+t+";}":"\n float "+r+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}function getSampler1D(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+r+"(int index) {\n return "+r+"Flat(index);\n }\n "}function getSampler2D(e){var t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(null!=a&&arraysEqual(t,a)){var o=a[0];return"\n float "+n+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var i=squeezeShape(t),s=i.newShape,u=i.keptDims,l=s;if(l.length=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+r+"("+(o<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}function getSamplerAtOutputCoords(e,t,r){var n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),o="get"+a+"AtOutCoords",i=getBroadcastDims(e.shapeInfo.logicalShape,t.logicalShape),s=e.shapeInfo.logicalShape.length,u=t.logicalShape.length,l=r&&(u>s||i.length>0),c=broadcastDimsAreOuter(i),p=e.shapeInfo.isUniform;if(l&&!c)return getBroadcastOutputCoordsSampler(e,t,a,o);var d=sizeFromShape(e.shapeInfo.logicalShape),h="";l&&c&&(h="\n int mainPart = index / "+d+";\n index -= mainPart * "+d+";\n ");var f=t.texShape;if(p)return 1===d?"float "+o+"() {return "+n+";}":"\n float "+o+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+f[0]+", "+f[1]+"));\n int index = resTexRC.x * "+f[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return arraysEqual(m,f)?"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ":"\n float "+o+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+f[0]+", "+f[1]+"));\n int index = resTexRC.x * "+f[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+n+", uv);\n }\n "}function getCoordsDataType(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function squeezeInputInfo(e,t){var r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function getSqueezedParams(e,t){return t.map(function(t){return e[t]}).join(", ")}var CumSumProgram=function(e,t,r){this.variableNames=["x"],this.outputShape=e;var n=e.length,a=e[e.length-1],o=r?"<":">";this.userCode="\n int getIndex(int i) {\n "+(r?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+getCoordsDataType(n)+" coords = getOutputCoords();\n int end = "+getFinalCoord(n,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+getFinalCoord(n,"coords")+" = idx;\n val += getX("+getCoords(n,"coords")+");\n }\n setOutput(val);\n }\n "};function getCoords(e,t){if(1===e)return""+t;if(2===e)return t+".x, "+t+".y";if(3===e)return t+".x, "+t+".y, "+t+".z";if(4===e)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}function getFinalCoord(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}var TextureUsage,PhysicalTextureType,EncodeFloatProgram=function(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "},FromPixelsProgram=function(e){this.variableNames=["A"];var t=e[0],r=e[1];this.outputShape=e,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+t+".0);\n\n vec4 values = texture2D(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},GatherProgram=function(e,t,r){this.variableNames=["A","indices"];var n=e.slice();n[r]=t,this.outputShape=n,this.rank=n.length;var a=getCoordsDataType(this.rank),o=getSourceCoords(e,r);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "};function getSourceCoords(e,t){var r=e.length;if(r>4)throw Error("Gather for rank "+r+" is not yet supported");if(1===r)return"int(getIndices(resRC))";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],o=0;o= "+n);for(var a=0,o=0;o= "+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) ? 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>>3){case 2:n.s&&n.s.length||(n.s=[]),n.s.push(e.bytes());break;case 3:if(n.i&&n.i.length||(n.i=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:a.name=e.string();break;case 2:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&o)}}return a},e}(),e.NodeDef=function(){function e(e){if(this.input=[],this.attr={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.name=e.string();break;case 2:a.op=e.string();break;case 3:a.input&&a.input.length||(a.input=[]),a.input.push(e.string());break;case 4:a.device=e.string();break;case 5:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&o)}}return a},e}(),e.VersionDef=function(){function e(e){if(this.badConsumers=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.producer=e.int32();break;case 2:n.minConsumer=e.int32();break;case 3:if(n.badConsumers&&n.badConsumers.length||(n.badConsumers=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.node&&n.node.length||(n.node=[]),n.node.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:n.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 2:n.library=$root.tensorflow.FunctionDefLibrary.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e}(),e.CollectionDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.nodeList=$root.tensorflow.CollectionDef.NodeList.decode(e,e.uint32());break;case 2:n.bytesList=$root.tensorflow.CollectionDef.BytesList.decode(e,e.uint32());break;case 3:n.int64List=$root.tensorflow.CollectionDef.Int64List.decode(e,e.uint32());break;case 4:n.floatList=$root.tensorflow.CollectionDef.FloatList.decode(e,e.uint32());break;case 5:n.anyList=$root.tensorflow.CollectionDef.AnyList.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.NodeList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push(e.string());break;default:e.skipType(7&a)}}return n},e}(),e.BytesList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push(e.bytes());break;default:e.skipType(7&a)}}return n},e}(),e.Int64List=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:if(n.value&&n.value.length||(n.value=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:if(n.value&&n.value.length||(n.value=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push($root.tensorflow.Any.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),e}(),e.SaverDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.filenameTensorName=e.string();break;case 2:n.saveTensorName=e.string();break;case 3:n.restoreOpName=e.string();break;case 4:n.maxToKeep=e.int32();break;case 5:n.sharded=e.bool();break;case 6:n.keepCheckpointEveryNHours=e.float();break;case 7:n.version=e.int32();break;default:e.skipType(7&a)}}return n},e.CheckpointFormatVersion=function(){const e={},t=Object.create(e);return t[e[0]="LEGACY"]=0,t[e[1]="V1"]=1,t[e[2]="V2"]=2,t}(),e}(),e.TensorInfo=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 4:n.cooSparse=$root.tensorflow.TensorInfo.CooSparse.decode(e,e.uint32());break;case 2:n.dtype=e.int32();break;case 3:n.tensorShape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.CooSparse=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.valuesTensorName=e.string();break;case 2:n.indicesTensorName=e.string();break;case 3:n.denseShapeTensorName=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),e.SignatureDef=function(){function e(e){if(this.inputs={},this.outputs={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:e.skip().pos++,a.inputs===$util.emptyObject&&(a.inputs={}),r=e.string(),e.pos++,a.inputs[r]=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:e.skip().pos++,a.outputs===$util.emptyObject&&(a.outputs={}),r=e.string(),e.pos++,a.outputs[r]=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 3:a.methodName=e.string();break;default:e.skipType(7&o)}}return a},e}(),e.AssetFileDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.tensorInfo=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:n.filename=e.string();break;default:e.skipType(7&a)}}return n},e}(),e.OpDef=function(){function e(e){if(this.inputArg=[],this.outputArg=[],this.attr=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.inputArg&&n.inputArg.length||(n.inputArg=[]),n.inputArg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 3:n.outputArg&&n.outputArg.length||(n.outputArg=[]),n.outputArg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 4:n.attr&&n.attr.length||(n.attr=[]),n.attr.push($root.tensorflow.OpDef.AttrDef.decode(e,e.uint32()));break;case 8:n.deprecation=$root.tensorflow.OpDef.OpDeprecation.decode(e,e.uint32());break;case 5:n.summary=e.string();break;case 6:n.description=e.string();break;case 18:n.isCommutative=e.bool();break;case 16:n.isAggregate=e.bool();break;case 17:n.isStateful=e.bool();break;case 19:n.allowsUninitializedInput=e.bool();break;default:e.skipType(7&a)}}return n},e.ArgDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.description=e.string();break;case 3:n.type=e.int32();break;case 4:n.typeAttr=e.string();break;case 5:n.numberAttr=e.string();break;case 6:n.typeListAttr=e.string();break;case 16:n.isRef=e.bool();break;default:e.skipType(7&a)}}return n},e}(),e.AttrDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.type=e.string();break;case 3:n.defaultValue=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 4:n.description=e.string();break;case 5:n.hasMinimum=e.bool();break;case 6:n.minimum=e.int64();break;case 7:n.allowedValues=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e}(),e.OpDeprecation=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.version=e.int32();break;case 2:n.explanation=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),e.OpList=function(){function e(e){if(this.op=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.op&&n.op.length||(n.op=[]),n.op.push($root.tensorflow.OpDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),e.MetaGraphDef=function(){function e(e){if(this.collectionDef={},this.signatureDef={},this.assetFileDef=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.metaInfoDef=$root.tensorflow.MetaGraphDef.MetaInfoDef.decode(e,e.uint32());break;case 2:a.graphDef=$root.tensorflow.GraphDef.decode(e,e.uint32());break;case 3:a.saverDef=$root.tensorflow.SaverDef.decode(e,e.uint32());break;case 4:e.skip().pos++,a.collectionDef===$util.emptyObject&&(a.collectionDef={}),r=e.string(),e.pos++,a.collectionDef[r]=$root.tensorflow.CollectionDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.signatureDef===$util.emptyObject&&(a.signatureDef={}),r=e.string(),e.pos++,a.signatureDef[r]=$root.tensorflow.SignatureDef.decode(e,e.uint32());break;case 6:a.assetFileDef&&a.assetFileDef.length||(a.assetFileDef=[]),a.assetFileDef.push($root.tensorflow.AssetFileDef.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return a},e.MetaInfoDef=function(){function e(e){if(this.tags=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.metaGraphVersion=e.string();break;case 2:n.strippedOpList=$root.tensorflow.OpList.decode(e,e.uint32());break;case 3:n.anyInfo=$root.tensorflow.Any.decode(e,e.uint32());break;case 4:n.tags&&n.tags.length||(n.tags=[]),n.tags.push(e.string());break;case 5:n.tensorflowVersion=e.string();break;case 6:n.tensorflowGitVersion=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),e.SavedModel=function(){function e(e){if(this.metaGraphs=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.savedModelSchemaVersion=e.int64();break;case 2:n.metaGraphs&&n.metaGraphs.length||(n.metaGraphs=[]),n.metaGraphs.push($root.tensorflow.MetaGraphDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),e.FunctionDefLibrary=function(){function e(e){if(this.function=[],this.gradient=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.function&&n.function.length||(n.function=[]),n.function.push($root.tensorflow.FunctionDef.decode(e,e.uint32()));break;case 2:n.gradient&&n.gradient.length||(n.gradient=[]),n.gradient.push($root.tensorflow.GradientDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),e.FunctionDef=function(){function e(e){if(this.attr={},this.nodeDef=[],this.ret={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.signature=$root.tensorflow.OpDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 3:a.nodeDef&&a.nodeDef.length||(a.nodeDef=[]),a.nodeDef.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:e.skip().pos++,a.ret===$util.emptyObject&&(a.ret={}),r=e.string(),e.pos++,a.ret[r]=e.string();break;default:e.skipType(7&o)}}return a},e}(),e.GradientDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.functionName=e.string();break;case 2:n.gradientFunc=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}();function getParamValue(e,t,r,n){var a=t.params[e];if(a&&void 0!==a.inputIndex){if("tensor"===a.type)return getTensor(t.inputNames[a.inputIndex],r,n);if("tensors"===a.type)return(0===a.inputIndex?0===a.inputParamLength?t.inputNames:t.inputNames.slice(a.inputIndex,-a.inputParamLength):t.inputNames.splice(a.inputIndex)).map(function(e){return getTensor(e,r,n)});var o=Array.prototype.slice.call(getTensor(t.inputNames.slice(a.inputIndex)[0],r,n).dataSync());return"number"===a.type?o[0]:o}return a&&a.value}function getTensor(e,t,r){var n=parseNodeName(e),a=n[0],o=n[1],i=r.currentContextIds.find(function(e){return!!t[getNodeNameWithContextId(a,e)]});return void 0!==i?t[getNodeNameWithContextId(a,i)][o]:void 0}function getNodeNameAndIndex(e,t){var r=parseNodeName(e),n=r[0],a=r[1];return[getNodeNameWithContextId(n,t&&t.currentContextId),a]}function getNodeNameWithContextId(e,t){return t?e+"-"+t:e}function parseNodeName(e){var t=e.lastIndexOf(":");return-1===t?[e,0]:[e.substring(0,t),Number(e.substring(t+1))]}function split$1(e,t){for(var r=[],n=0;n0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},e.prototype.getWeight=function(e){return this.weightMap[e]},e}(),__assign$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]0;){var r=e.pop();t[r.name]=!0,this.compiledOrder.push(r),r.children.forEach(function(r){!t[r.name]&&r.inputNames.every(function(e){var r=getNodeNameAndIndex(e)[0];return t[r]})&&e.push(r)})}},e.prototype.execute=function(e,t){var r=this;return this.checkInput(e),this.checkInputShapeAndType(e),tidy(function(){var n=new ExecutionContext(r._weightMap),a=r.compiledOrder.reduce(function(e,t){return e[t.name]=executeOp$13(t,e,n),e},__assign$1({},r.weightMap,e));return r.findOutputs(a,n,t)})},e.prototype.executeAsync=function(e,t){return __awaiter$3(this,void 0,void 0,function(){var r,n,a,o,i,s,u=this;return __generator$3(this,function(l){switch(l.label){case 0:return this.checkInput(e),this.checkInputShapeAndType(e),r=new ExecutionContext(this._weightMap),[4,this.executeWithControlFlow(e,r)];case 1:return n=l.sent(),a=this.findOutputs(n,r,t),o=Object.keys(a).map(function(e){return a[e].id}),i=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})}),s=[].concat.apply([],i),Object.keys(n).forEach(function(e){n[e].forEach(function(e){e&&-1===o.indexOf(e.id)&&-1===s.indexOf(e.id)&&-1===u.weightIds.indexOf(e.id)&&e.dispose()})}),[2,a]}})})},e.prototype.executeWithControlFlow=function(e,t){return __awaiter$3(this,void 0,void 0,function(){var r,n,a,o,i,s,u,l;return __generator$3(this,function(c){switch(c.label){case 0:r=this.graph.inputs.map(function(e){return{node:e,contexts:t.currentContext}}),n=__assign$1({},this.weightMap,e),a={},c.label=1;case 1:return r.length>0?(o=r.pop(),t.currentContext=o.contexts,i=executeOp$13(o.node,n,t),s=getNodeNameAndIndex(o.node.name,t)[0],u=n,l=s,[4,i]):[3,3];case 2:return u[l]=c.sent(),o.node.children.forEach(function(e){var o=getNodeNameAndIndex(e.name,t)[0];a[o]||("merge"===e.op?e.inputNames.some(function(e){return!!getTensor(e,n,t)})&&(a[o]=!0,r.push({contexts:t.currentContext,node:e})):e.inputNames.every(function(e){return!!getTensor(e,n,t)})&&(a[o]=!0,r.push({contexts:t.currentContext,node:e})))}),[3,1];case 3:return[2,n]}})})},e.prototype.findOutputs=function(e,t,r){return!r||r instanceof Array||(r=[r]),(r||this.graph.outputs.map(function(e){return e.name})).reduce(function(r,n){return r[n]=getTensor(n,e,t),r},{})},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})})},e.prototype.checkInputShapeAndType=function(e){this.placeholders.forEach(function(t){var r=e[t.name][0];if(t.params.shape&&t.params.shape.value){var n=t.params.shape.value,a=n.length===r.shape.length&&r.shape.every(function(e,t){return-1===n[t]||n[t]===e});util.assert(a,"The shape of dict['"+t.name+"'] provided in model.execute(dict) must be ["+n+"], but was ["+r.shape+"]")}t.params.dtype&&t.params.dtype.value&&util.assert(r.dtype===t.params.dtype.value,"The dtype of dict['"+t.name+"'] provided in model.execute(dict) must be "+t.params.dtype.value+", but was "+r.dtype)})},e.prototype.checkInput=function(e){var t=this,r=Object.keys(e),n=[],a=[];if(this.inputNodes.forEach(function(e){-1===r.indexOf(e)&&n.push(e)}),r.forEach(function(e){-1===t.inputNodes.indexOf(e)&&a.push(e)}),n.length>0)throw new Error("The dict provided in model.execute(dict) has the keys ["+r+"], but is missing the required keys: ["+n+"].");if(a.length>0)throw new Error("The dict provided in model.execute(dict) has unused keys: ["+a+"]. Please provide only the following keys: ["+this.inputNodes+"].")},e}(),__awaiter$4=function(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())})},__generator$4=function(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]1?t.map(function(e){return r[e]}):r[n[0]]},e.prototype.executeAsync=function(e,t){return __awaiter$4(this,void 0,void 0,function(){var r,n;return __generator$4(this,function(a){switch(a.label){case 0:if(!this.executor.isControlFlowModel)throw new Error("The model does not contain control flow ops, please use execute method for better performance.");return t=t||this.outputNodes,(e instanceof Tensor||Array.isArray(e))&&(e=this.constructTensorMap(e)),[4,this.executor.executeAsync(this.convertTensorMapToTensorsMap(e),t)];case 1:return r=a.sent(),n=Object.keys(r),[2,Array.isArray(t)&&t.length>1?t.map(function(e){return r[e]}):r[n[0]]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,r){return t[r]=[e[r]],t},{})},e.prototype.dispose=function(){this.executor.dispose()},e}();function loadFrozenModel(e,t,r){return __awaiter$4(this,void 0,void 0,function(){var n;return __generator$4(this,function(a){switch(a.label){case 0:return[4,(n=new FrozenModel(e,t,r)).load()];case 1:return a.sent(),[2,n]}})})}var version$2="0.5.0",version$3="0.12.0",version$4={"tfjs-core":version,"tfjs-layers":version$1,"tfjs-converter":version$2,tfjs:version$3};exports.version=version$4,exports.setBackend=setBackend,exports.getBackend=getBackend,exports.disposeVariables=disposeVariables,exports.memory=memory,exports.version_core=version,exports.nextFrame=nextFrame,exports.environment=environment,exports.io=io,exports.serialization=serialization,exports.test_util=test_util,exports.util=util,exports.webgl=webgl,exports.AdadeltaOptimizer=AdadeltaOptimizer,exports.AdagradOptimizer=AdagradOptimizer,exports.AdamOptimizer=AdamOptimizer,exports.AdamaxOptimizer=AdamaxOptimizer,exports.MomentumOptimizer=MomentumOptimizer,exports.Optimizer=Optimizer,exports.RMSPropOptimizer=RMSPropOptimizer,exports.SGDOptimizer=SGDOptimizer,exports.Tensor=Tensor,exports.TensorBuffer=TensorBuffer,exports.variable=variable,exports.Variable=Variable,exports.ENV=ENV,exports.Environment=Environment,exports.doc=doc,exports.batchNormalization=batchNormalization,exports.batchNormalization2d=batchNormalization2d,exports.batchNormalization3d=batchNormalization3d,exports.batchNormalization4d=batchNormalization4d,exports.concat=concat,exports.concat1d=concat1d,exports.concat2d=concat2d,exports.concat3d=concat3d,exports.concat4d=concat4d,exports.conv1d=conv1d,exports.conv2d=conv2d,exports.conv2dTranspose=conv2dTranspose,exports.depthwiseConv2d=depthwiseConv2d,exports.separableConv2d=separableConv2d,exports.matMul=matMul,exports.matrixTimesVector=matrixTimesVector,exports.outerProduct=outerProduct,exports.vectorTimesMatrix=vectorTimesMatrix,exports.dot=dot,exports.avgPool=avgPool,exports.maxPool=maxPool,exports.transpose=transpose,exports.reverse=reverse,exports.reverse1d=reverse1d,exports.reverse2d=reverse2d,exports.reverse3d=reverse3d,exports.reverse4d=reverse4d,exports.slice=slice,exports.slice1d=slice1d,exports.slice2d=slice2d,exports.slice3d=slice3d,exports.slice4d=slice4d,exports.stridedSlice=stridedSlice,exports.argMax=argMax,exports.argMin=argMin,exports.logSumExp=logSumExp,exports.max=max,exports.mean=mean,exports.min=min,exports.all=all,exports.any=any,exports.moments=moments,exports.sum=sum,exports.equal=equal,exports.equalStrict=equalStrict,exports.greater=greater,exports.greaterStrict=greaterStrict,exports.greaterEqual=greaterEqual,exports.greaterEqualStrict=greaterEqualStrict,exports.less=less,exports.lessStrict=lessStrict,exports.lessEqual=lessEqual,exports.lessEqualStrict=lessEqualStrict,exports.notEqual=notEqual,exports.notEqualStrict=notEqualStrict,exports.logicalNot=logicalNot,exports.logicalAnd=logicalAnd,exports.logicalOr=logicalOr,exports.logicalXor=logicalXor,exports.where=where,exports.abs=abs,exports.acos=acos,exports.acosh=acosh,exports.asin=asin,exports.asinh=asinh,exports.atan=atan,exports.atanh=atanh,exports.ceil=ceil,exports.clipByValue=clipByValue,exports.cos=cos,exports.cosh=cosh,exports.elu=elu,exports.exp=exp,exports.expm1=expm1,exports.floor=floor,exports.sign=sign,exports.leakyRelu=leakyRelu,exports.log=log,exports.log1p=log1p,exports.logSigmoid=logSigmoid,exports.neg=neg,exports.prelu=prelu,exports.relu=relu,exports.reciprocal=reciprocal,exports.round=round,exports.selu=selu,exports.sigmoid=sigmoid,exports.sin=sin,exports.sinh=sinh,exports.softplus=softplus,exports.sqrt=sqrt,exports.rsqrt=rsqrt,exports.square=square,exports.step=step,exports.tan=tan,exports.tanh=tanh$1,exports.erf=erf,exports.add=add,exports.addStrict=addStrict,exports.atan2=atan2,exports.div=div,exports.floorDiv=floorDiv,exports.divStrict=divStrict,exports.maximum=maximum,exports.maximumStrict=maximumStrict,exports.minimum=minimum,exports.minimumStrict=minimumStrict,exports.mod=mod,exports.modStrict=modStrict,exports.mul=mul,exports.mulStrict=mulStrict,exports.pow=pow,exports.powStrict=powStrict,exports.sub=sub,exports.subStrict=subStrict,exports.squaredDifference=squaredDifference,exports.squaredDifferenceStrict=squaredDifferenceStrict,exports.norm=norm,exports.cast=cast,exports.clone=clone,exports.fromPixels=fromPixels,exports.toPixels=toPixels,exports.ones=ones,exports.onesLike=onesLike,exports.zeros=zeros,exports.zerosLike=zerosLike,exports.eye=eye,exports.rand=rand,exports.randomNormal=randomNormal,exports.truncatedNormal=truncatedNormal,exports.randomUniform=randomUniform,exports.multinomial=multinomial,exports.reshape=reshape,exports.squeeze=squeeze,exports.tile=tile,exports.gather=gather,exports.oneHot=oneHot,exports.linspace=linspace,exports.range=range,exports.buffer=buffer,exports.fill=fill,exports.tensor=tensor,exports.scalar=scalar,exports.tensor1d=tensor1d,exports.tensor2d=tensor2d,exports.tensor3d=tensor3d,exports.tensor4d=tensor4d,exports.tensor5d=tensor5d,exports.tensor6d=tensor6d,exports.print=print,exports.expandDims=expandDims,exports.stack=stack,exports.unstack=unstack,exports.split=split,exports.cumsum=cumsum,exports.pad=pad,exports.pad1d=pad1d,exports.pad2d=pad2d,exports.pad3d=pad3d,exports.pad4d=pad4d,exports.unsortedSegmentSum=unsortedSegmentSum,exports.movingAverage=movingAverage,exports.basicLSTMCell=basicLSTMCell,exports.multiRNNCell=multiRNNCell,exports.softmax=softmax,exports.sigmoidCrossEntropyWithLogits=sigmoidCrossEntropyWithLogits,exports.localResponseNormalization=localResponseNormalization,exports.linalg=linalg,exports.losses=losses,exports.image=image,exports.operation=operation,exports.train=train,exports.tidy=tidy,exports.keep=keep,exports.dispose=dispose,exports.time=time,exports.grad=grad,exports.valueAndGrad=valueAndGrad,exports.grads=grads,exports.valueAndGrads=valueAndGrads,exports.variableGrads=variableGrads,exports.customGrad=customGrad,exports.model=model,exports.sequential=sequential,exports.loadModel=loadModel,exports.input=input,exports.layers=layers,exports.constraints=constraints,exports.initializers=initializers,exports.metrics=metrics,exports.regularizers=regularizers,exports.CallbackList=CallbackList,exports.CustomCallback=CustomCallback,exports.Callback=Callback,exports.SymbolicTensor=SymbolicTensor,exports.Model=Model,exports.RNN=RNN,exports.Sequential=Sequential,exports.version_layers=version$1,exports.FrozenModel=FrozenModel,exports.loadFrozenModel=loadFrozenModel,exports.version_converter=version$2,Object.defineProperty(exports,"__esModule",{value:!0})});