// @tensorflow/tfjs Copyright 2019 Google !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.tf=t.tf||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function c(t,e,n){return Math.max(t,Math.min(e,n))}function p(t){return t%2==0?t:t+1}function h(t){for(var e=0,n=0;n=n?i():setTimeout(a,s)}};a()})}function E(t,e){for(var n=1,r=-1,i=0;i=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o}function I(t,e){var n=e.length;return d((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ta)&&1===t[a]&&(n.push(t[a]),r.push(a)),i[o]<=a&&o++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}}function A(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function T(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function R(t,e,n){if("float32"===e)for(var r=0;r=0;--r)n[r]=n[r+1]*t[r+1];return n}function j(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=y(t)),n&&D(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}var X=Object.freeze({shuffle:l,clamp:c,nearestLargerEven:p,sum:h,randUniform:f,distSquared:function(t,e){for(var n=0,r=0;r1)for(var l=0;lZ){var c=Q*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice(u-Q*s,u));return"complex64"===r&&(p=rt(p),h=rt(h)),["["+p.map(function(t,e){return nt(t,o[e])}).join(", ")+", ..., "+h.map(function(t,e){return nt(t,o[u-Q+e])}).join(", ")+"]"]}return["["+("complex64"===r?rt(e):Array.from(e)).map(function(t,e){return nt(t,o[e])}).join(", ")+"]"]}var f=n.slice(1),d=i.slice(1),m=i[0]*s,g=[];if(u>Z){for(var y=0;y0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return i(this,void 0,void 0,function(){var e,n;return o(this,function(r){return this.profiling=!0,e=this.numBytes,n=this.numTensors,this.activeProfile.kernels=[],this.activeProfile.result=t(),this.profiling=!1,this.activeProfile.peakBytes=Math.max.apply(Math,this.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.activeProfile.newBytes=this.numBytes-e,this.activeProfile.newTensors=this.numTensors-n,[2,this.activeProfile]})})},t.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var i={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.activeTape.push(i)},t.prototype.keep=function(t){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(t.id),t},t.prototype.startScope=function(t,e){void 0===e&&(e=!1),e&&0===this.gradientScopeCount&&(this.activeTape=[]),e&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};t&&(n.name=t),this.scopeStack.push(n),this.activeScope=n},t.prototype.endScope=function(t,e){var n=this;void 0===e&&(e=!1),e&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),i=wt(t);i.forEach(function(t){return r.add(t.id)});for(var o=0;o0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");return this.tidy("gradients",function(){var o=t();d(o instanceof ut,function(){return"The result y returned by f() must be a tensor."});var a=function(t,e,n){for(var r={},i={},o=0;o=0;o--)for(a=(d=t[o]).inputs,c=0;c0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var s={};return s[o.id]=null==n?function(t){var e=G(v(t),"float32");return ut.make(t,{values:e})}(o.shape):n,function(t,e){for(var n=function(n){var r=e[n],i=[];if(r.outputs.forEach(function(e){var n=t[e.id];if(null!=n)i.push(n);else{var r=ut.make(e.shape,{values:H(e.size,e.dtype)},e.dtype);i.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var o=r.gradient(1===r.outputs.length?i[0]:i);for(var a in r.inputs){if(!(a in o))throw new Error("Cannot backprop through input "+a+". Available gradients found: "+Object.keys(o)+".");var s=o[a]();if("float32"!==s.dtype)throw new Error("Error in gradient for op "+r.name+". The gradient of input "+a+" must have 'float32' dtype, but has '"+s.dtype+"'");var u=r.inputs[a];if(!b(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+a+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==t[u.id])t[u.id]=s;else{var l=t[u.id];t[u.id]=l.add(s),l.dispose()}}},r=e.length-1;r>=0;r--)n(r)}(s,a),{value:o,grads:e.map(function(t){return s[t.id]})}},!0)},t.prototype.customGrad=function(t){var e=this;return d(U(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r,i=[],o=0;o {op();...}); to avoid memory leaks.");return null!=this.activeScope&&this.activeScope.track.push(t),t},t.nextTensorId=0,t.nextVariableId=0,t}();!function(t){t[t.NUMBER=0]="NUMBER",t[t.BOOLEAN=1]="BOOLEAN",t[t.STRING=2]="STRING"}(xt||(xt={}));var St,Ct,Et=[{name:"DEBUG",type:xt.BOOLEAN},{name:"IS_BROWSER",type:xt.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:xt.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:xt.BOOLEAN},{name:"WEBGL_PACK",type:xt.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:xt.BOOLEAN},{name:"WEBGL_PACK_CLIP",type:xt.BOOLEAN},{name:"WEBGL_PACK_DEPTHWISECONV",type:xt.BOOLEAN},{name:"WEBGL_PACK_BINARY_OPERATIONS",type:xt.BOOLEAN},{name:"WEBGL_PACK_ARRAY_OPERATIONS",type:xt.BOOLEAN},{name:"WEBGL_PACK_IMAGE_OPERATIONS",type:xt.BOOLEAN},{name:"WEBGL_PACK_REDUCE",type:xt.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:xt.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:xt.NUMBER},{name:"WEBGL_NUM_MB_BEFORE_PAGING",type:xt.NUMBER},{name:"WEBGL_MAX_TEXTURES_IN_SHADER",type:xt.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:xt.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:xt.BOOLEAN},{name:"WEBGL_VERSION",type:xt.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:xt.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:xt.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:xt.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:xt.NUMBER},{name:"BACKEND",type:xt.STRING},{name:"EPSILON",type:xt.NUMBER},{name:"PROD",type:xt.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:xt.BOOLEAN},{name:"DEPRECATION_WARNINGS_ENABLED",type:xt.BOOLEAN}];function It(t){try{if(null!=u(t))return!0}catch(t){return!1}return!1}var kt="tfjsflags";function At(){var t={};if("undefined"==typeof window||void 0===window.location||void 0===window.location.search)return t;var e=function(t){var e={};return t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var n=[],r=1;r0&&!function(){var t=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return It(2)?2:It(1)?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(t){if(0===t)return!1;var e=u(t);if(1===t){if(!Tt(e,"OES_texture_float"))return!1}else if(!Tt(e,"EXT_color_buffer_float"))return!1;return Rt(e,t)}(this.get("WEBGL_VERSION"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(t){if(0===t)return!1;var e=u(t);if(1===t){if(!Tt(e,"OES_texture_float"))return!1;if(!Tt(e,"WEBGL_color_buffer_float"))return!1}else if(!Tt(e,"EXT_color_buffer_float"))return!1;return Rt(e,t)}(this.get("WEBGL_VERSION"));if("WEBGL_FENCE_API_ENABLED"===t)return function(t){return 2===t&&null!=u(t).fenceSync}(this.get("WEBGL_VERSION"));if("WEBGL_SIZE_UPLOAD_UNIFORM"===t)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?4:0;if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:1e-4;if("PROD"===t)return!1;if("TENSORLIKE_CHECK_SHAPE_CONSISTENCY"===t)return!this.get("PROD");if("DEPRECATION_WARNINGS_ENABLED"===t)return!0;throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(t){this.features=Object.assign({},t)},t.prototype.reset=function(){this.features=At(),null!=this.globalEngine&&(this.globalEngine=null)},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(t){return t in this.registry?this.registry[t].backend:null},t.prototype.registerBackend=function(t,e,n){var r=this;if(void 0===n&&(n=1),t in this.registry)return console.warn(t+" backend was already registered. Reusing existing backend"),!1;try{var i=e();return i.setDataMover({moveData:function(t){return r.engine.moveData(t)}}),this.registry[t]={backend:i,priority:n},!0}catch(e){return console.warn("Registration of backend "+t+" failed"),console.warn(e.stack||e.message),!1}},t.prototype.removeBackend=function(t){if(!(t in this.registry))throw new Error(t+" backend not found in registry");this.registry[t].backend.dispose(),delete this.registry[t]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initEngine(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initEngine=function(){var t=this;if(null==this.globalEngine){this.backendName=this.get("BACKEND");var e=this.findBackend(this.backendName);this.globalEngine=new Nt(e,!1,function(){return t.get("DEBUG")})}},Object.defineProperty(t.prototype,"global",{get:function(){return Mt()},enumerable:!0,configurable:!0}),t}();function Mt(){if(null==Ot){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else{if("undefined"==typeof process)throw new Error("Could not find a global object");t=process}Ot=t}return Ot}function Lt(){Bt.set("PROD",!0)}function Ft(){Bt.set("DEBUG",!0)}function zt(){Bt.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Pt(t){Bt.get("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}!function(t){st=t}(Pt);var Bt=function(){var t=Mt();return null==t.ENV&&(t.ENV=new _t(At())),function(t){ot=t}(function(){return t.ENV.engine}),t.ENV}(),Ut=Object.freeze({EPSILON_FLOAT16:1e-4,EPSILON_FLOAT32:1e-7,Environment:_t,enableProdMode:Lt,enableDebugMode:Ft,disableDeprecationWarnings:zt,deprecationWarn:Pt,ENV:Bt});function Wt(t,e){if(d(U(t),function(){return"The f passed in variableGrads(f) must be a function"}),d(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof lt}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}),null==e)for(var n in e=[],Bt.engine.registeredVariables)e.push(Bt.engine.registeredVariables[n]);var r=e.length;d((e=e.filter(function(t){return t.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable."});var i=Bt.engine.gradients(t,e,null,!0),o=i.value,a=i.grads;d(a.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),d(0===o.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+o.rank+" tensor"});var s={};return e.forEach(function(t,e){null!=a[e]&&(s[t.name]=a[e])}),{value:o,grads:s}}function Vt(t){return Bt.engine.customGrad(t)}function jt(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var qt=_t.tidy,Gt=_t.keep,Ht=_t.dispose,Kt=_t.time,$t=_t.profile;function Xt(){for(var t=[],e=0;e=2*e+1||i%2==1?a.push(i):o.push(i);r.push.apply(r,o),r.push(0),r.push.apply(r,a)}return r}function Zt(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var o=1;ot.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],i=1,o=0;o1?e.shape[e.rank-1]:1,i=e.rank>1?e.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rank1?e.shape[e.rank-1]:1,i=n.length,o=1,a=r;a0?i>=c[e]:i<=c[e]);i+=r[e])n+=1;return n}),[l,f,p]}function me(t,e,n,r,i){var o=e[i];t&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var a=r[i];return o<0&&(o+=a),c(0,o,a-1)}function ge(t,e,n,r,i){var o=e[i];t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var a=r[i];return o<0&&(o+=a),n[i]>0?c(0,o,a):c(-1,o,a-1)}function ye(t,e,n){for(var r=n.length,i=0;i1){r=i;break}for(i=r+1;i0||n[i]!==t[i])return!1;return!0}function ve(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),d(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),o=0;o=0&&(i=r),we(r,i,e,n),!_(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+t.constructor.name+"'");var o=be(t);_(t)||Array.isArray(t)||(t=[t]);var a="string"!==i?j(t,i,Bt.get("DEBUG")):y(t);return ut.make(o,{values:a},i)}function Ne(t,e,n){if(!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return xe(t,e+"["+r+"]",n)})}function Se(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var i=function(){for(var t=[],e=0;e1)return Pe([0],r);var i=H(Math.abs(Math.ceil((e-t)/n)),r);ei}).sort(function(t,e){return e.score-t.score}),a=[],s=0;s=0;--h)if(Qe(t,c,a[h])>=r){p=!0;break}if(!p&&(a.push(c),a.length>=n))break}return De(a,"int32")}function Qe(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),c=Math.min(i[1],i[3]),p=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),f=(s-o)*(u-a),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(o,l),g=Math.max(a,c),y=Math.min(s,p),v=Math.min(u,h),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(f+d-b)}function tn(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var o=t.slice(r,i);return r[n]+=e,o})}function en(t,e,n,r,i){for(var o=e[e.length-1],a=[t.length/o,o],s=a[0],u=a[1],l=A(n,s*r),c=A("int32",s*r),p=0;p":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function rn(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function on(t,e){return 1===e?[t]:rn(t,e)}function an(t,e){for(var n=t.length,r=[],i=0;i1&&1===a&&r.unshift(o)}return r}function sn(t,e){for(var n=[],r=0;r1)&&n.unshift(o)}return n}function un(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;i1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var o,a,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?dn(t):fn(t);var i=t.shapeInfo.logicalShape,o=e.logicalShape;return i.length<=o.length&&(r+=n?function(t,e){var n,r=t.name,i=r.charAt(0).toUpperCase()+r.slice(1),o="get"+i+"AtOutCoords",a=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=an(t.shapeInfo.logicalShape,e.logicalShape),l=xn(s),c=s-a,p=["x","y","z","w","u","v"];n=0===a?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+p[t+c]+" = 0;"}).join("\n");var h="";h=s<2&&a>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+c]}).join(", ");var f="return outputValue;";if(1===a&&s>1)f="\n return vec4(outputValue.xy, outputValue.xy);\n ";else if(0===a&&s>0)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var d=a-2,m=a-1;u.indexOf(d)>-1&&u.indexOf(m)>-1?f="return vec4(outputValue.x);":u.indexOf(d)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(m)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return"\n vec4 "+o+"() {\n "+l+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+i+"("+h+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",o=e.texShape,a=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&b(a,o))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=xn(u),c=an(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+i+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+h[t+p]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+p]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),l=e.texShape,c=ln(),p=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(c),h=function(t){var e="";return e=Bt.get("PROD")?"\n bool isNaN(float val) {\n return false;\n }\n\n bool hasNaN(vec4 values) {\n return false;\n }\n ":"\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bvec4 isNaN(vec4 val) {\n return bvec4(\n isNaN(val.x),\n isNaN(val.y),\n isNaN(val.z),\n isNaN(val.w)\n );\n }\n\n bool hasNaN(vec4 values) {\n return any(bvec4(\n isNaN(values.x),\n isNaN(values.y),\n isNaN(values.z),\n isNaN(values.w)\n ));\n }\n ",t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n "+e+"\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n "+t.defineRound+"\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 "+mn+"\n "+gn+"\n "+yn+"\n "}(c);return e.isPacked?(o=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return resTexRC.x * "+n[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(b(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[2]/2),i=r*Math.ceil(t[1]/2);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec3(b, r, c);\n }\n "}(t,e);default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),i=r*Math.ceil(t[t.length-2]/2),o=i,a="",s="b, r, c",u=2;u2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],o=Math.ceil(i/e);this.outputShape=t.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,l=u.length,c=xn(l),p=on("coords",l);if(1===o){var h=xn(s=l+1);a="\n "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,a="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),m="."+f[s-1],g=f.map(function(t){return"int "+t}),y=on("sourceLocR",s-1).concat("inIdx.r"),v=on("sourceLocG",s-1).concat("inIdx.g"),b=on("sourceLocB",s-1).concat("inIdx.b"),w=on("sourceLocA",s-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",N=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+b.join()+"),\n getBestIndicesAChannel("+w.join()+")));",S="vec4(\n getAChannel("+y.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+b.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+w.join()+") : 0.)",C=r?"":"\n float getBestIndicesAChannel("+g.join()+") {\n return getChannel(getBestIndicesA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+g.join()+") {\n return getChannel(getA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }\n "+C+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+a+"\n ivec4 srcIdx = ivec4(sourceLocR"+m+", sourceLocG"+m+",\n sourceLocB"+m+", sourceLocA"+m+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+S+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+N+"\n vec4 candidate = "+S+";\n bvec4 nan = isNaN(candidate);\n bvec4 replace = bvec4(\n vec4("+x+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},En=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},In=function(t,e,n,r,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],un(t,e),un(t,n);var a="0.0";null!=r&&(un(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=i&&(un(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+a+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},kn=function(t,e,n,r,i,o){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],un(t,e),un(t,n);var a="vec4(0.0)";null!=r&&(un(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(un(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+a+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},An="return areal * breal - aimag * bimag;",Tn="return areal * bimag + aimag * breal;",Rn=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=un(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},Dn="return a + b;",On="return a - b;",_n="return a * b;",Mn=function(){function t(t,e,n){this.variableNames=["A","B"],this.outputShape=un(e,n),this.userCode="\n uniform float NAN;\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),Ln=function(){function t(t,e,n){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=un(e,n),this.userCode="\n uniform float NAN;\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),Fn=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, min, max));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),zn=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (hasNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(min), vec4(max)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Pn=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},Bn=function(t){this.outputShape=[],this.outputShape=ue(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n 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 "},Vn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\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 < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n 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 "},jn=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,o=t.padInfo.top,a=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+i+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+o+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},qn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Gn=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Hn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // 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 "},Kn=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,l=4*Math.floor(t.inChannels/4),c=t.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+i+");\n const ivec2 pads = ivec2("+e+", "+n+");\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 >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+a+";\n\n if (xC < 0 || xC >= "+t.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 "},$n=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+o+", "+a+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Xn=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+r+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // 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 >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "},Yn=function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+d+"C"+m+" = vec4(previous.zw, xTexelR"+d+"C"+m+".xy);\n } else {\n xR"+d+"C"+m+" = vec4(0, 0, xTexelR"+d+"C"+m+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = xTexelR"+d+"C"+m+";\n ",m+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(f+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n "),f+="\n xR"+d+"C"+(m+1)+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".xy);\n "):f+="\n xCOffset = xC + "+y+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+d+"C"+(m+1)+" = xTexelR"+d+"C"+(m+2)+";\n "}}else m= 0 && xR < "+e+") {\n ",i%2==1?(f+="\n xCOffset = xC + 1 - "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".zw);\n ",m+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+d+"C"+(m+1)+" = vec4(xTexelR"+d+"C"+(m+2)+".xy, final.xy);\n ")):(f+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".xy, xTexelR"+d+"C"+(m+2)+".xy);\n ",m+11?[""+(a-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],N=w[1],S=w[2];this.userCode="\n const float height_ratio = float("+y+");\n const float width_ratio = float("+x+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+o+") {\n return;\n }\n\n float height_scale = "+v+";\n float width_scale = "+N+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "},Zn=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],o=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+xn(r)+" coords = getOutputCoords();\n int end = "+Qn(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Qn(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function Qn(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var tr=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),er=function(t){this.variableNames=["A"];var e=ln();this.outputShape=t,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 "+e.output+" = encode_float(x);\n }\n "},nr="return real * expR - imag * expI;",rr="return real * expI + imag * expR;",ir=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},or=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),ar=function(t){this.variableNames=["A"];var e=ln(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},sr=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var i=xn(this.rank),o=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],o=0;o1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function pr(t,e){return[e,t]}function hr(t,e){return t*e}function fr(t,e,n){var r=function(t,e){if(t%e!=0)throw new Error("unpackedSize ("+t+") must be a multiple of "+e);return t/e}(t.length,n);if(e.length= "+r);for(var i=0,o=0;o= "+o);for(var a=r%2==1,s=n%2==1,u=Math.floor(r/2),l=Math.floor(n/2),c=Math.ceil(r/2),h=c*Math.ceil(n/2),f=p(n)*p(r),d=0;dn||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function zr(t){return Kr(t,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Pr(t,e,n,r,i,o,a){var s=t.getAttribLocation(e,n);return-1!==s&&(yr(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),yr(t,function(){return t.vertexAttribPointer(s,i,t.FLOAT,!1,o,a)}),yr(t,function(){return t.enableVertexAttribArray(s)}),!0)}function Br(t,e,n){$r(t,n),yr(t,function(){return t.activeTexture(t.TEXTURE0+n)}),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)})}function Ur(t,e,n){return Kr(t,function(){return t.getUniformLocation(e,n)},'uniform "'+n+'" not present in program.')}function Wr(t,e,n){return t.getUniformLocation(e,n)}function Vr(t,e,n,r,i){yr(t,function(){return Br(t,n,i)}),yr(t,function(){return t.uniform1i(r,i)})}function jr(t,e,n){yr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),yr(t,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)})}function qr(t,e){yr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,e)}),yr(t,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function Gr(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Hr(t,e))}function Hr(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function Kr(t,e,n){var r=yr(t,function(){return e()});if(null==r)throw new Error(n);return r}function $r(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Xr(t,e){return void 0===e&&(e=2),v(t.slice(0,t.length-e))}function Yr(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Jr(t,e){var n;void 0===e&&(e=!1);var r=Bt.get("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?p(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var i=k(t);t=i.newShape}var o=v(t);if(t.length<=1&&o<=r)return[1,o];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var a=Xr(t),s=2,u=2;return t.length&&(s=(n=Yr(t))[0],u=n[1]),N(o=a*(s/2)*(u/2)).map(function(t){return 2*t})}return N(o)}function Zr(t){return t%2==0}function Qr(t,e){if(b(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(Zr(n)&&Zr(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Zr(t[0])&&Zr(e[0])}var ti=Object.freeze({callAndCheck:yr,enableDebugWebGLErrorChecking:br,checkWebGLError:wr,canBeRepresented:Sr,getWebGLErrorMessage:Cr,getExtensionOrThrow:Er,createVertexShader:Ir,createFragmentShader:kr,createProgram:Tr,linkProgram:Rr,validateProgram:Dr,createStaticVertexBuffer:Or,createStaticIndexBuffer:_r,getNumChannels:Mr,createTexture:Lr,validateTextureSize:Fr,createFramebuffer:zr,bindVertexBufferToProgramAttribute:Pr,bindTextureUnit:Br,unbindTextureUnit:function(t,e){$r(t,e),yr(t,function(){return t.activeTexture(t.TEXTURE0+e)}),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:Ur,getProgramUniformLocation:Wr,bindTextureToProgramUniformSampler:Vr,bindCanvasToFramebuffer:function(t){yr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),yr(t,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),yr(t,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:jr,unbindColorTextureFromFramebuffer:qr,validateFramebuffer:Gr,getFramebufferErrorMessage:Hr,getBatchDim:Xr,getRowsCols:Yr,getTextureShapeFromLogicalShape:Jr,isReshapeFree:Qr});function ei(t){var e=ln();return Ir(t,e.version+"\n precision highp float;\n "+e.attribute+" vec3 clipSpacePos;\n "+e.attribute+" vec2 uv;\n "+e.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function ni(t){return Or(t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ri(t){return _r(t,new Uint16Array([0,1,2,2,1,3]))}function ii(t,e){var n,r,i,o,a,s,u,l,c=t;return 2===Bt.get("WEBGL_VERSION")?(n=c.R32F,r=c.R16F,i=c.RGBA16F,o=c.RGBA32F,a=c.RED,s=4,u=1,l=c.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,i=t.RGBA,o=c.RGBA,a=t.RGBA,s=4,u=4,l=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:l}}function oi(t,e,n,r,i,o){Fr(e,n);var a=Lr(t),s=t.TEXTURE_2D;return yr(t,function(){return t.bindTexture(s,a)}),yr(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),yr(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),yr(t,function(){return t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST)}),yr(t,function(){return t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST)}),yr(t,function(){return t.texImage2D(s,0,r,e,n,0,i,o,null)}),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)}),a}function ai(t,e,n,r){var i=pr(e,n);return oi(t,i[0],i[1],r.internalFormatFloat,r.textureFormatFloat,t.FLOAT)}function si(t,e,n,r){var i=pr(e,n);return oi(t,i[0],i[1],r.internalFormatHalfFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function ui(t,e,n,r){var i=pr(e,n);return oi(t,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function li(t,e,n,r){var i=dr(e,n);return oi(t,i[0],i[1],r.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ci(t,e,n,r){var i=dr(e,n);return oi(t,i[0],i[1],r.internalFormatPackedHalfFloat,t.RGBA,r.textureTypeHalfFloat)}function pi(t,e,n){return yr(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,n)}),Pr(t,e,"clipSpacePos",n,3,20,0)&&Pr(t,e,"uv",n,2,20,12)}function hi(t,e,n){yr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),yr(t,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n)}),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function fi(t,e,n,r,i,o){Fr(n,r),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),yr(t,function(){return t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,o,t.FLOAT,i)}),yr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function di(t,e,n,r,i,o,a){var s,u=pr(n,r),l=u[0],c=u[1],p=n*r;1===a.defaultNumChannels&&p===i.length?s=i:function(t,e,n){var r=hr(t.length,n);if(e.length= "+r);for(var i=0,o=0;o0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n,r,i,o){var a=this;return this.downloadMatrixDriver(t,function(){return xi(a.gl,e,n,r,i,o,a.textureConfig)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=kr(e,t),r=ei(e),i=Tr(e);return yr(e,function(){return e.attachShader(i,r)}),yr(e,function(){return e.attachShader(i,n)}),Rr(e,i),this.autoDebugValidate&&Dr(e,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=pi(e,this.program,this.vertexBuffer)),i},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&yr(this.gl,function(){return e.gl.deleteProgram(t)})},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.autoDebugValidate&&Dr(this.gl,this.program),yr(this.gl,function(){return e.gl.useProgram(t)})},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?Ur(this.gl,t,e):Wr(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),yr(this.gl,function(){return n.gl.getAttribLocation(t,e)})},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),Vr(this.gl,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=dr(e,n),i=r[0],o=r[1];this.setOutputMatrixTextureDriver(t,i,o)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&Dr(this.gl,this.program),Gr(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.autoDebugValidate&&this.debugValidate(),yr(t,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),yr(this.gl,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Er(this.gl,2===Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},t.prototype.endQuery=function(){if(2!==Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return i(this,void 0,void 0,function(){var e=this;return o(this,function(n){switch(n.label){case 0:return[4,C(function(){return e.disposed||e.isQueryAvailable(t,Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||C(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),jr(this.gl,t,this.framebuffer),this.autoDebugValidate&&Gr(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(jr(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Gr(this.gl)):qr(this.gl,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;jr(r,t,this.framebuffer),this.autoDebugValidate&&Gr(r),this.outputTexture=t,yr(r,function(){return r.viewport(0,0,e,n)}),yr(r,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),yr(this.gl,function(){return i.gl.scissor(t,e,n,r)})},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function Ci(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,i=e[n],o=i.shape;if(!b(r,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+o+" must match");if(!t.isUniform||!i.isUniform){var a=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!b(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}})}var Ei=function(t,e,n){this.variableNames=["A"],this.outputShape=t;var r=n.filterWidth,i=n.inChannels,o=n.strideWidth,a=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=s.left,h=s.top,f=i*r,d=ln();this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n int blockIndex = rc.y + col;\n int pos = rc.x + row;\n\n if(blockIndex >= "+t[1]+" || pos >= "+t[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+a+" - "+h+";\n int d0 = offsetY + "+c+" * (pos / "+f+");\n\n if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+o+". - "+p+".);\n int d1 = offsetX + "+l+" * (int(mod(float(pos), "+f+".) / "+i+".));\n\n if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+i+".)));\n }\n }\n\n "+d.output+" = result;\n }\n "},Ii=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var o,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+a+"; j <= "+a+"; 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 "},ki=function(t,e,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},Ai=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,o=t.effectiveFilterWidth,a=i-1-t.padInfo.top,s=o-1-t.padInfo.left,u=i*o-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Ti=function(t,e,n,r,i,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===o&&(o=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var a=n?t[1]:t[2],s=Math.ceil(a/2),u=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],h="",f="";o&&(h="vec4 activation(vec4 x) {\n "+o+"\n }",f="result = activation(result);");var d=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),this.userCode="\n "+h+"\n\n const float sharedDimension = "+s+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+s+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+l+");\n\n result += ("+c[0]+" * "+p[0]+") + ("+c[1]+" * "+p[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+d+"\n\n "+f+"\n\n setOutput(result);\n }\n "},Ri=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Di=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Oi=function(t){this.variableNames=["A"],this.isPackShader=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=on("rc",e),r=xn(e),i=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",i=t-2;i= "+e[i],i= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),a=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var o=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),a=2;a= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+i+") {\n setOutput(vec4(0));\n } else {\n "+o+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}};var _i=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,i=xn(r),o=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+i+" start = "+i+"("+o+");\n "+i+" end = "+i+"("+a+");\n\n void main() {\n "+i+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+i+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+o+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Mi=function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,i=xn(r),o=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=on("rc",r),u=on("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[i+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var m=4*Math.floor(r/4),g=r%4,y="\n if ("+h+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+c+", "+p+");\n const float initializationValue = "+f+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+f+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+y+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+y+"\n }\n }\n setOutput("+d+");\n }\n "}},Fi=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,i=t.inSize,o=Math.ceil(i/n);this.outputShape=[r,o];var a="0.0",s="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 1e-20",s="min"):"max"===e&&(a="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(a="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(a="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";i%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+a+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},zi=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n "+function(t){return"\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+cn(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n "}(e)+"\n "+function(t){return"\n int getFlatIndex(ivec3 coords) {\n return round("+function(t,e){if(t.length!==e.length)throw new Error("Vectors to be dotted must be of the same length -got "+t.length+" and "+e.length);for(var n=[],r=Math.floor(t.length/4),i=t.length%4,o=0;o1?i-1:i,n&&u>1?o-1:o],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(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 "},Bi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".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 "},Ui=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+o+".0, "+a+".0,\n "+a+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Wi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],o=r[2],a=t.shape,s=a[1],u=a[2],l=[n&&s>1?i-1:i,n&&u>1?o-1:o],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Vi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".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 "},ji=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),i=xn(n);this.userCode="\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},qi=function(t,e,n,r,i,o,a){void 0===a&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=xn(i.length),u=xn(o.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Gi=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,o=t.numSegments,a=o*Math.ceil(i/n);this.outputShape=[r,a];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";i%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var p="";i%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+n+"));\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 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},Hi=function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "},Ki=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=xn(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return $i.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return"sourceLoc."+$i[e]+" = start["+e+"] + coords."+$i[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+i+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),$i=["x","y","z","w","u","v"];var Xi=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=xn(this.rank),n=on("coords",this.rank),r=on("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",o="getChannel(getSource("+r.join()+"), "+i+")",a="\n result.x = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+o+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+o+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+" \n vec4 result = vec4(0.);\n "+a+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Yi=function(t,e,n,r){this.variableNames=["x"];var i=n.filter(function(t,e){return-1===r.indexOf(e)});this.outputShape=i;var o=n.length,a=xn(n.length),s=xn(i.length),u="";if(1===o)u="coords * strides + begin";else{var l=0;u=n.map(function(t,e){return-1===r.indexOf(e)?(l++,1===i.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(l-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "},Ji=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,i=Zi(e,n),o=Qi(t,i,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[o].shift();return this.usedTextures[o].push(a),a}return this.numUsedTextures++,this.log(),i===lr.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===lr.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===lr.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===lr.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===lr.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var i=Qi(e,Zi(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[i],a=o.indexOf(t);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Zi(t,e){if(t===ur.UPLOAD)return e?lr.PACKED_2X2_FLOAT32:lr.UNPACKED_FLOAT32;if(t===ur.RENDER||null==t)return e?Bt.get("WEBGL_RENDER_FLOAT32_ENABLED")?lr.PACKED_2X2_FLOAT32:lr.PACKED_2X2_FLOAT16:Bt.get("WEBGL_RENDER_FLOAT32_ENABLED")?lr.UNPACKED_FLOAT32:lr.UNPACKED_FLOAT16;if(t===ur.DOWNLOAD||t===ur.PIXELS)return lr.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Qi(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var to=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=xn(this.rank),o=rn("rc",this.rank),a=new Array(this.rank);for(r=0;r= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var co="return exp(x);",po=ao+"\n return sin(x);\n",ho=ao+"\n return cos(x);\n",fo=ao+"\n return atan(x);\n",mo=ao+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",go=ao+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",yo="return x;",vo="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n\n result.r = isNaN(x.r) ? x.r : result.r;\n result.g = isNaN(x.g) ? x.g : result.g;\n result.b = isNaN(x.b) ? x.b : result.b;\n result.a = isNaN(x.a) ? x.a : result.a;\n\n return result;\n",bo=function(){function t(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float NAN;\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),wo=function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=on("rc",e),r=xn(e),i=function(t,e){if(1===t)return"rc";for(var n="",r=0;r=1,function(){return"Pass at least one tensor to concat"});var n=Ne(t,"tensors","concat");e=I(e,n[0].shape)[0];var r=ue(n.map(function(t){return t.shape}),e);if(0===v(r))return Te([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});!function(t,e){var n=t[0].length;t.forEach(function(t,e){d(t.length===n,function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"})}),d(e>=0&&e>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),To=ko(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Ro=ko(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Do=ko(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),Oo=ko(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,o=-32;o>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),_o=ko(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Mo=ko(function(t){!function(e,n){var r,i=this,o=256,a=6,s="random",u=n.pow(o,a),l=n.pow(2,52),c=2*l,p=o-1;function h(t,h,g){var y=[],v=d(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,a=n&&n.plugins;return[+new Date,i,a,i.screen,m(e)]}}():t,3),y),b=new function(t){var e,n=t.length,r=this,i=0,a=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,d(m(b.S),e),(h.pass||g||function(t,e,r,i){return i&&(i.S&&f(i,b),t.state=function(){return f(b,{})}),r?(n[s]=t,e):t})(w,v,"global"in h?h.global:this==n,h.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",i=0;i=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}();function zo(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",$(t),new it(t,e,n)}function Po(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Bo=Se({batchToSpaceND_:function(t,e,n){var r=xe(t,"x","batchToSpaceND"),i=e.reduce(function(t,e){return t*e});return d(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),d(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),d(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),Bt.engine.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Uo=Se({cast_:function(t,e){var n=xe(t,"x","cast");return Bt.engine.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Wo=Se({clone_:function(t){var e=xe(t,"x","clone",null);return Bt.engine.runKernel(function(t){return ut.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),Vo=Se({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=xe(t,"x","cumsum"),o=oe([e|=0],i.rank),a=i;null!=o&&(a=i.transpose(o));var s=se(1,i.rank)[0],u=Bt.engine.runKernel(function(t){return t.cumsum(a,s,n,r)},{permutedX:a},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=o&&(u=u.transpose(o)),u}}),jo=Se({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=xe(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return d(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),d(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape}),d(a%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape}),Bt.engine.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),qo=Se({expandDims_:function(t,e){void 0===e&&(e=0);var n=xe(t,"x","expandDims");d(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(d(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),na(n,r)}}),Go=Se({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=zo([t,e],r),o=t<=e?t:e,a=0;a2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?i.as2D(1,-1):i,u=Bt.engine.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===a?u.as1D():u}}),Ko=Se({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var i=xe(t,"indices","oneHot","int32"),o=i.shape.concat([e]);return i=i.flatten(),Bt.engine.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return Pe(i.shape,"float32")}}}).reshape(o)}}),$o=Se({pad_:function(t,e,n){void 0===n&&(n=0);var r=xe(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return Bt.engine.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),Xo=Se({pad1d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),$o(t,[e],n)}}),Yo=Se({pad2d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$o(t,e,n)}}),Jo=Se({pad3d_:function(t,e,n){return void 0===n&&(n=0),d(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$o(t,e,n)}}),Zo=Se({pad4d_:function(t,e,n){return void 0===n&&(n=0),d(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$o(t,e,n)}}),Qo=Se({rand_:function(t,e,n){var r=v(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var o=0;o=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),d(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),d(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Bt.engine.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),ia=Se({squeeze_:function(t,e){var n=xe(t,"x","squeeze");return na(n,k(n.shape,e).newShape)}}),oa=Se({stack_:function(t,e){void 0===e&&(e=0);var n=Ne(t,"tensors","stack");if(d(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,i=n[0].shape,o=n[0].dtype;d(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){m(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){d(o===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=n.map(function(t){return t.expandDims(e)});return xo(a,e)}}),aa=Se({tile_:function(t,e){var n=xe(t,"x","tile");return d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),Bt.engine.runKernel(function(t){return t.tile(n,e)},{$x:n},function(t){return{$x:function(){var r=je(n);if(1===n.rank)for(var i=0;i=-n.shape.length&&e0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},t.prototype.endTimer=function(t){return Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=performance.now(),t)},t.prototype.getQueryTime=function(t){return i(this,void 0,void 0,function(){var e;return o(this,function(n){return Bt.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){var e=this.texData.get(t),n=e.texture,r=e.dtype,i=e.texShape,o=e.usage,a=e.complexTensors,s=e.isPacked,u=e.slice;if(null!=n){var l=u&&u.origDataId||t,c=this.dataRefCount.get(l);c>1?this.dataRefCount.set(l,c-1):(this.dataRefCount.delete(l),this.releaseTexture(t,n,i,o,r,s),this.texData.delete(t))}null!=a&&(a.real.dispose(),a.imag.dispose())}},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getCPUBackend=function(){return Bt.get("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Bt.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.sizeBt.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),i=this.concat(t.slice(n),e);return this.concat([r,i],e)}if(Bt.get("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var o=new Un(t.map(function(t){return t.shape}),e);return this.compileAndRun(o,t)}var a=ue(t.map(function(t){return t.shape}),e),s=t.map(function(t){return t.as2D(-1,v(t.shape.slice(e)))}),u=new Bn(s.map(function(t){return t.shape}));return this.compileAndRun(u,s).reshape(a)},t.prototype.neg=function(t){var e=new oo(t.shape,"return -x;");return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var i=n?t.shape[2]:t.shape[1],o=r?e.shape[1]:e.shape[2],a=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===i||1===o)&&a>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===o?t:t.as3D(s,a,1),l=1===o?2:1,c=1===o?e.as3D(s,1,a):e;return this.multiply(u,c).sum(l,!0)}var p=yt(t.dtype,e.dtype),h=new Ti(t.shape,[s,i,o],n,r),f=this.makePackedTensor(h.outputShape,p);return this.compileAndRun(h,[t,e],f)},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){var a=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],l=yt(t.dtype,e.dtype),c=new Ti(t.shape,[u,a,s],n,r,!!i,o?function(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?yo:so;if("relu"===t)return e?vo:uo;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}(o,!0):null),p=this.makePackedTensor(c.outputShape,l),h=[t,e];return i&&h.push(i),this.compileAndRun(c,h,p)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),i=new Rn(An,t.shape,e.shape),o=new Rn(Tn,t.shape,e.shape),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],s=this.compileAndRun(i,a),u=this.compileAndRun(o,a),l=this.complex(s,u);return s.dispose(),u.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,_n,t.dtype);var c=new Mn(_n,t.shape,e.shape),p=this.makeOutputArray(c.outputShape,t.dtype);return this.compileAndRun(c,[t,e],p)},t.prototype.batchNormalization=function(t,e,n,r,i,o){var a=[t,e,n],s=null;null!=o&&(s=o.shape,a.push(o));var u=null;if(null!=i&&(u=i.shape,a.push(i)),Bt.get("WEBGL_PACK_BATCHNORMALIZATION")){var l=new kn(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,a)}var c=new In(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,a)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){var o=new Ii(t.shape,e,n,r,i);return this.compileAndRun(o,[t])},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){var s=new ki(e.shape,r,i,o,a);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){var n=new to(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.pad=function(t,e,n){var r=Bt.get("WEBGL_PACK_ARRAY_OPERATIONS")?new Mi(t.shape,e,n):new _i(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=Bt.get("WEBGL_PACK_ARRAY_OPERATIONS")?new no(t.shape,e):new eo(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new sr(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){d(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=Yt(t.shape,e,r),o=Jt(i.length,e.length),a=Zt(t.shape,e,r),s=Qt(n,e.length),u=te(a,n,e.length);return t.reshape(i).transpose(o).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){d(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var o=1+e.length;oe||n===t){r=!0;break}n=W(t,n+1)}return n}(a,i),u=new Gi({windowSize:s,inSize:a,batchSize:o,numSegments:i},e),l=u.outputShape,c=l[0],p=l[1],h=this.makeOutputArray([c,p],r);return this.compileAndRun(u,[t,n],h),h.shape[1]===i?h:(n=We(0,i).tile([a/s]),this.segOpCompute(h,e,n,r,i))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(ie("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!Bt.get("WEBGL_PACK_REDUCE")||t.rank<=2){var i=ne(t.shape,r),o=i[0],a=v(i[1]),s=t.as2D(-1,a);return this.argReduce(s,n).reshape(o)}return this.argReducePacked(t,n)},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var i=new Zn(t.shape,n,r);return this.compileAndRun(i,[t])},t.prototype.equal=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Mn("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.notEqual=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Mn("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Mn("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.lessEqual=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Mn("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Mn("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Mn("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalNot=function(t){var e=new oo(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Mn("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalOr=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new Mn("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.select=function(t,e,n){var r=new Hi(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,yt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},t.prototype.where=function(t){Xt("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return ca(t.shape,e)},t.prototype.topk=function(t,e,n){return en(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){ie("min",e,t.rank);var n=ne(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Mn("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.mod=function(t,e){var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Mn("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);ie("max",e,t.rank);var n=ne(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"max",o.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Mn("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.all=function(t,e){ie("all",e,t.rank);var n=ne(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(r)},t.prototype.any=function(t,e){ie("any",e,t.rank);var n=ne(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("return (a - b) * (a - b);",t.shape,e.shape):new Mn("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){var n=new Mn("if (a == b) return 1.0;\n return a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r)},t.prototype.floorDiv=function(t,e){if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n vec4 resultSign = sign(a) * sign(b);\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n ivec4 result = ia / ib;\n ivec4 amodb = ia - ib * result;\n\n // Vectorize INT_DIV\n // if (resultSign < 0.0 && amodb != 0) result -= 1;\n // return float(result);\n return vec4(result -\n ivec4(lessThan(resultSign, vec4(0.0))) * ivec4(notEqual(amodb, ivec4(0))));\n","int32");var n=new Mn("\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",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r)},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Dn);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=yt(t.dtype,e.dtype);if(Bt.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Dn,n);var r=new Mn(Dn,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.packedBinaryOp=function(t,e,n,r){var i=new Ln(n,t.shape,e.shape),o=this.makePackedTensor(i.outputShape,r);return this.compileAndRun(i,[t,e],o)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),o=this.texData.get(e.dataId),a=[[i.complexTensors.real,o.complexTensors.real],[i.complexTensors.imag,o.complexTensors.imag]].map(function(i){var o=i[0],a=i[1],s=r.makeComplexComponentTensorHandle(t,o),u=r.makeComplexComponentTensorHandle(e,a),l=new Mn(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,yt(o.dtype,a.dtype));return r.compileAndRun(l,[s,u],c)}),s=a[0],u=a[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){for(var e=t[0],n=1;n 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Mn("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),i=yt(t.dtype,e.dtype),o=n?this.makePackedTensor(r.outputShape,i):this.makeOutputArray(r.outputShape,i),a=r.getCustomSetupFunc();return this.compileAndRun(r,[t,e],o,a)},t.prototype.ceil=function(t){var e=new oo(t.shape,"return ceil(x);");return this.compileAndRun(e,[t])},t.prototype.floor=function(t){var e=new oo(t.shape,"return floor(x);");return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new oo(t.shape,"\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},t.prototype.round=function(t){var e=new oo(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},t.prototype.exp=function(t){var e;return e=Bt.get("WEBGL_PACK")?new bo(t.shape,co):new oo(t.shape,co),this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new oo(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e,n=(e=Bt.get("WEBGL_PACK")?new bo(t.shape,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n"):new oo(t.shape,"if (x < 0.0) return NAN;\n return log(x);")).getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.log1p=function(t){var e=new oo(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new oo(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new oo(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new oo(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new oo(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=Bt.get("WEBGL_PACK")?new bo(t.shape,vo):new oo(t.shape,uo),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Mn("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){var e=new oo(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Mn("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.selu=function(t){var e=new oo(t.shape,lo);return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new oo(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},t.prototype.clip=function(t,e,n){var r,i=(r=Bt.get("WEBGL_PACK_CLIP")?new zn(t.shape):new Fn(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,i)},t.prototype.abs=function(t){var e=new oo(t.shape,"return abs(x);");return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Pn(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(t){var e=new oo(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new oo(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},t.prototype.sin=function(t){var e=new oo(t.shape,po);return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new oo(t.shape,ho);return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new oo(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new oo(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new oo(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new oo(t.shape,fo);return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=Bt.get("WEBGL_PACK_BINARY_OPERATIONS")?new Ln("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Mn("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.sinh=function(t){var e=new oo(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.cosh=function(t){var e=new oo(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.tanh=function(t){var e=new oo(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},t.prototype.asinh=function(t){var e=new oo(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new oo(t.shape,mo),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.atanh=function(t){var e=new oo(t.shape,go),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.erf=function(t){var e=new oo(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new oo(t.shape,function(t){return void 0===t&&(t=0),ao+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,i=this.texData.get(t.dataId);if(!Bt.get("WEBGL_LAZILY_UNPACK")||!Bt.get("WEBGL_PACK_BINARY_OPERATIONS")||r[2]%2==0||!i.isPacked){var o=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),a=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(o,a,!1,!1),n.outShape)}var s=ut.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),u=i.shape;i.shape=i.shape.slice(),i.shape[i.shape.length-2]++,d(Qr(i.shape,s.shape),function(){return"packed reshape "+i.shape+" to "+s.shape+" isn't free"});var l=this.reshape(e,[1,n.inChannels,n.outChannels]),c=this.batchMatMul(s,l,!1,!1),p=this.texData.get(c.dataId);return d(p.isPacked,function(){return"batchMatMul result is expected to be packed"}),i.shape=u,p.shape=n.outShape,ut.make(n.outShape,{dataId:c.dataId},c.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,i=n.filterHeight,o=n.inChannels,a=n.outWidth,s=n.outHeight,u=r*i*o,l=s*a,c=[u,l],p=t.squeeze([0]),h=e.reshape([1,u,-1]),f=new Ei(c,p.shape,n),d=this.compileAndRun(f,[p]).reshape([1,c[0],c[1]]),m=new Ti(d.shape,[1,l,n.outChannels],!0,!1);return this.compileAndRun(m,[d,h]).reshape([1,s,a,n.outChannels])},t.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(Bt.get("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Kn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new Vn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new Wn(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r;return Bt.get("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Yn(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new Xn(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Hn(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Gn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new $n(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new qn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new jn(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new Li(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},t.prototype.avgPool=function(t,e){var n=new Li(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var i=new Li(r,"max",!0),o=this.compileAndRun(i,[e]),a=new Ai(r),s=this.makeOutputArray(a.outputShape,e.dtype),u=this.compileAndRun(a,[t,o],s);return o.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new En(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},t.prototype.cast=function(t,e){return He(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,o=0;o1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],o="NHWC"===n?t.shape[2]:t.shape[3],a="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=o*e,l=a/(e*e),c=new tr("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},t.prototype.split=function(t,e,n){return tn(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=fe(0,t,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/a,a],c=t.reshape([o,i]),p=e.reshape([o,a]);if(0===u)return Ke(Te([]),n);var h=Re(0),f=new qi(o,i,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var i=fe(0,t,n),o=i.sliceRank,a=i.numUpdates,s=i.strides,u=i.outputSize,l=new qi(a,o,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ir(nr,t.shape,e),i=new ir(rr,t.shape,e),o=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],a=this.compileAndRun(r,o),s=this.compileAndRun(i,o),u=this.complex(a,s).as2D(t.shape[0],t.shape[1]);return a.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=le(t,e),o=i[0],a=i[1],s=i[2],u=i[3],l=e.reshape([a,r]),c=t.reshape([t.size/s,s]),p=new cr(r,u,[a,s]);return this.compileAndRun(p,[c,l]).reshape(o)},t.prototype.fill=function(t,e,n){if("string"===(n=n||B(e))){var r=T(n,v(t));return r.fill(e),ut.make(t,{values:r},n)}var i=new or(t,e),o=i.getCustomSetupFunc(e),a=this.makeOutputArray(t,n);return this.compileAndRun(i,[],a,o)},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},t.prototype.makeOutputArray=function(t,e){return ut.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=ut.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new wo(t.shape);return this.compileAndRun(e,[t],ut.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new Oi(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype))},t.prototype.packedReshape=function(t,e){var n=t.reshape([Xr(t.shape)].concat(Yr(t.shape))),r=[Xr(e)].concat(Yr(e)),i=new zi(r,n.shape);return this.compileAndRun(i,[n]).reshape(e)},t.prototype.compileAndRun=function(t,e,n,r,i){var o=this;if(void 0===i&&(i=!0),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=A(n.dtype,0),n;var a=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&v(e.shape)<=Bt.get("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:o.readSync(e.dataId)};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?o.unpackTensor(e):o.packTensor(e),n=o.texData.get(e.dataId);else if(n.isPacked&&!Qr(n.shape,e.shape)){var r=e,i=e.shape;e.shape=n.shape,e=o.packedReshape(e,i),n=o.texData.get(e.dataId),r.shape=i}return o.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(t,e,n){var r="";e.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(t,a,u),c=this.getAndSaveBinary(l,function(){return function(t,e,n,r){for(var i=e.userCode,o=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),a=o.map(function(t){return t.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=hn(o,s,i,e.usesPackedTextures),l=t.createProgram(u),c={},p=0;ph)for(var f=this.numBytesInGPU-h;f>0&&this.lruDataGPU.length>0;){var d=this.lruDataGPU.shift(),m=this.texData.get(d),g=m.texShape,y=m.dtype;f-=this.computeBytes(g,y),this.read(d)}return p&&(s=this.endTimer(s),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(s)})),Bt.get("WEBGL_LAZILY_UNPACK")||!this.texData.get(n.dataId).isPacked||t.isPackShader?n:this.unpackTensor(n)},t.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){if(!this.disposed){for(var t in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},t.prototype.floatPrecision=function(){var t=this;return qt(function(){var e=Bt.get("DEBUG");Bt.set("DEBUG",!1);var n=t.abs(Re(1e-8)).dataSync()[0];return Bt.set("DEBUG",e),n>0?32:16})},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,i=n.dtype,o=n.values,a=n.texture,s=n.usage,u=n.isPacked;if(null==a){var l,c=null!=this.activeTimers;c&&(l=performance.now());var p=Jr(r,u);n.texShape=p;var h=this.acquireTexture(t,p,s,i,u);if(n.texture=h,null!=o){if(u){var f=Xr(r),d=1,m=1;r.length&&(d=(e=Yr(r))[0],m=e[1]),this.gpgpu.uploadMatrixToPackedTexture(h,f,d,m,p[0],p[1],ha(o))}else this.gpgpu.uploadMatrixToTexture(h,p[0],p[1],ha(o));n.values=null,c&&(this.uploadWaitMs+=performance.now()-l)}}else Bt.get("WEBGL_NUM_MB_BEFORE_PAGING")=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(t),1),this.lruDataGPU.push(t))},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.texture,i=n.texShape,o=n.dtype,a=n.usage,s=n.isPacked;return null!=r&&(this.releaseTexture(t,r,i,a,o,s),n.texture=null,n.texShape=null,n.isPacked=!1),n.usage=ur.UPLOAD,null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r=0&&this.lruDataGPU.splice(a,1)}this.numBytesInGPU-=this.computeBytes(n,i),this.textureManager.releaseTexture(e,n,r,o)},t.prototype.acquireTexture=function(t,e,n,r,i){return Bt.get("WEBGL_NUM_MB_BEFORE_PAGING")=2&&a.rank>=2&&o.rank===a.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+a.rank+"."}),d(b(p,h),function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+o.shape+" and "+a.shape+" must match."}),d(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var g=o.shape.slice(0,-2).concat([l,c]),y=n?o.as3D(f,s,l):o.as3D(f,l,s),w=r?a.as3D(m,c,u):a.as3D(m,u,c);return Bt.engine.runKernel(function(t){return t.batchMatMul(y,w,n,r)},{$a:y,$b:w},function(t){return n||r?!n&&r?{$a:function(){return t.matMul(w,!1,!1)},$b:function(){return t.matMul(y,!0,!1)}}:n&&!r?{$a:function(){return w.matMul(t,!1,!0)},$b:function(){return y.matMul(t,!1,!1)}}:{$a:function(){return w.matMul(t,!0,!0)},$b:function(){return t.matMul(y,!0,!0)}}:{$a:function(){return t.matMul(w,!1,!0)},$b:function(){return y.matMul(t,!0,!1)}}}).reshape(g)}}),Es=Se({dot_:function(t,e){var n=xe(t,"t1","dot"),r=xe(e,"t2","dot");d(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var i=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];return d(i===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+o+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Is=Se({outerProduct_:function(t,e){var n=xe(t,"v1","outerProduct"),r=xe(e,"v2","outerProduct");return d(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}});var ks=Se({reverse_:function(t,e){var n=xe(t,"x","reverse");if(0===n.rank)return n.clone();var r=I(e,n.shape);return Bt.engine.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),As=Se({reverse1d_:function(t){var e=xe(t,"x","reverse");return d(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),ks(e,0)}}),Ts=Se({reverse2d_:function(t,e){var n=xe(t,"x","reverse");return d(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),ks(n,e)}}),Rs=Se({reverse3d_:function(t,e){var n=xe(t,"x","reverse");return d(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),ks(n,e)}}),Ds=Se({reverse4d_:function(t,e){var n=xe(t,"x","reverse");return d(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),ks(n,e)}});function Os(t,e,n,r,i,o){var a=xe(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),d(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),d(fs(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=o&&d(w(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var l=os(s.shape,e,n,r,i,o),c=Bt.engine.runKernel(function(t,e){return e(t.maxPool(s,l))},{x:s},function(t,o){var a=o[0];return{x:function(){return function(t,e,n,r,i,o,a,s){var u=xe(t,"dy","maxPoolBackprop"),l=xe(e,"input","maxPoolBackprop"),c=xe(n,"output","maxPoolBackprop");d(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==o&&(o=[1,1]),d(fs(i,o),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"}),d(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}),null!=s&&d(w(a),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."});var p=os(l.shape,r,i,o,a,s);return Bt.engine.runKernel(function(t){return t.maxPoolBackprop(u,l,c,p)},{$dy:u,$input:l})}(t,s,a,e,n,r,i)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function _s(t,e,n,r,i,o){var a=xe(t,"x","avgPool","float32");null==r&&(r=[1,1]),d(fs(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=o&&d(w(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var l=os(s.shape,e,n,r,i,o),c=Bt.engine.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,o){var a=xe(t,"dy","avgPoolBackprop"),s=xe(e,"input","avgPoolBackprop");d(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"}),null==i&&(i=[1,1]),d(fs(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,l=a,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=os(u.shape,n,r,i,o),h=Bt.engine.runKernel(function(t){return t.avgPoolBackprop(l,u,p)},{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,i)}}});return c=c.cast(a.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Ms=Se({maxPool_:function(t,e,n,r,i){return Os(t,e,n,1,r,i)}}),Ls=Se({avgPool_:function(t,e,n,r,i){return _s(t,e,n,1,r,i)}}),Fs=Se({pool_:function(t,e,n,r,i,o){null==i&&(i=[1,1]),null==o&&(o=1),0===r&&(r="valid");var a=xe(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(fs(o,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"});var l,c=os(s.shape,e,o,i,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],f=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),o=t.concat(r,i),a=e.map(function(t,e){return(t-o[e]%t)%t}),s=i.map(function(t,e){return t+a[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,a[e]]})]}([c.inHeight,c.inWidth],p,l),m=f[0],g=f[1],y=h?r:"valid",v=h?s:ra(s,p,m),b=("avg"===n?function(){return _s(v,e,o,1,y)}:function(){return Os(v,e,o,1,y)})(),w=h?b:Bo(b,p,g);return u?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}});var zs=Se({slice_:function(t,e,n){var r,i,o=xe(t,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(o.rank-1).fill(0)):e.length=0?t:(d(-1===t,function(){return"Bad value in size"}),o.shape[e]-r[e])}),function(t,e,n){d(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),d(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){d(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},i=0;i0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=sn(i.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),fu=Se({addN_:function(t){d(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return xe(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!b(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return Bt.engine.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),du=Se({addStrict_:function(t,e){var n=xe(t,"a","addStrict"),r=xe(e,"b","addStrict");return m(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),mu=Se({atan2_:function(t,e){var n,r=xe(t,"a","atan2"),i=xe(e,"b","atan2");n=bt(r,i),r=n[0],i=n[1];var o=un(r.shape,i.shape);return Bt.engine.runKernel(function(t){return t.atan2(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=hu(r.square(),i.square()),n=t.mul(i.div(e)),a=sn(r.shape,o);return a.length>0&&(n=n.sum(a)),n.reshape(r.shape)},$b:function(){var e=hu(r.square(),i.square()),n=Da(t.mul(r.div(e))),a=sn(i.shape,o);return a.length>0&&(n=n.sum(a)),n.reshape(i.shape)}}})}}),gu=Se({div_:function(t,e){var n,r,i=xe(t,"a","div"),o=xe(e,"b","div");if(n=bt(i,o),i=n[0],o=n[1],"int32"===i.dtype&&"int32"===o.dtype)return vu(i,o);r=function(t){return t.realDivide(i,o)};var a=un(i.shape,o.shape);return Bt.engine.runKernel(r,{$a:i,$b:o},function(t){return{$a:function(){var e=t.div(o.toFloat()),n=sn(i.shape,a);return n.length>0?e.sum(n).reshape(i.shape):e},$b:function(){var e=t.mul(i.toFloat()),n=sn(o.shape,a);n.length>0&&(e=e.sum(n).reshape(o.shape));var r=o.square();return e.div(r.toFloat()).neg()}}})}}),yu=Se({divStrict_:function(t,e){var n=xe(t,"a","div"),r=xe(e,"b","div");return m(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),vu=Se({floorDiv_:function(t,e){var n,r=xe(t,"a","floorDiv"),i=xe(e,"b","floorDiv");n=bt(r,i),r=n[0],i=n[1];var o=un(r.shape,i.shape);return Bt.engine.runKernel(function(t){return t.floorDiv(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t.div(i.toFloat()),n=sn(r.shape,o);return n.length>0?e.sum(n).reshape(r.shape):e},$b:function(){var e=t.mul(r.toFloat()),n=sn(i.shape,o);n.length>0&&(e=e.sum(n).reshape(i.shape));var a=i.square();return e.div(a.toFloat()).neg()}}})}}),bu=Se({maximum_:function(t,e){var n,r=xe(t,"a","maximum"),i=xe(e,"b","maximum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),un(r.shape,i.shape),Bt.engine.runKernel(function(t){return t.maximum(r,i)},{$a:r,$b:i},function(t){return{$a:function(){return t.mul(r.greaterEqual(i).toFloat())},$b:function(){return t.mul(r.less(i).toFloat())}}})}}),wu=Se({maximumStrict_:function(t,e){var n=xe(t,"a","maximumStrict"),r=xe(e,"b","maximumStrict");return m(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),xu=Se({minimum_:function(t,e){var n,r=xe(t,"a","minimum"),i=xe(e,"b","minimum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),un(r.shape,i.shape),Bt.engine.runKernel(function(t){return t.minimum(r,i)},{$a:r,$b:i},function(t){return{$a:function(){return t.mul(r.lessEqual(i).toFloat())},$b:function(){return t.mul(r.greater(i).toFloat())}}})}}),Nu=Se({minimumStrict_:function(t,e){var n=xe(t,"a","minimumStrict"),r=xe(e,"b","minimumStrict");return m(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Su=Se({mod_:function(t,e){var n,r=xe(t,"a","mod"),i=xe(e,"b","mod");n=bt(r,i),r=n[0],i=n[1];var o=un(r.shape,i.shape);return Bt.engine.runKernel(function(t){return t.mod(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=sn(r.shape,o);return e.length>0?t.sum(e).reshape(r.shape):t},$b:function(){var e=t.mul(r.div(i).floor().neg()),n=sn(i.shape,o);return n.length>0?e.sum(n).reshape(i.shape):e}}})}}),Cu=Se({modStrict_:function(t,e){var n=xe(t,"a","modStrict"),r=xe(e,"b","modStrict");return m(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Eu=Se({mul_:function(t,e){var n,r=xe(t,"a","mul"),i=xe(e,"b","mul");n=bt(r,i),r=n[0],i=n[1];var o=un(r.shape,i.shape);return Bt.engine.runKernel(function(t){return t.multiply(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t.mul(i.toFloat()),n=sn(r.shape,o);return n.length>0?e.sum(n).reshape(r.shape):e},$b:function(){var e=t.mul(r.toFloat()),n=sn(i.shape,o);return n.length>0?e.sum(n).reshape(i.shape):e}}})}}),Iu=Se({mulStrict_:function(t,e){var n=xe(t,"a","mul"),r=xe(e,"b","mul");return m(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),ku=Se({pow_:function(t,e){var n=xe(t,"base","pow"),r=xe(e,"exp","pow"),i=un(n.shape,r.shape);return t=n.cast(yt(n.dtype,r.dtype)),e=r.cast(yt(n.dtype,r.dtype)),Bt.engine.runKernel(function(t,e){return e(t.pow(n,r))},{$base:n,$exp:r},function(t,e){var o=e[0];return{$base:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(Re(1))))),a=sn(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},$exp:function(){var e=n.greater(0),a=n.log().where(e,je(n)),s=t.mul(o.mul(a)),u=sn(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),Au=Se({powStrict_:function(t,e){return m(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Tu=Se({squaredDifference_:function(t,e){var n,r=xe(t,"a","squaredDifference"),i=xe(e,"b","squaredDifference");return n=bt(r,i),r=n[0],i=n[1],un(r.shape,i.shape),Bt.engine.runKernel(function(t){return t.squaredDifference(r,i)},{$a:r,$b:i},function(t){var e=Re(2);return{$a:function(){return t.mul(r.sub(i).mul(e))},$b:function(){return t.mul(i.sub(r).mul(e))}}})}}),Ru=Se({squaredDifferenceStrict_:function(t,e){var n=xe(t,"a","squaredDifferenceStrict"),r=xe(e,"b","squaredDifferenceStrict");return m(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Du=Se({sub_:function(t,e){var n,r=xe(t,"a","sub"),i=xe(e,"b","sub");n=bt(r,i),r=n[0],i=n[1];var o=un(r.shape,i.shape);return Bt.engine.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=sn(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=sn(i.shape,o);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),Ou=Se({subStrict_:function(t,e){var n=xe(t,"a","subStrict"),r=xe(e,"b","subStrict");return m(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var _u=Se({logicalAnd_:function(t,e){var n=xe(t,"a","logicalAnd","bool"),r=xe(e,"b","logicalAnd","bool");return un(n.shape,r.shape),Bt.engine.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),Mu=Se({logicalNot_:function(t){var e=xe(t,"x","logicalNot","bool");return Bt.engine.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),Lu=Se({logicalOr_:function(t,e){var n=xe(t,"a","logicalOr","bool"),r=xe(e,"b","logicalOr","bool");return un(n.shape,r.shape),Bt.engine.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),Fu=Se({logicalXor_:function(t,e){var n=xe(t,"a","logicalXor","bool"),r=xe(e,"b","logicalXor","bool");return un(n.shape,r.shape),Lu(t,e).logicalAnd(_u(t,e).logicalNot())}}),zu=Se({where_:function(t,e,n){var r=xe(e,"a","where"),i=xe(n,"b","where"),o=xe(t,"condition","where","bool");return m(r.shape,i.shape,"Error in where: "),1===o.rank?d(o.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):m(o.shape,i.shape,"Error in where: "),Bt.engine.runKernel(function(t){return t.select(o,r,i)},{$condition:o,$a:r,$b:i},function(t){return{$condition:function(){return je(o).toFloat()},$a:function(){return t.mul(o.cast(t.dtype))},$b:function(){return t.mul(o.logicalNot().cast(t.dtype))}}})}}),Pu=function(t){return i(this,void 0,void 0,function(){var e,n,r;return o(this,function(i){switch(i.label){case 0:return[4,(e=xe(t,"condition","whereAsync","bool")).data()];case 1:return n=i.sent(),r=ca(e.shape,n),t!==e&&e.dispose(),[2,r]}})})};var Bu=Se({elu_:function(t){var e=xe(t,"x","elu");return Bt.engine.runKernel(function(t,n){return n(t.elu(e))},{$x:e},function(t,e){var n=e[0];return{$x:function(){return Bt.engine.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Uu=Se({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=xe(t,"x","leakyRelu");return bu(Re(e).mul(n),n)}}),Wu=Se({prelu_:function(t,e){var n=xe(t,"x","prelu"),r=xe(e,"alpha","prelu");return Bt.engine.runKernel(function(t){return t.prelu(n,r)},{$x:n,$alpha:r},function(t){var e=n.greater(0);return{$x:function(){return zu(e,t,t.mul(r))},$alpha:function(){var i=zu(e,je(t),t.mul(n)),o=sn(r.shape,t.shape);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Vu=Se({relu_:function(t){var e=xe(t,"x","relu");return"bool"===e.dtype?e.toInt():Bt.engine.runKernel(function(t){return t.relu(e)},{$x:e},function(t){var n=e.step();return{$x:function(){return t.mulStrict(n.toFloat())}}})}}),ju=Se({selu_:function(t){var e=xe(t,"x","selu");return Bt.engine.runKernel(function(t){return t.selu(e)},{$x:e},function(t){return{$x:function(){var n=e.greater(Re(0)),r=Re(ro),i=Re(io),o=t.mul(i),a=t.mul(r).mul(e.toFloat().exp());return zu(n,o,a)}}})}});var qu=Se({transpose_:function(t,e){var n=xe(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){d(t>=0&&ti)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var o=Bt.engine.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:o[0],indices:o[1]}}});var nl=Se({scatterND_:function(t,e,n){var r=xe(t,"indices","scatterND","int32"),i=xe(e,"updates","scatterND");return he(i,r,n),Bt.engine.runKernel(function(t){return t.scatterND(r,i,n)},{$indices:r,$updates:i})}});var rl=Se({fft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.engine.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),il=Se({ifft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.engine.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),ol=Se({rfft_:function(t){d("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.zerosLike(),i=Ie(t,r).as2D(n,e),o=rl(i),a=Math.floor(e/2)+1,s=ke(o),u=Ae(o),l=s.split([a,e-a],s.shape.length-1),c=u.split([a,e-a],u.shape.length-1),p=t.shape.slice();return p[t.shape.length-1]=a,Ie(l[0],c[0]).reshape(p)}}),al=Se({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=il(r);return ke(i)}var o=[n,2*(e-1)],a=ke(t).as2D(n,e),s=Ae(t).as2D(n,e),u=a.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(Re(-1)),c=a.concat(u,1),p=s.concat(l,1);return r=Ie(c,p).as2D(o[0],o[1]),i=il(r),ke(i)}}),sl=Object.freeze({fft:rl,ifft:il,rfft:ol,irfft:al});var ul=Se({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=xe(t,"sparseIndices","sparseToDense","int32"),o=xe(e,"sparseValues","sparseToDense"),a=xe(r,"defaultValue","sparseToDense",o.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var i=t.rank>0?t.shape[0]:1,o=t.rank>1?t.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var a=e.size;if(0!==e.rank&&(1!==e.rank||a!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,o,n,a),Bt.engine.runKernel(function(t){return t.sparseToDense(i,o,n,a)},{$sparseIndices:i,$sparseValues:o,$defaultValue:a})}});var ll=Se({gatherND_:function(t,e){var n=xe(e,"indices","gatherND","int32"),r=xe(t,"x","gatherND");return Bt.engine.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(t.Reduction||(t.Reduction={}));var cl=Se({absoluteDifference_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=xe(e,"labels","absoluteDifference"),a=xe(n,"predictions","absoluteDifference"),s=null;null!=r&&(s=xe(r,"weights","absoluteDifference")),m(o.shape,a.shape,"Error in absoluteDifference: ");var u=o.sub(a).abs();return pl(u,s,i)}}),pl=Se({computeWeightedLoss_:function(e,n,r){void 0===r&&(r=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=xe(e,"losses","computeWeightedLoss"),o=null;null!=n&&(o=xe(n,"weights","computeWeightedLoss"));var a=null==o?i:i.mul(o);if(r===t.Reduction.NONE)return a;if(r===t.Reduction.SUM)return a.sum();if(r===t.Reduction.MEAN){if(null==o)return a.mean();var s=v(i.shape)/v(o.shape),u=a.sum().div(o.sum());return s>1?u.div(Re(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(Re(i.size));var l=o.mul(ze(i.shape)).notEqual(Re(0)).sum().toFloat();return a.sum().div(l)}throw Error("Unknown reduction: "+r)}}),hl=Se({cosineDistance_:function(e,n,r,i,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=xe(e,"labels","cosineDistance"),s=xe(n,"predictions","cosineDistance"),u=null;null!=i&&(u=xe(i,"weights","cosineDistance")),m(a.shape,s.shape,"Error in cosineDistance: ");var l=Re(1).sub(a.mul(s).sum(r,!0));return pl(l,u,o)}}),fl=Se({hingeLoss_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=xe(e,"labels","hingeLoss"),a=xe(n,"predictions","hingeLoss"),s=null;null!=r&&(s=xe(r,"weights","hingeLoss")),m(o.shape,a.shape,"Error in hingeLoss: ");var u=Re(1);o=Re(2).mul(o).sub(u);var l=u.sub(o.mul(a)).relu();return pl(l,s,i)}}),dl=Se({huberLoss_:function(e,n,r,i,o){void 0===i&&(i=1),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=xe(e,"labels","huberLoss"),s=xe(n,"predictions","huberLoss"),u=null;null!=r&&(u=xe(r,"weights","huberLoss")),m(a.shape,s.shape,"Error in huberLoss: ");var l=Re(i),c=s.sub(a).abs(),p=xu(c,l),h=c.sub(p),f=Re(.5).mul(p.square()).add(l.mul(h));return pl(f,u,o)}}),ml=Se({logLoss_:function(e,n,r,i,o){void 0===i&&(i=1e-7),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=xe(e,"labels","logLoss"),s=xe(n,"predictions","logLoss"),u=null;null!=r&&(u=xe(r,"weights","logLoss")),m(a.shape,s.shape,"Error in logLoss: ");var l=Re(1),c=Re(i),p=a.mul(s.add(c).log()).neg().sub(l.sub(a).mul(l.sub(s).add(c).log()));return pl(p,u,o)}}),gl=Se({meanSquaredError_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=xe(e,"labels","meanSquaredError"),a=xe(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=xe(r,"weights","meanSquaredError")),m(o.shape,a.shape,"Error in meanSquaredError: ");var u=o.squaredDifference(a);return pl(u,s,i)}}),yl=Se({sigmoidCrossEntropy_:function(e,n,r,i,o){void 0===i&&(i=0),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=xe(e,"multiClassLabels","sigmoidCrossEntropy"),s=xe(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=xe(r,"weights","sigmoidCrossEntropy")),m(a.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=Re(i),c=Re(1),p=Re(.5);a=a.mul(c.sub(l)).add(p.mul(l))}var h=function(t,e){var n=xe(t,"labels","sigmoidCrossEntropyWithLogits"),r=xe(e,"logits","sigmoidCrossEntropyWithLogits");m(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),o=r.mul(n),a=r.abs().neg().exp().log1p();return i.sub(o).add(a)}(a,s);return pl(h,u,o)}}),vl=Se({softmaxCrossEntropy_:function(e,n,r,i,o){void 0===i&&(i=0),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=xe(e,"onehotLabels","softmaxCrossEntropy"),s=xe(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=xe(r,"weights","softmaxCrossEntropy")),m(a.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=Re(i),c=Re(1),p=Re(a.shape[1]);a=a.mul(c.sub(l)).add(l.div(p))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Vt(function(t,e){var r=e.logSumExp([n],!0),i=e.toFloat().sub(r);return{value:i.mul(t).neg().sum([n]),gradFunc:function(e){var r=re(e.shape,[n]);return[e.reshape(r).mul(t.toFloat().sub(i.exp())),e.reshape(r).mul(i.exp().sub(t.toFloat()))]}}})(t,e)}(a,s);return pl(h,u,o)}}),bl=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:cl,computeWeightedLoss:pl,cosineDistance:hl,hingeLoss:fl,huberLoss:dl,logLoss:ml,meanSquaredError:gl,sigmoidCrossEntropy:yl,softmaxCrossEntropy:vl});function wl(t,e){return void 0===e&&(e=!1),Bt.engine.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],i=Go(n),o=t.clone(),a=Oe([[1]],[1,1]),s=a.clone(),u=n>=r?r:n,l=function(t){var e,u=o,l=s,c=i;e=Bt.engine.tidy(function(){var e=o.slice([t,t],[n-t,1]),u=e.norm(),l=o.slice([t,t],[1,1]),c=l.sign().neg(),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?a.clone():a.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=o.slice([t,0],[n-t,r]),m=f.mul(s);o=0===t?d.sub(m.matMul(s.transpose().matMul(d))):o.slice([0,0],[t,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=i.slice([0,t],[n,i.shape[1]-t]);return i=0===t?g.sub(g.matMul(s).matMul(m.transpose())):i.slice([0,0],[n,t]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,o,i]}),s=e[0],o=e[1],i=e[2],Ht([u,l,c])},c=0;cr&&(i=i.slice([0,0],[n,r]),o=o.slice([0,0],[r,r])),[i,o]})}var xl=Se({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,d(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){d(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return wl(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return ua(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=wl(t,e),o=n[0],a=n[1];r.push(o),i.push(a)}),[oa(r,0).reshape(t.shape),oa(i,0).reshape(t.shape)]}}),Sl=Object.freeze({gramSchmidt:xl,qr:Nl});function Cl(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var o=t.shape[0];return n=Math.min(n,o),d(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),d(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),d(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),d(1===e.rank,function(){return"scores must be a 1D tensor"}),d(e.shape[0]===o,function(){return"scores has incompatible shape with boxes. Expected "+o+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var El=Se({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=xe(t,"images","resizeBilinear");d(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Bt.engine.runKernel(function(t,e){return t.resizeBilinear(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Bt.engine.runKernel(function(e){return e.resizeBilinearBackprop(t,i,n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Il=Se({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=xe(t,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),d("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Bt.engine.runKernel(function(t,e){return t.resizeNearestNeighbor(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Bt.engine.runKernel(function(e){return e.resizeNearestNeighborBackprop(t,i,n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),kl=Se({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var o=xe(t,"boxes","nonMaxSuppression"),a=xe(e,"scores","nonMaxSuppression"),s=Cl(o,a,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,Bt.engine.runKernel(function(t){return t.nonMaxSuppression(o,a,n,r,i)},{$boxes:o})}}),Al=function(t,e,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),i(this,void 0,void 0,function(){var i,s,u,l,c,p;return o(this,function(o){switch(o.label){case 0:return i=xe(t,"boxes","nonMaxSuppressionAsync"),s=xe(e,"scores","nonMaxSuppressionAsync"),u=Cl(i,s,n,r,a),n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,[4,i.data()];case 1:return l=o.sent(),[4,s.data()];case 2:return c=o.sent(),p=Ze(l,c,n,r,a),i!==t&&i.dispose(),s!==e&&s.dispose(),[2,p]}})})},Tl=Se({cropAndResize_:function(t,e,n,r,i,o){var a=xe(t,"image","cropAndResize","float32"),s=xe(e,"boxes","cropAndResize","float32"),u=xe(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;var l=s.shape[0];return d(4===a.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."}),d(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),d(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),d(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),d(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),d("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),Bt.engine.runKernel(function(t,e){return t.cropAndResize(a,s,u,r,i,o)},{$image:a,$boxes:s})}}),Rl=Object.freeze({resizeBilinear:El,resizeNearestNeighbor:Il,nonMaxSuppression:kl,nonMaxSuppressionAsync:Al,cropAndResize:Tl});var Dl=Se({matMul_:function(t,e,n,r,i,o){var a;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o="linear");var s=xe(t,"a","fused matMul"),u=xe(e,"b","fused matMul");a=bt(s,u),s=a[0],u=a[1];var l=n?s.shape[s.rank-2]:s.shape[s.rank-1],c=r?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?s.shape[s.rank-1]:s.shape[s.rank-2],h=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=s.shape.slice(0,-2),m=u.shape.slice(0,-2),g=v(f),y=v(m);d(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+"."}),d(b(f,m),function(){return"Error in fused matMul: outer dimensions ("+f+") and ("+m+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match."}),d(l===c,function(){return"Error in fused matMul: inner shapes ("+l+") and ("+c+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var w,x=s.shape.slice(0,-2).concat([p,h]),N=n?s.as3D(g,l,p):s.as3D(g,p,l),S=r?u.as3D(y,h,c):u.as3D(y,c,h);null!=i&&un(x,(w=bt(w=xe(i,"bias","fused matMul"),s)[0]).shape);var C={$a:N,$b:S};return null!=i&&(C.$bias=w),Bt.engine.runKernel(function(t,e){return e(t.fusedBatchMatMul(N,S,n,r,w,o))},C,function(t,e){var a,s=e[0];if(null==o||"linear"===o)a=t;else{if("relu"!==o)throw new Error("Gradient for activation "+o+" has not been implemented yet.");a=t.mul(s.step())}var u={};return null!=i&&(u={$bias:function(){var t=a,e=sn(w.shape,a.shape);return e.length>0&&(t=t.sum(e)),t.reshape(w.shape)}}),n||r?!n&&r?Object.assign({$a:function(){return a.matMul(S,!1,!1)},$b:function(){return a.matMul(N,!0,!1)}},u):n&&!r?Object.assign({$a:function(){return S.matMul(a,!1,!0)},$b:function(){return N.matMul(a,!1,!1)}},u):Object.assign({$a:function(){return S.matMul(a,!0,!0)},$b:function(){return a.matMul(N,!0,!0)}},u):Object.assign({$a:function(){return a.matMul(S,!1,!0)},$b:function(){return N.matMul(a,!0,!1)}},u)}).reshape(x)}}),Ol=Object.freeze({matMul:Dl}),_l=Object.freeze({image:Rl,linalg:Sl,losses:bl,spectral:sl,fused:Ol,op:Se,batchNormalization2d:Ja,batchNormalization3d:Za,batchNormalization4d:Qa,batchNormalization:ts,batchNorm:es,batchNorm2d:ns,batchNorm3d:rs,batchNorm4d:is,complex:Ie,real:ke,imag:Ae,concat:xo,concat1d:No,concat2d:So,concat3d:Co,concat4d:Eo,split:Io,conv1d:ys,conv2d:vs,conv3d:bs,conv2dDerFilter:ws,depthwiseConv2d:xs,separableConv2d:Ns,conv2dTranspose:Ss,matMul:Cs,dot:Es,outerProduct:Is,reverse:ks,reverse1d:As,reverse2d:Ts,reverse3d:Rs,reverse4d:Ds,maxPool:Ms,avgPool:Ls,pool:Fs,slice:zs,slice1d:Ps,slice2d:Bs,slice3d:Us,slice4d:Ws,abs:fa,acos:da,acosh:ma,asin:ga,asinh:ya,atan:va,atanh:ba,ceil:wa,clipByValue:xa,cos:Na,cosh:Sa,erf:Ca,exp:Ea,expm1:Ia,floor:ka,log:Aa,log1p:Ta,logSigmoid:Ra,neg:Da,reciprocal:Oa,round:_a,rsqrt:Ma,sigmoid:La,sign:Fa,sin:za,sinh:Pa,softplus:Ba,sqrt:Ua,square:Wa,step:Va,tan:ja,tanh:qa,all:js,any:qs,argMax:Gs,argMin:Hs,logSumExp:Ks,max:$s,mean:Xs,min:Ys,moments:Js,sum:Zs,prod:Qs,equal:tu,equalStrict:eu,greater:nu,greaterEqual:ru,greaterEqualStrict:iu,greaterStrict:ou,less:au,lessEqual:su,lessEqualStrict:uu,lessStrict:lu,notEqual:cu,notEqualStrict:pu,add:hu,addN:fu,addStrict:du,atan2:mu,div:gu,divStrict:yu,floorDiv:vu,maximum:bu,maximumStrict:wu,minimum:xu,minimumStrict:Nu,mod:Su,modStrict:Cu,mul:Eu,mulStrict:Iu,pow:ku,powStrict:Au,squaredDifference:Tu,squaredDifferenceStrict:Ru,sub:Du,subStrict:Ou,elu:Bu,leakyRelu:Uu,prelu:Wu,relu:Vu,selu:ju,logicalAnd:_u,logicalNot:Mu,logicalOr:Lu,logicalXor:Fu,where:zu,whereAsync:Pu,buffer:zo,print:Po,batchToSpaceND:Bo,cast:Uo,clone:Wo,cumsum:Vo,depthToSpace:jo,expandDims:qo,eye:Go,multinomial:Ho,oneHot:Ko,pad:$o,pad1d:Xo,pad2d:Yo,pad3d:Jo,pad4d:Zo,rand:Qo,randomNormal:ta,randomUniform:ea,reshape:na,spaceToBatchND:ra,squeeze:ia,stack:oa,tile:aa,truncatedNormal:sa,unstack:ua,setdiff1dAsync:la,fill:Be,linspace:Ue,ones:ze,range:We,scalar:Re,tensor:Te,tensor1d:De,tensor2d:Oe,tensor3d:_e,tensor4d:Me,tensor5d:Le,tensor6d:Fe,zeros:Pe,onesLike:Ve,zerosLike:je,transpose:qu,softmax:Ce,logSoftmax:Ee,localResponseNormalization:Gu,norm:Hu,gather:Xu,unsortedSegmentSum:Yu,basicLSTMCell:Ju,multiRNNCell:Zu,movingAverage:Qu,stridedSlice:tl,topk:el,scatterND:nl,fft:rl,ifft:il,rfft:ol,irfft:al,sparseToDense:ul,gatherND:ll});var Ml=function(){function t(){this.blockSize=48,this.firstUse=!0,Bt.get("IS_BROWSER")&&(this.fromPixels2DContext=document.createElement("canvas").getContext("2d"))}return t.prototype.setDataMover=function(t){this.data=new qe(t)},t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,Bt.get("IS_NODE")&&Xt("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n})},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r;if(Bt.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(t instanceof ImageData)n=t.data;else{if(!(t instanceof HTMLImageElement||t instanceof HTMLVideoElement))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data}if(4===e)r=new Int32Array(n);else{var i=t.width*t.height;r=new Int32Array(i*e);for(var o=0;oh&&(h=m,f=d)}u[c]=f}return a},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var i=yt(t.dtype,"int32"),o=Pe(t.shape,i),a=o.dataSync(),s=t.dataSync(),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?1:0})},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=t.dataSync(),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],c=0;c=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),ie("max",e,t.rank);for(var n=ne(t.shape,e),r=n[0],i=n[1],o=Pe(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;lp&&(p=f)}s[l]=p}return o},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),ie("all",e,t.rank);for(var n=ne(t.shape,e),r=n[0],i=n[1],o=Pe(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l0?n[r]=1:n[r]=0;return ut.make(t.shape,{values:n})},t.prototype.round=function(t){this.assertNotComplex(t,"round");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return ut.make(t.shape,{values:n})},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r=0?i:Math.exp(i)-1}return ut.make(t.shape,{values:e})},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=e.dataSync(),i=t.dataSync(),o=0;o=1?i[o]:i[o]*(a+1)}return ut.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=ro,n=io,r=new Float32Array(t.size),i=t.dataSync(),o=0;o=0?n*a:e*(Math.exp(a)-1)}return ut.make(t.shape,{values:r})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=t.dataSync(),o=0;on?n:a-e,s=r[i]0?1:e}return ut.make(t.shape,{values:n})},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=zo(n.outShape,t.dtype),c=t.dataSync(),p=e.dataSync(),h=l.values,f=0;f=n.inHeight))for(var x=b*e.strides[0],N=d+w*t.strides[1],S=0;S=n.inWidth))for(var A=x+I*e.strides[1],T=N+k*n.inChannels,R=A,D=0;D=n.inDepth))for(var C=N*e.strides[0],E=y+S*t.strides[1],I=0;I=n.inHeight))for(var D=C+T*e.strides[1],O=E+R*t.strides[2],_=0;_=n.inWidth))for(var P=D+F*e.strides[2],B=O+z*n.inChannels,U=P,W=0;W=n.inHeight))for(var N=w*e.strides[0],S=m+x*t.strides[1],C=0;C=n.inWidth))for(var T=N+k*e.strides[1],R=S+A*n.inChannels,D=E,O=T,_=0;_D?D=z:"avg"===n&&(O+=z,_++)}if(isNaN(D))break}d[I+k*y+x]="avg"===n?O/_:D}return f.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=zo(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p=t.bufferSync(),h=0;hN&&(N=A,S=E*u+k)}n.set(S,h,d,v,f)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),o=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=c-1-r.padInfo.left,h=l-1-r.padInfo.top,f=zo(e.shape,"float32"),d=i.bufferSync(),m=t.bufferSync(),g=0;g=r.outHeight||Math.floor(C)!==C))for(var E=0;E=r.outWidth||Math.floor(I)!==I)){var k=l*c-1-d.get(g,C,I,y)===S*c+E?1:0;0!==k&&(N+=m.get(g,C,I,y)*k)}}}f.set(N,g,v,b,y)}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=zo(e.shape,"float32"),d=1/(o*a),m=t.bufferSync(),g=0;g=n.outHeight||Math.floor(C)!==C))for(var E=0;E=n.outWidth||Math.floor(I)!==I||(N+=m.get(g,C,I,y))}}f.set(N*d,g,v,b,y)}return f.toTensor()},t.prototype.cast=function(t,e){return He(t,e,this)},t.prototype.reshape=function(t,e){return Ke(t,e)},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var i=t.shape,o=i[0],a=i[1],s=i[2],u=i[3],l=t.dataSync(),c=new Float32Array(v([o,e,n,u])),p=[r&&e>1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g1?o-1:o,n&&c>1?a-1:a],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=t.dataSync(),y=0,v=0;v1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g1?o-1:o,n&&c>1?a-1:a],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],y=1/m,v=1/g,b=2*Math.ceil(y)+2,w=2*Math.ceil(v)+2,x=0;x=l)){var L=N+M*t.strides[1],F=M*m;if(S===Math.min(o-1,n?Math.round(F):Math.floor(F)))for(var z=0;z=c)){var B=L+P*t.strides[2],U=P*g;k===Math.min(a-1,n?Math.round(U):Math.floor(U))&&(O+=h[B+D])}}}}p[A+D]=O}return Me(p,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,i,o){this.assertNotComplex([t,e,n,i,o],"batchNorm");for(var a=t.dataSync(),s=e.dataSync(),u=n.dataSync(),l=i?i.dataSync():new Float32Array([1]),c=o?o.dataSync():new Float32Array([0]),p=new Float32Array(a.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w=h&&(g=0),y>=m&&(y=0),v>=f&&(v=0),b>=d&&(b=0);return Me(p,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var o=t.shape[3],a=o-1,s=t.dataSync(),u=v(t.shape),l=new Float32Array(u);function c(t){for(var n=t%o,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,a),u=0;r<=i;r++){var l=s[r];u+=l*l}return u}for(var p=0;p=0&&o[a]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],o=t.shape[2],a=t.shape[3],s=i*e,u=o*e,l=a/(e*e),c=t.dataSync(),p=new Float32Array(r*s*u*l),h=0,f=0;f=s))for(var k=h>1?(C-N)*(u-1)/(h-1):0,A=f>1?(E-S)*(l-1)/(f-1):0,T=0;T1?N*(u-1)+T*k:.5*(N+C)*(u-1);if(R<0||R>u-1)for(var D=0;D1?S*(l-1)+D*A:.5*(S+E)*(l-1))<0||G>l-1)for(O=0;O1?S*(l-1)+D*A:.5*(S+E)*(l-1))<0||G>l-1)for(O=0;O=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var y=0;y=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b0,function(){return"scheme must not be an empty string."});var r=t.getInstance();d(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Kl(t){if(-1===t.indexOf(Gl))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Hl.getSchemes().join(","));return{scheme:t.split(Gl)[0],path:t.split(Gl)[1]}}function $l(t,e,n){return void 0===n&&(n=!1),i(this,void 0,void 0,function(){var r,i,a,s,u,l,c,p,h;return o(this,function(o){switch(o.label){case 0:return d(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),d((r=ql.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),d(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),i=r[0],d((a=ql.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),d(a.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=a[0],u=Kl(t).scheme,l=Kl(t).path,c=u===Kl(t).scheme,[4,i.load()];case 1:return p=o.sent(),n&&c?[4,Hl.getManager(u).removeModel(l)]:[3,3];case 2:o.sent(),o.label=3;case 3:return[4,s.save(p)];case 4:return h=o.sent(),!n||c?[3,6]:[4,Hl.getManager(u).removeModel(l)];case 5:o.sent(),o.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var Xl="models_store",Yl="model_info_store";function Jl(){if(!Bt.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Zl(t){var e=t.result;e.createObjectStore(Xl,{keyPath:"modelPath"}),e.createObjectStore(Yl,{keyPath:"modelPath"})}var Ql=function(){function t(t){if(this.indexedDB=Jl(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){return o(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return i(this,void 0,void 0,function(){return o(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Zl(i)},i.onsuccess=function(){var o=i.result;if(null==e){var a=o.transaction(Xl,"readonly"),s=a.objectStore(Xl).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return o.close(),r(s.error)},a.oncomplete=function(){return o.close()}}else{var u,l=jl(e),c=o.transaction(Yl,"readwrite"),p=c.objectStore(Yl),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var i=(u=o.transaction(Xl,"readwrite")).objectStore(Xl).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});i.onsuccess=function(){return t({modelArtifactsInfo:l})},i.onerror=function(t){var e=(p=c.objectStore(Yl)).delete(n.modelPath);e.onsuccess=function(){return o.close(),r(i.error)},e.onerror=function(t){return o.close(),r(i.error)}}},h.onerror=function(t){return o.close(),r(h.error)},c.oncomplete=function(){null==u?o.close():u.oncomplete=function(){return o.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),tc=function(t){return Bt.get("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Ql.URL_SCHEME)?function(t){return new Ql(t)}(t.slice(Ql.URL_SCHEME.length)):null};ql.registerSaveRouter(tc),ql.registerLoadRouter(tc);var ec=function(){function t(){this.indexedDB=Jl()}return t.prototype.listModels=function(){return i(this,void 0,void 0,function(){var t=this;return o(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Zl(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(Yl,"readonly"),o=i.objectStore(Yl).getAll();o.onsuccess=function(){for(var t={},n=0,r=o.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){d(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),d(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),d(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(o){return o.then(function(o){var a=n+ ++i/t.length*(r-n);return e(a),o}),o}))}function wc(t,e){return i(this,void 0,void 0,function(){var n,r,i,a,s,u,l,c,p;return o(this,function(o){switch(o.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?fetch:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit)}),i=0,a=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return s=o.sent(),[3,4];case 2:return[4,bc(r,e.onProgress,i,a)];case 3:s=o.sent(),o.label=4;case 4:return u=s.map(function(t){return t.arrayBuffer()}),l=.5,c=1,null!=e.onProgress?[3,6]:[4,Promise.all(u)];case 5:return p=o.sent(),[3,8];case 6:return[4,bc(u,e.onProgress,l,c)];case 7:p=o.sent(),o.label=8;case 8:return[2,p]}})})}function xc(t){var e=this;return function(n,r,a){return void 0===r&&(r=""),i(e,void 0,void 0,function(){var e,i,s,u,l,c,p,h,f,d;return o(this,function(o){switch(o.label){case 0:if(e=n.map(function(){return!1}),i={},s=null!=a?a.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var o="quantization"in t?t.quantization.dtype:t.dtype,l=zl[o]*v(t.shape),c=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:l})};null!=a?a.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),r+=l})}),!s.every(function(t){return t}))throw l=a.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),p=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=o.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,r=0,o=0;o0,function(){return"URL path for browserHTTPRequest must not be null, undefined or empty."}),Array.isArray(t)&&d(2===t.length,function(){return"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){var e,n,r,i;return o(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.getFetchFunc()(this.path,e)];case 1:if((i=o.sent()).ok)return[2,{modelArtifactsInfo:jl(t),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}})})},t.prototype.load=function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a,s,u;return o(this,function(o){switch(o.label){case 0:return[4,this.getFetchFunc()(this.path,this.requestInit)];case 1:if(!(t=o.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");o.label=2;case 2:return o.trys.push([2,4,,5]),[4,t.json()];case 3:return e=o.sent(),[3,5];case 4:throw o.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,i=e.weightsManifest,null==r&&null==i)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==i?[3,7]:[4,this.loadWeights(i)];case 6:u=o.sent(),a=u[0],s=u[1],o.label=7;case 7:return[2,{modelTopology:r,weightSpecs:a,weightData:s}]}})})},t.prototype.loadWeights=function(t){return i(this,void 0,void 0,function(){var e,n,r,i,a,s,u,l,c,p,h;return o(this,function(o){switch(o.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],i=n[1],a=this.weightPathPrefix||r,s=[],u=0,l=t;u0&&(t=r({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=r({weightData:this.weightData},t)),[2,t]})})},t}(),kc=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){return o(this,function(e){return[2,this.saveHandler(t)]})})},t}();var Ac=Object.freeze({browserFiles:function(t){return new vc(t)},browserHTTPRequest:Ec,concatenateArrayBuffers:Wl,decodeWeights:Pl,encodeWeights:function(t){return i(this,void 0,void 0,function(){var e,n,r,i;return o(this,function(o){switch(o.label){case 0:for(r in e=[],n=[],t){if("float32"!==(i=t[r]).dtype&&"int32"!==i.dtype&&"bool"!==i.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+i.dtype);e.push({name:r,shape:i.shape,dtype:i.dtype}),n.push(i.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach(function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)});var r=new Uint8Array(e),i=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),i),i+=t.byteLength}),r.buffer}(o.sent()),specs:e}]}})})},fromMemory:function(t,e,n){return new Ic(t,e,n)},getLoadHandlers:function(t,e){return ql.getLoadHandlers(t)},getModelArtifactsInfoForJSON:jl,getSaveHandlers:function(t){return ql.getSaveHandlers(t)},isHTTPScheme:Sc,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),i(this,void 0,void 0,function(){return o(this,function(i){return[2,xc(function(t){return wc(t,{requestInit:r})})(t,e,n)]})})},registerLoadRouter:function(t){return ql.registerLoadRouter(t)},registerSaveRouter:function(t){return ql.registerSaveRouter(t)},weightsLoaderFactory:xc,withSaveHandler:function(t){return new kc(t)},copyModel:function(t,e){return i(this,void 0,void 0,function(){return o(this,function(n){switch(n.label){case 0:return[4,$l(t,e,!1)];case 1:return[2,n.sent()]}})})},listModels:function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a,s;return o(this,function(o){switch(o.label){case 0:t=Hl.getSchemes(),e={},n=0,r=t,o.label=1;case 1:return n0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),d(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),d(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),d(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),d(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var o=Ko(r.asType("int32"),n),a=Ko(i.asType("int32"),n);return o.transpose().matMul(a).asType("int32")}}),Rc=Object.freeze({confusionMatrix:Tc});var Dc=Se({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return Bt.engine.fromPixels(t,e)}}),Oc=Object.freeze({toPixels:function(t,e){return i(this,void 0,void 0,function(){var n,r,i,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N;return o(this,function(o){switch(o.label){case 0:if(n=xe(t,"img","toPixels"),t instanceof ut||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),i=r[0],a=r[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return u=n.min(),l=n.max(),[4,u.data()];case 1:return c=o.sent()[0],[4,l.data()];case 2:if(p=o.sent()[0],u.dispose(),l.dispose(),"float32"===n.dtype){if(c<0||p>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+c+" - "+p+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(c<0||p>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+c+" - "+p+"].")}return[4,n.data()];case 3:for(h=o.sent(),f="float32"===n.dtype?255:1,d=new Uint8ClampedArray(a*i*4),m=0;m0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Mc.register(t)}var Fc=Object.freeze({Serializable:_c,SerializationMap:Mc,registerClass:Lc});function zc(t,e,n){return null==n&&(n=Bt.get("TEST_EPSILON")),Pc(t,"number"==typeof e||"boolean"==typeof e?[e]:e,function(t,e){return Bc(t,Number(e),n)})}function Pc(t,e,n){if(t instanceof ut||e instanceof ut){if(t instanceof ut&&e instanceof ut){if(t.dtype!==e.dtype)throw new Error("Arrays are of different type actual: "+t.dtype+" vs expected: "+e.dtype+".");if(!b(t.shape,e.shape))throw new Error("Arrays are of different shape actual: "+t.shape+" vs expected: "+e.shape+".")}}else{var r=t.constructor.name,i=e.constructor.name;if(r!==i)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+i)}var o,a;if(o=t instanceof ut?t.dataSync():t,a=e instanceof ut?e.dataSync():e,o.length!==a.length)throw new Error("Arrays have different lengths actual: "+o.length+" vs expected: "+a.length+".\nActual: "+o+".\nExpected: "+a+".");for(var s=0;sn)}var Uc=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},PACKED_ENVS:{WEBGL_PACK:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},ALL_ENVS:{},expectArraysClose:zc,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return t instanceof ut&&"string"===t.dtype||e instanceof ut&&"string"===e.dtype||Array.isArray(t)&&F(t[0])||Array.isArray(e)&&F(e[0])?Pc(t,n,function(t,e){return t==e}):zc(t,e,0)},expectNumbersClose:function(t,e,n){if(null==n&&(n=Bt.get("TEST_EPSILON")),!Bc(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){var r;r=t instanceof ut?t.dataSync():t;for(var i=0;in)throw new Error("Value out of range:"+r[i]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),Wc=Object.freeze({gpgpu_util:Ni,webgl_util:ti,MathBackendWebGL:pa,GPGPUContext:Si}),Vc=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),i=r.value,o=r.grads;return this.applyGradients(o),Object.keys(o).forEach(function(t){return o[t].dispose()}),e?i:(i.dispose(),null)},e.prototype.computeGradients=function(t,e){return Wt(t,e)},e.prototype.dispose=function(){},e}(_c);Object.defineProperty(Vc,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var jc=function(t){function e(e,n,r){void 0===r&&(r=null);var i=t.call(this)||this;return i.learningRate=e,i.rho=n,i.epsilon=r,i.accumulatedGrads={},i.accumulatedUpdates={},i.c=Gt(Re(-e)),i.rhoScalar=Gt(Re(n)),i.oneMinusRho=Gt(Re(1-n)),null===r&&(r=Bt.get("EPSILON")),i.epsilonScalar=Gt(Re(r)),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Bt.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&qt(function(){e.accumulatedGrads[n]=je(i).variable(!1)}),null==r.accumulatedUpdates[n]&&qt(function(){e.accumulatedUpdates[n]=je(i).variable(!1)});var o=t[n],a=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];qt(function(){var t=e.rhoScalar.mul(a).add(e.oneMinusRho.mul(o.square())),r=s.add(e.epsilonScalar).sqrt().div(a.add(e.epsilonScalar).sqrt()).mul(o),u=e.rhoScalar.mul(s).add(e.oneMinusRho.mul(r.square()));e.accumulatedGrads[n].assign(t),e.accumulatedUpdates[n].assign(u);var l=e.c.mul(r).add(i);i.assign(l)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(e){return t.accumulatedUpdates[e].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(e){return t.accumulatedGrads[e].dispose()}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="AdadeltaOptimizer",e}(Vc);Lc(jc);var qc=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Gt(Re(-e)),r.epsilon=Gt(Re(Bt.get("EPSILON"))),r}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Bt.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&qt(function(){e.accumulatedGrads[n]=Be(i.shape,e.initialAccumulatorValue).variable(!1)});var o=t[n],a=r.accumulatedGrads[n];qt(function(){var t=a.add(o.square());e.accumulatedGrads[n].assign(t);var r=e.c.mul(o.div(t.add(e.epsilon).sqrt())).add(i);i.assign(r)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(e){return t.accumulatedGrads[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="AdagradOptimizer",e}(Vc);Lc(qc);var Gc=function(t){function e(e,n,r,i){void 0===i&&(i=null);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=i,o.accumulatedFirstMoment={},o.accumulatedSecondMoment={},o.c=Gt(Re(-e)),o.beta1Scalar=Gt(Re(n)),o.beta2Scalar=Gt(Re(r)),qt(function(){o.accBeta1=Re(n).variable(),o.accBeta2=Re(r).variable()}),o.oneMinusBeta1=Gt(Re(1-n)),o.oneMinusBeta2=Gt(Re(1-r)),o.one=Gt(Re(1)),null===i&&(i=Bt.get("EPSILON")),o.epsScalar=Gt(Re(i)),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this;qt(function(){var n=e.one.sub(e.accBeta1),r=e.one.sub(e.accBeta2);for(var i in t){var o=Bt.engine.registeredVariables[i];if(null==e.accumulatedFirstMoment[i]){var a=!1;e.accumulatedFirstMoment[i]=je(o).variable(a)}null==e.accumulatedSecondMoment[i]&&(a=!1,e.accumulatedSecondMoment[i]=je(o).variable(a));var s=t[i],u=e.accumulatedFirstMoment[i],l=e.accumulatedSecondMoment[i],c=e.beta1Scalar.mul(u).add(e.oneMinusBeta1.mul(s)),p=e.beta2Scalar.mul(l).add(e.oneMinusBeta2.mul(s.square())),h=c.div(n),f=p.div(r);e.accumulatedFirstMoment[i].assign(c),e.accumulatedSecondMoment[i].assign(p);var d=e.c.mul(h.div(e.epsScalar.add(f.sqrt()))).add(o);o.assign(d)}e.accBeta1.assign(e.accBeta1.mul(e.beta1Scalar)),e.accBeta2.assign(e.accBeta2.mul(e.beta2Scalar))})},e.prototype.dispose=function(){var t=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(e){return t.accumulatedFirstMoment[e].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(e){return t.accumulatedSecondMoment[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="AdamOptimizer",e}(Vc);Lc(Gc);var Hc=function(t){function e(e,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=0);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=i,a.decay=o,a.accumulatedFirstMoment={},a.accumulatedWeightedInfNorm={},a.c=Gt(Re(-e)),a.beta1Scalar=Gt(Re(n)),a.beta2Scalar=Gt(Re(r)),a.decayScalar=Gt(Re(o)),qt(function(){a.iteration=Re(0).variable(),a.accBeta1=Re(n).variable()}),a.oneMinusBeta1=Gt(Re(1-n)),a.one=Gt(Re(1)),null===i&&(i=Bt.get("EPSILON")),a.epsScalar=Gt(Re(i)),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this;qt(function(){var n=e.one.sub(e.accBeta1),r=e.c.div(e.one.add(e.decayScalar.mul(e.iteration)));for(var i in t){var o=Bt.engine.registeredVariables[i];if(null==e.accumulatedFirstMoment[i]){var a=!1;e.accumulatedFirstMoment[i]=je(o).variable(a)}null==e.accumulatedWeightedInfNorm[i]&&(a=!1,e.accumulatedWeightedInfNorm[i]=je(o).variable(a));var s=t[i],u=e.accumulatedFirstMoment[i],l=e.accumulatedWeightedInfNorm[i],c=e.beta1Scalar.mul(u).add(e.oneMinusBeta1.mul(s)),p=e.beta2Scalar.mul(l),h=s.abs(),f=p.maximum(h);e.accumulatedFirstMoment[i].assign(c),e.accumulatedWeightedInfNorm[i].assign(f);var d=r.div(n).mul(c.div(e.epsScalar.add(f))).add(o);o.assign(d)}e.iteration.assign(e.iteration.add(e.one)),e.accBeta1.assign(e.accBeta1.mul(e.beta1Scalar))})},e.prototype.dispose=function(){var t=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(e){return t.accumulatedFirstMoment[e].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(e){return t.accumulatedWeightedInfNorm[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="AdamaxOptimizer",e}(Vc);Lc(Hc);var Kc=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return n(e,t),e.prototype.applyGradients=function(t){var e=this;Object.keys(t).forEach(function(n){var r=t[n],i=Bt.engine.registeredVariables[n];qt(function(){var t=e.c.mul(r).add(i);i.assign(t)})})},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Gt(Re(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGDOptimizer",e}(Vc);Lc(Kc);var $c=function(t){function e(e,n,r){void 0===r&&(r=!1);var i=t.call(this,e)||this;return i.learningRate=e,i.momentum=n,i.useNesterov=r,i.m=Re(i.momentum),i.accumulations={},i}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Bt.engine.registeredVariables[n];null==r.accumulations[n]&&qt(function(){e.accumulations[n]=je(i).variable(!1)});var o=r.accumulations[n],a=t[n];qt(function(){var t,r=e.m.mul(o).add(a);t=e.useNesterov?e.c.mul(a.add(r.mul(e.m))).add(i):e.c.mul(r).add(i),e.accumulations[n].assign(r),i.assign(t)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){if(t.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var e in this.accumulations)this.accumulations[e].dispose()},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="MomentumOptimizer",e}(Kc);Lc($c);var Xc=function(t){function e(e,n,r,i,o){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===i&&(i=null),void 0===o&&(o=!1);var a=t.call(this)||this;return a.learningRate=e,a.decay=n,a.momentum=r,a.epsilon=i,a.accumulatedMeanSquares={},a.accumulatedMeanGrads={},a.accumulatedMoments={},a.c=Gt(Re(e)),a.decayScalar=Gt(Re(n)),a.momentumScalar=Gt(Re(r)),a.oneMinusDecay=Gt(Re(1-n)),a.centered=o,null===i&&(i=Bt.get("EPSILON")),a.epsilonScalar=Gt(Re(i)),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Bt.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&qt(function(){e.accumulatedMeanSquares[n]=je(i).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&qt(function(){e.accumulatedMeanGrads[n]=je(i).variable(!1)}),null==r.accumulatedMoments[n]&&qt(function(){e.accumulatedMoments[n]=je(i).variable(!1)});var o=r.accumulatedMeanSquares[n],a=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=t[n];qt(function(){var t=e.decayScalar.mul(o).add(e.oneMinusDecay.mul(u.square()));if(e.centered){var r=e.decayScalar.mul(a).add(e.oneMinusDecay.mul(u)),l=e.momentumScalar.mul(s).add(e.c.mul(u).div(t.sub(r.square().add(e.epsilonScalar)).sqrt()));e.accumulatedMeanSquares[n].assign(t),e.accumulatedMeanGrads[n].assign(r),e.accumulatedMoments[n].assign(l);var c=i.sub(l);i.assign(c)}else{var p=e.decayScalar.mul(o).add(e.oneMinusDecay.mul(u.square()));l=e.momentumScalar.mul(s).add(e.c.mul(u).div(p.add(e.epsilonScalar).sqrt())),e.accumulatedMeanSquares[n].assign(p),e.accumulatedMoments[n].assign(l),c=i.sub(l),i.assign(c)}})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=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(e){return t.accumulatedMeanSquares[e].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(e){return t.accumulatedMeanGrads[e].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(e){return t.accumulatedMoments[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSPropOptimizer",e}(Vc);Lc(Xc);var Yc=function(){function t(){}return t.sgd=function(t){return new Kc(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new $c(t,e,n)},t.rmsprop=function(t,e,n,r,i){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===i&&(i=!1),new Xc(t,e,n,r,i)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new Gc(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new jc(t,e,n)},t.adamax=function(t,e,n,r,i){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===i&&(i=0),new Hc(t,e,n,r,i)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new qc(t,e)},t}(),Jc={sgd:Yc.sgd,momentum:Yc.momentum,adadelta:Yc.adadelta,adagrad:Yc.adagrad,rmsprop:Yc.rmsprop,adamax:Yc.adamax,adam:Yc.adam},Zc=_t.setBackend,Qc=_t.getBackend,tp=_t.disposeVariables,ep=_t.memory;!function(t){at=t}(_l);var np=function(t,e){return(np=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function rp(t,e){function n(){this.constructor=t}np(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var ip,op=function(){return(op=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]e?1:0}(t,e)}function Op(t){if(null==t)return t;for(var e=[],n=0,r=t;n=0),Np(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every(function(t){return typeof t===e})}function Fp(t,e){Array.isArray(t)?(X.assert(t.length>0,function(){return e+" is unexpectedly an empty array."}),t.forEach(function(t,n){return Fp(t,"element "+(n+1)+" of "+e)})):X.assert(Number.isInteger(t)&&t>0,function(){return"Expected "+e+" to be a positive integer, but got "+function t(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return t(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}(t)+"."})}function zp(t,e){return qt(function(){return Ua(Zs(Iu(t,t),e,!0))})}var Pp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.getConfig=function(){return{}},e}(Fc.Serializable),Bp=function(t){function e(e){var n=t.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return rp(e,t),e.prototype.apply=function(t){var e=this;return qt(function(){var n=zp(t,e.axis),r=xa(n,0,e.maxValue);return Eu(t,gu(r,hu(mp(up()),n)))})},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(Pp);Fc.registerClass(Bp);var Up=function(t){function e(e){var n=t.call(this)||this;return n.defaultAxis=0,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return rp(e,t),e.prototype.apply=function(t){var e=this;return qt(function(){return gu(t,hu(mp(up()),zp(t,e.axis)))})},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(Pp);Fc.registerClass(Up);var Wp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.apply=function(t){return Vu(t)},e.className="NonNeg",e}(Pp);Fc.registerClass(Wp);var Vp=function(t){function e(e){var n=t.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=e.minValue?e.minValue:n.defaultMinValue,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.rate=null!=e.rate?e.rate:n.defaultRate,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return rp(e,t),e.prototype.apply=function(t){var e=this;return qt(function(){var n=zp(t,e.axis),r=hu(Eu(mp(e.rate),xa(n,e.minValue,e.maxValue)),Eu(mp(1-e.rate),n));return Eu(t,gu(r,hu(mp(up()),n)))})},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(Pp);Fc.registerClass(Vp);var jp={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function qp(t){return Tp(t)}function Gp(t,e){return void 0===e&&(e={}),Rp(t,Fc.SerializationMap.getMap().classNameMap,e,"constraint")}function Hp(t){return null==t?null:"string"==typeof t?Gp({className:t in jp?jp[t]:t,config:{}}):t instanceof Pp?t:Gp(t)}var Kp=Object.freeze({maxNorm:function(t){return new Bp(t)},unitNorm:function(t){return new Up(t)},nonNeg:function(){return new Wp},minMaxNorm:function(t){return new Vp(t)}}),$p=["channelsFirst","channelsLast"],Xp=["valid","same","causal"],Yp=["max","avg"],Jp=["sum","mul","concat","ave"],Zp=new Map;function Qp(t){Mp($p,"DataFormat",t)}function th(t){Mp(Xp,"PaddingMode",t)}var eh=[],nh="/";function rh(t,e){eh.push(t);try{var n=e();return eh.pop(),n}catch(t){throw eh.pop(),t}}function ih(t){if(!sh(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===eh.length?"":eh.join(nh)+nh)+t}function oh(t){if(!sh(t))throw new Error("Not a valid tensor name: '"+t+"'");Zp.has(t)||Zp.set(t,0);var e=Zp.get(t);if(Zp.set(t,Zp.get(t)+1),e>0){var n=t+"_"+e;return Zp.set(n,1),n}return t}var ah=new RegExp(/^[A-Za-z][-A-Za-z0-9\._\/]*$/);function sh(t){return!!t.match(ah)}function uh(t){return t===parseInt(t.toString(),10)}function lh(t,e,n){null==e&&(e=0),null==n&&(n=t.length);for(var r=1,i=e;i= 2 but got x shape = "+t.shape+" and y shape = "+e.shape);if(e.rank>=3&&(r=t.shape.slice(-1)[0])!==(a=e.shape.slice(-2)[0]))throw new bp("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+t.shape+" and y shape = "+e.shape);if(2===t.rank&&2===e.rank)return Cs(t,e);var n=t.shape.slice(),r=n.pop();t=t.reshape([-1,r]);var i=e.shape.slice(),o=i.pop(),a=i.pop(),s=i.concat([o]),u=Array.from({length:e.rank},function(t,n){return 0===n?e.rank-2:n<=e.rank-2?n-1:n});e=e.transpose(u).reshape([a,-1]);var l=n.concat(s);return Cs(t,e).reshape(l)}function Ch(t,e,n){return qt(function(){return e=Array.isArray(e)?De(e,"int32"):e.toInt(),Xu(t,e,n)})}function Eh(t){return Iu(t,t)}function Ih(t,e,n){return qt(function(){if(null==n&&(n="channelsLast"),Qp(n),1!==e.rank&&e.rank!==t.rank)throw new vp("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+t.rank);var r,i=e.shape;if(5===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1,1,1])):t.add(e.reshape([1,i[3],i[0],i[1],i[2]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,1,1,i[0]])):t.add(e.reshape([1].concat(i))));else if(4===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1,1])):t.add(e.reshape([1,i[2],i[0],i[1]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,1,i[0]])):t.add(e.reshape([1].concat(i))));else if(3===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1])):t.add(e.reshape([1,i[1],i[0]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,i[0]])):t.add(e.reshape([1].concat(i))));else{if(!(t.rank<3))throw new vp("Unsupported input rank by biasAdd: "+t.rank);r=t.add(e)}return r})}function kh(t,e,n,r){return qt(function(){if(null!=n&&!X.arraysEqual(t.shape,n))throw new bp("Non-default noise shape is not implemented yet: "+JSON.stringify(n));if(null!=r)throw new bp("seed is not implemented for dropout yet.");var i=Va(hu(Da(e),ea(t.shape,0,1,"float32")));return i=Eu(gu(mp(1),Du(mp(1),e)),i),Eu(t,i)})}function Ah(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Th=["fanIn","fanOut","fanAvg"],Rh=["normal","uniform"];var Dh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(Fc.Serializable),Oh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.apply=function(t,e){return Pe(t,e)},e.className="Zeros",e}(Dh);Fc.registerClass(Oh);var _h=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.apply=function(t,e){return ze(t,e)},e.className="Ones",e}(Dh);Fc.registerClass(_h);var Mh=function(t){function e(e){var n=t.call(this)||this;if("object"!=typeof e)throw new vp("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new vp("config must have value set but got "+e);return n.value=e.value,n}return rp(e,t),e.prototype.apply=function(t,e){var n=this;return qt(function(){return Eu(Re(n.value),ze(t,e))})},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(Dh);Fc.registerClass(Mh);var Lh=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=e.minval||n.DEFAULT_MINVAL,n.maxval=e.maxval||n.DEFAULT_MAXVAL,n.seed=e.seed,n}return rp(e,t),e.prototype.apply=function(t,e){return ea(t,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(Dh);Fc.registerClass(Lh);var Fh=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return rp(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new bp("randomNormal does not support dType "+e+".");return Nh(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="RandomNormal",e}(Dh);Fc.registerClass(Fh);var zh=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return rp(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new bp("truncatedNormal does not support dType "+e+".");return sa(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="TruncatedNormal",e}(Dh);Fc.registerClass(zh);var Ph=function(t){function e(e){var n=t.call(this)||this;return n.gain=null!=e.gain?Re(e.gain):mp(1),n}return rp(e,t),e.prototype.apply=function(t,e){var n=this;return qt(function(){if(2!==t.length||t[0]!==t[1])throw new vp("Identity matrix initializer can only be used for 2D square matrices.");return Eu(n.gain,Go(t[0]))})},e.prototype.getConfig=function(){return{gain:this.gain.dataSync()[0]}},e.className="Identity",e}(Dh);Fc.registerClass(Ph);var Bh=function(t){function e(e){var n=t.call(this)||this;if(e.scale<0)throw new vp("scale must be a positive float. Got: "+e.scale);return n.scale=null==e.scale?1:e.scale,n.mode=e.mode,function(t){Mp(Th,"FanMode",t)}(n.mode),n.distribution=e.distribution,function(t){Mp(Rh,"Distribution",t)}(n.distribution),n.seed=e.seed,n}return rp(e,t),e.prototype.apply=function(t,e){var n=function(t,e){var n,r;if(void 0===e&&(e="channelsLast"),Qp(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var i=lh(t,2);n=t[1]*i,r=t[0]*i}else"channelsLast"===e&&(i=lh(t,0,t.length-2),n=t[t.length-2]*i,r=t[t.length-1]*i);else{var o=lh(t);n=Math.sqrt(o),r=Math.sqrt(o)}return[n,r]}(t),r=n[0],i=n[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,r):"fanOut"===this.mode?o/=Math.max(1,i):o/=Math.max(1,(r+i)/2),"normal"===this.distribution){var a=Math.sqrt(o);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new bp(this.getClassName()+" does not support dType "+e+".");return sa(t,0,a,e,this.seed)}var s=Math.sqrt(3*o);return ea(t,-s,s,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(Dh);Fc.registerClass(Bh);var Uh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="GlorotUniform",e}(Bh);Fc.registerClass(Uh);var Wh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="GlorotNormal",e}(Bh);Fc.registerClass(Wh);var Vh=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="HeNormal",e}(Bh);Fc.registerClass(Vh);var jh=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="HeUniform",e}(Bh);Fc.registerClass(jh);var qh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="LeCunNormal",e}(Bh);Fc.registerClass(qh);var Gh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return rp(e,t),e.prototype.getClassName=function(){return Bh.className},e.className="LeCunNormal",e}(Bh);Fc.registerClass(Gh);var Hh=function(t){function e(e){var n=t.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==e.gain?n.DEFAULT_GAIN:e.gain,n.seed=e.seed,null!=n.seed)throw new bp("Random seed is not implemented for Orthogonal Initializer yet.");return n}return rp(e,t),e.prototype.apply=function(t,e){var n=this;return qt(function(){if(2!==t.length)throw new bp("The Orthogonal Initializer does not support non-2D shapes yet.");t[0]*t[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+t[0]*t[1]+") elements: Slowness may result.");var e=Nh(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32"),r=Sl.gramSchmidt(e);return t[0]>t[1]&&(r=r.transpose()),Eu(mp(n.gain),r)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(Dh);Fc.registerClass(Hh);var Kh={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function $h(t,e){return void 0===e&&(e={}),Rp(t,Fc.SerializationMap.getMap().classNameMap,e,"initializer")}function Xh(t){return Tp(t)}function Yh(t){if("string"==typeof t){var e=t in Kh?Kh[t]:t;if("GlorotNormal"===e)return new Wh;if("GlorotUniform"===e)return new Uh;if("HeNormal"===e)return new Vh;if("HeUniform"===e)return new jh;if("LeCunNormal"===e)return new qh;if("LeCunUniform"===e)return new Gh;var n={};return n.className=e,n.config={},$h(n)}return t instanceof Dh?t:$h(t)}var Jh=Object.freeze({zeros:function(){return new Oh},ones:function(){return new _h},constant:function(t){return new Mh(t)},randomUniform:function(t){return new Lh(t)},randomNormal:function(t){return new Fh(t)},truncatedNormal:function(t){return new zh(t)},identity:function(t){return new Ph(t)},varianceScaling:function(t){return new Bh(t)},glorotUniform:function(t){return new Uh(t)},glorotNormal:function(t){return new Wh(t)},heNormal:function(t){return new Vh(t)},heUniform:function(t){return new jh(t)},leCunNormal:function(t){return new qh(t)},leCunUniform:function(t){return new Gh(t)},orthogonal:function(t){return new Hh(t)}});function Zh(t){return Array.isArray(t)&&Array.isArray(t[0])}function Qh(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function tf(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new vp("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function ef(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new vp("Expected exactly 1 Shape; got "+t.length)}return t}function nf(t){for(var e=0,n=0,r=t;n1)throw new gp("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 gp("Layer "+this.name+" is not connected, no input to return.");return Cp(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new gp("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new gp("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return Cp(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),e.prototype.calculateLosses=function(){return this.losses.map(function(t){return t()})},Object.defineProperty(e.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this._trainableWeights.forEach(function(e){e.trainable=t}),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights:[]},set:function(t){this._trainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable_?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(t){this._nonTrainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},e.prototype.assertInputCompatibility=function(t){if(t=Ep(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=Ep(this.inputSpec);if(t.length!==e.length)throw new vp("Layer "+this.name+" expects "+e.length+" inputs, but it received "+t.length+" input tensors. Input received: "+t);for(var n=0;n=0?a[u]:a[a.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new vp("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+a+".")}}if(null!=i.shape)for(var p=0;p0&&Array.isArray(d[0])?d.map(function(r,i){return new lf(g,r,n,Ep(t),e,n.name,i)}):new lf(g,d,n,Ep(t),e,n.name),n.addInboundNode(t,m,null,null,f,d,e),n._refCount++,null!=n.activityRegularizer)throw new bp("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},e.prototype.warnOnIncompatibleInputShape=function(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(t)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=t[r]&&t[r]!==n&&(e=!0)}),e&&console.warn("The shape of the input tensor ("+JSON.stringify(t)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(e.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new gp("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var t=[],e=0,n=this.inboundNodes;et.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(e-this.batchStartMillis),this.batchDurationsMillis.length>=t.DECISION_BATCH_COUNT&&(n=this.batchDurationsMillis.reduce(function(t,e){return t+e})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=Math.round(t.THRESHOLD_MILLIS/n),this.autoYieldEveryBatches<1&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=X.now(),this.lastYieldBatchCount=this.batchCount,[3,4];case 2:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,Fl()]:[3,4];case 3:r.sent(),this.lastYieldBatchCount=this.batchCount,r.label=4;case 4:return[3,7];case 5:return"batch"!==this.yieldEvery?[3,7]:[4,Fl()];case 6:r.sent(),r.label=7;case 7:return[2]}})})},t.prototype.maybeYieldOnEpoch=function(){return ap(this,void 0,void 0,function(){return sp(this,function(t){switch(t.label){case 0:return"epoch"!==this.yieldEvery?[3,2]:[4,Fl()];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.SKIP_FIRST_BATCHES=1,t.DECISION_BATCH_COUNT=2,t.THRESHOLD_MILLIS=16,t}(),Nf=function(t){function e(e){var n=t.call(this)||this;return n.yieldEvery=e||"auto",n}return rp(e,t),e.prototype.onTrainBegin=function(t){return ap(this,void 0,void 0,function(){return sp(this,function(t){return this.autoYielder=new xf(this.yieldEvery),[2]})})},e.prototype.onEpochBegin=function(t){return ap(this,void 0,void 0,function(){return sp(this,function(t){return this.seen=0,this.totals={},[2]})})},e.prototype.onBatchEnd=function(t,e){return ap(this,void 0,void 0,function(){var t,n,r,i,o=this;return sp(this,function(a){switch(a.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(e)];case 1:for(i in a.sent(),null==e&&(e={}),t=null==e.size?0:e.size,this.seen+=t,n=function(n){var i=e[n];if("number"==typeof i)r.totals.hasOwnProperty(n)||(r.totals[n]=0),r.totals[n]=r.totals[n]+i*t;else{var a=void 0;n in r.totals?a=r.totals[n]:r.totals[n]=mp(0),r.totals[n]=qt(function(){return hu(o.totals[n],Eu(i,mp(t)))}),null!=a&&a.dispose()}},r=this,e)n(i);return[2]}})})},e.prototype.onEpochEnd=function(t,e){return ap(this,void 0,void 0,function(){var t,n,r,i,o,a=this;return sp(this,function(s){switch(s.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(s.sent(),null!=e)for(t=function(t){if(null==n.totals[t])return"continue";"number"==typeof n.totals[t]?e[t]=n.totals[t]/n.seen:qt(function(){e[t]=Eu(gu(mp(1),mp(a.seen)),a.totals[t]),a.totals[t].dispose(),Gt(e[t])})},n=this,r=0,i=this.params.metrics;r=0&&Number.isInteger(e),function(){return"Verbosity level is expected to be an integer >= 0, but got "+e}),t.checkForDuplicate(n),null==t.constructors[e]&&(t.constructors[e]=[]),t.constructors[e].push(n)},t.checkForDuplicate=function(e){for(var n in t.constructors)t.constructors[+n].forEach(function(t){if(t===e)throw new vp("Duplicate callback constructor.")})},t.clear=function(){t.constructors={}},t.createCallbacks=function(e){var n=[];for(var r in t.constructors){var i=+r;e>=i&&n.push.apply(n,t.constructors[i])}return n.map(function(t){return new t})},t.constructors={},t}();function kf(t,e,n,r,i,o,a,s,u,l){var c=new Sf,p=[new Nf(e)].concat(If.createCallbacks(n));null!=t&&p.push.apply(p,t),p.push(c);var h=new wf(p);return h.setParams({epochs:r,initialEpoch:i,samples:o,steps:a,batchSize:s,verbose:n,doValidation:u,metrics:l}),{callbackList:h,history:c}}function Af(t,e){return qt(function(){var n=Zs(Eh(t),e,!0),r=Eu(Re(up()),Ve(t)),i=Ua(bu(n,r));return gu(t,i)})}function Tf(t,e){return qt(function(){return Xs(Eh(Du(e,t)),-1)})}function Rf(t,e){return qt(function(){return Xs(fa(Du(e,t)),-1)})}function Df(t,e){return qt(function(){var n=Du(t,e),r=xa(fa(t),up(),Number.MAX_VALUE),i=fa(gu(n,r));return Eu(mp(100),Xs(i,-1))})}function Of(t,e){return qt(function(){var n=mp(1),r=xa(e,up(),Number.MAX_VALUE),i=Aa(hu(n,r)),o=xa(t,up(),Number.MAX_VALUE),a=Aa(hu(n,o));return Xs(Eh(Du(i,a)),-1)})}function _f(t,e){return qt(function(){var n=mp(0),r=mp(1),i=bu(n,Du(r,Eu(t,e)));return Xs(Eh(i),-1)})}function Mf(t,e){return qt(function(){var n=mp(0),r=mp(1),i=bu(n,Du(r,Eu(t,e)));return Xs(i,-1)})}function Lf(t,e){return qt(function(){var n=mp(0),r=mp(1),i=Zs(Eu(t,e),-1),o=$s(Eu(Du(r,t),e),-1);return bu(n,hu(r,Du(o,i)))})}function Ff(t,e){return qt(function(){var n=mp(Math.log(2)),r=Du(e,t),i=Du(hu(r,Ba(Eu(mp(-2),r))),n);return Xs(i,-1)})}function zf(t,e,n){return void 0===n&&(n=!1),qt(function(){if(n)e=Ce(e);else{var r=Zs(e,e.shape.length-1,!0);e=gu(e,r)}return e=xa(e,up(),1-up()),Da(Zs(Eu(t.toFloat(),Aa(e)),e.shape.length-1))})}function Pf(t,e){return qt(function(){var n=ka(function(t){var e=[lh(t.shape)];return t.reshape(e)}(t)).toInt(),r=(e=xa(e,up(),1-up())).shape;return zf(Ko(n,r[r.length-1]).reshape(r),e,!1)})}function Bf(t,e){return qt(function(){var n;return n=xa(e,up(),1-up()),n=Aa(gu(n,Du(mp(1),n))),Xs(function(t,e){if(!X.arraysEqual(t.shape,e.shape))throw new vp("logits and labels must have the same shape, but got shapes "+JSON.stringify(t.shape)+" and "+JSON.stringify(e.shape));return qt(function(){var n=e.relu(),r=e.abs().neg();return n.sub(e.mul(t)).add(r.exp().log1p())})}(t,n),-1)})}function Uf(t,e){return qt(function(){var n=xa(t,up(),1),r=xa(e,up(),1);return Zs(Eu(t,Aa(gu(n,r))),-1)})}function Wf(t,e){return qt(function(){var n=Aa(hu(mp(up()),e));return Xs(Du(e,Eu(t,n)),-1)})}function Vf(t,e){return qt(function(){var n=Af(t,-1),r=Af(e,-1),i=Eu(n,r);return Da(Zs(i,-1))})}function jf(t){var e={meanSquaredError:Tf,meanAbsoluteError:Rf,meanAbsolutePercentageError:Df,meanSquaredLogarithmicError:Of,squaredHinge:_f,hinge:Mf,categoricalHinge:Lf,logcosh:Ff,categoricalCrossentropy:zf,sparseCategoricalCrossentropy:Pf,binaryCrossentropy:Bf,kullbackLeiblerDivergence:Uf,poisson:Wf,cosineProximity:Vf};if("string"==typeof t){if(t in e)return e[t];var n="Unknown loss "+t;throw t.toLowerCase().includes("softmaxcrossentropy")&&(n="Unknown loss "+t+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new vp(n)}return t}function qf(t,e){return qt(function(){var n=Eu(mp(.5),Ve(e)),r=dh(nu(e,n),t.dtype);return Xs(tu(t,r),-1)})}function Gf(t,e){return qt(function(){return dh(tu(Gs(t,-1),Gs(e,-1)),"float32")})}function Hf(t,e){return qt(function(){var n=mp(1);return _u(t.equal(n),e.equal(n)).sum().cast("float32")})}function Kf(t,e){return qt(function(){var n=mp(0),r=Hf(t,e),i=function(t,e){return qt(function(){var n=mp(1),r=mp(0);return _u(t.equal(r),e.equal(n)).sum().cast("float32")})}(t,e),o=r.add(i);return zu(nu(o,n),r.div(o),n).cast("float32")})}function $f(t,e){return qt(function(){var n=mp(0),r=Hf(t,e),i=function(t,e){return qt(function(){var n=mp(1),r=mp(0);return _u(t.equal(n),e.equal(r)).sum().cast("float32")})}(t,e),o=r.add(i);return zu(nu(o,n),r.div(o),n).cast("float32")})}function Xf(t,e){return Bf(t,e)}function Yf(t,e){return t.rank===e.rank&&(t=t.squeeze([t.rank-1])),(e=e.argMax(-1)).dtype!==t.dtype&&(e=e.asType(t.dtype)),tu(t,e).asType("float32")}var Jf=Tf,Zf=Tf,Qf=Rf,td=Rf,ed=Df,nd=Df,rd=zf,id=Vf,od=Pf;function ad(t,e,n,r){void 0===r&&(r=console.log);var i,o=function(t){var e=!0,n=[],r=[];for(var i in t.nodesByDepth)n.push(t.nodesByDepth[i]);for(var o=0,a=n;o1||1===s.length&&s[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,s)}if(e)for(var u=0,l=t.layers;u0&&(r=r.slice(0,r.length-1)+" "),r=(r+=t[i]).slice(0,e[i]),r+=" ".repeat(e[i]-r.length);n(r)}function ud(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}sd([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function ld(t,e,n,r){var i;try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}for(var o=[],a=0,s=t.inboundNodes;a0&&-1===n.indexOf(u)))for(var l=0;l0,function(){return"Expected at least one fetch, got none"});var n=[],r={};if(1===t.length){var i=yd(t[0],e);n=i.sorted,r=i.recipientMap}else for(var o=new Set,a=0,s=t;ar.maxNumTensors&&(r.maxNumTensors=b),b0;){var c=u[u.length-1];if(n.has(c.name))u.pop();else{var p=l[l.length-1]===u.length-1;if(0===c.inputs.length||p)u.pop(),r.push(c),n.add(c.name),p&&l.pop();else{l.push(u.length-1);for(var h=0,f=c.inputs;h0&&Number.isInteger(n.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs}),X.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+n.batchesPerEpoch}),X.assert(null==n.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,R.label=1;case 1:return R.trys.push([1,,22,23]),i=null!=n.validationData,o=void 0,a=void 0,i&&(Sd(n.validationData)?X.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches}):(s=function(t){if(3===t.length)throw new bp("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(n.validationData),o=s.xs,a=s.ys)),u=t.makeTrainFunction(),l=t.getDedupedMetricsNames(),c=void 0,c=i?l.slice().concat(l.map(function(t){return"val_"+t})):l.slice(),p=Ef(n.callbacks),h=null==n.verbose?1:n.verbose,f=kf(p,n.yieldEvery,h,n.epochs,null,null,function(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}(e,n),null,i,c),d=f.callbackList,m=f.history,d.setModel(t),t.history=m,[4,d.onTrainBegin()];case 2:return R.sent(),t.stopTraining_=!1,g=null==n.initialEpoch?0:n.initialEpoch,[4,e.iterator()];case 3:y=R.sent(),R.label=4;case 4:return g=n.batchesPerEpoch:x.done)?i?(k=void 0,Sd(n.validationData)?(A=Ep,[4,t.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,13]):[3,15]:[3,16];case 12:return k=A.apply(void 0,[R.sent()]),[3,14];case 13:k=Ep(t.evaluate(o,a,{batchSize:null==n.validationBatchSize?bd:n.validationBatchSize,verbose:0})),R.label=14;case 14:for(T=0;T0&&Number.isInteger(t),function(){return"batchSize is required to be a positive integer, but got "+t})}function Ed(t,e,n){return null==t?[null]:Array.isArray(t)?t.map(function(t){return gh(t,e,n-e)}):gh(t,e,n-e)}function Id(t,e){return qt(function(){return null==t?null:Array.isArray(t)?t.map(function(t){return Id(t,e)}):Ch(t,"int32"===e.dtype?e:e.toInt())})}function kd(t,e){for(var n=[],r=0,i=null;r=t&&(i=t),n.push([r,i]),r=i;return n}function Ad(t,e,n,r){return void 0===r&&(r={}),ap(this,void 0,void 0,function(){var i,o,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N;return sp(this,function(S){switch(S.label){case 0:if(t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,S.label=1;case 1:if(S.trys.push([1,,3,4]),Cd(c=null==r.batchSize?32:r.batchSize),p=t.standardizeUserData(e,n,!1,c),i=p[0],o=p[1],h=!1,f=void 0,null!=r.validationData&&r.validationData.length>0){if(h=!0,2!==r.validationData.length)throw 3===r.validationData.length?new bp("validationData including sample weights is not supported yet."):new vp("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");a=r.validationData[0],s=r.validationData[1],d=t.standardizeUserData(a,s,!0,c),u=d[0],l=d[1],f=u.concat(l)}else null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(h=!0,m=Math.floor(i[0].shape[0]*(1-r.validationSplit)),g=i[0].shape[0],u=Ed(i,m,g),i=Ed(i,0,m),l=Ed(o,m,g),o=Ed(o,0,m),f=u.concat(l)):null!=r.validationSteps&&(h=!0);return y=i.concat(o),t.checkTrainableWeightsConsistency(),v=t.makeTrainFunction(),b=t.getDedupedMetricsNames(),w=void 0,x=void 0,h?(t.makeTestFunction(),w=t.testFunction,x=b.slice().concat(b.map(function(t){return"val_"+t}))):(w=null,f=[],x=b.slice()),N=Ef(r.callbacks),[4,function(t,e,n,r,i,o,a,s,u,l,c,p,h,f,d,m){return ap(this,void 0,void 0,function(){var g,y,v,b,w,x,N,S;return sp(this,function(C){switch(C.label){case 0:if(null==i&&(i=32),null==o&&(o=1),null==c&&(c=!0),null==h&&(h=0),g=!1,null!=u&&null!=l&&(g=!0),null!=d&&(g=!0,null==f))throw new vp("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(y=t.checkNumSamples(n,i,f,"steps_per_epoch"))&&(v=fh(0,y)),null==a&&(a=1),b=kf(s,m,a,o,h,y,f,i,g,p),w=b.callbackList,x=b.history,w.setModel(t),t.history=x,[4,w.onTrainBegin()];case 1:C.sent(),t.stopTraining_=!1,N=function(o){var a,s,p,h,d;return sp(this,function(m){switch(m.label){case 0:return[4,w.onEpochBegin(o)];case 1:if(m.sent(),a={},null==f)return[3,2];throw new bp("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new bp("batch shuffling is not implemneted yet");c&&X.shuffle(v),s=De(v),p=kd(y,i),h=function(o){var c;return sp(this,function(h){switch(h.label){case 0:return c={},[4,w.onBatchBegin(o,c)];case 1:return h.sent(),qt(function(){var h=p[o][0],f=p[o][1],d=gh(s,h,f-h);c.batch=o,c.size=f-h;for(var m=Id(n,d),y=e(m),v=0;v0)o=!0;else if(Od(t)){for(var a in t)if(t.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new vp("Error when checking model "+i+" expected no data, but got "+t)}return[]}if(null==t)return e.map(function(t){return null});var s;if(Od(t)){t=t,s=[];for(var u=0,l=e;u1)throw new vp("The model "+i+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);s=[t]}if(s=Td(s),null!=n)for(var p=0;p=0&&d!==m)throw new vp("Error when checking "+i+": expected "+e[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function Md(t,e,n,r,i){var o;if(void 0===r&&(r=!0),void 0===i&&(i=""),Array.isArray(t)){if(t.length!==e.length)throw new vp("Error when checking model "+i+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+e.length+" Tensor(s), but instead got "+t.length+" Tensors(s).");o=t}else{if(e.length>1)throw new vp("The model expects "+e.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(t.shape)+".");o=[t]}if(null!=n)for(var a=0;a1&&(e.metricsTensors.push([n,t]),e.metricsNames.push(e.outputNames[t]+"_loss"))}});var f=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map(function(t){return[]});if(Array.isArray(t))return e.map(function(e){return t});if(null!=t){for(var n=[],r=0,i=e;r1&&(n=e.outputNames[t]+"_"+n),e.metricsNames.push(n),e.metricsTensors.push([r,t])}(t,r,l)},s=0,u=f[t];s0)throw new bp("Verbose mode is not implemented yet.");return X.assert(!r||n.batches>0&&Number.isInteger(n.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),function(t){return"function"==typeof t.next}(e)?(s=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:s=f.sent(),f.label=3;case 3:a=s,u=0,l=0,c=function(){var e,s,c,p,h,f;return sp(this,function(d){switch(d.label){case 0:return[4,a.next()];case 1:if((e=d.sent()).value){if(s=wd(t,e.value),c=qt(function(){return i(s)}),Ht(s),0===l)for(f=0;f0&&Ht(n)},f=0;f0){var c=[];throw e.forEach(function(e,n){null==e&&c.push(t[n])}),new vp("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return e},e.prototype.predictLoop=function(t,e,n){var r=this;return void 0===e&&(e=32),void 0===n&&(n=!1),qt(function(){var i=r.checkNumSamples(t);if(n)throw new bp("Verbose predictLoop() is not implemented yet.");for(var o=kd(i,e),a=r.outputs.map(function(t){return[]}),s=function(e){qt(function(){var n=o[e][0],i=o[e][1],a=Ed(t,n,i),s=[];if(Array.isArray(a))for(var u=0;u1)throw new vp("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(t){return t.shape})));if(i.length>1)throw new vp("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(r.length>0&&i.length>0&&!X.arraysEqual(r,i))throw new vp("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+i[0]+" target sample(s).")}(t=_d(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=_d(e,this.feedOutputNames,i,!1,"target")),function(t,e,n){for(var r=[Tf,Bf,zf],i=0;i0&&t[0].shape[0]%r!=0)throw new vp("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+t[0].shape[0]+" sample(s).");return[t,e,null]},e.prototype.testLoop=function(t,e,n,r,i){var o=this;return void 0===r&&(r=0),qt(function(){var a=o.checkNumSamples(e,n,i,"steps"),s=[];if(r>0)throw new bp("Verbose mode is not implemented yet.");if(null!=i)throw new bp("steps mode in testLoop() is not implemented yet");for(var u=kd(a,n),l=De(fh(0,a)),c=0;c1&&(i+="_"+Sp(t.slice(0,n),r)),e.push(i)}return e},e.prototype.makeTrainFunction=function(){var t=this;return function(e){var n=e.slice(0,t.inputs.length),r=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),i=[],o=t.collectedTrainableWeights.map(function(t){return t.read()});return[t.optimizer.minimize(function(){for(var e=[],o=0;o1)throw new vp("Found more than one ("+n.length+") save handlers for URL '"+t+"'");t=n[0]}if(null==t.save)throw new vp("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,Ac.encodeWeights(this.getNamedWeights(e))];case 1:return r=s.sent(),i=!1,o=null,a=this.toJSON(o,i),[2,t.save({modelTopology:a,weightData:r.data,weightSpecs:r.specs,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v1.0.0",convertedBy:null})]}})})},e.className="Model",e}(function(t){function e(n){var r=t.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var i=r.getClassName().toLowerCase();r.name=hp(i)}if(r.supportsMasking=!1,r.trainable_=!0,r.updatable=!0,Array.isArray(n.inputs)?r.inputs=n.inputs.slice():r.inputs=[n.inputs],Array.isArray(n.outputs)?r.outputs=n.outputs.slice():r.outputs=[n.outputs],Op(r.inputs).length!==r.inputs.length)throw new vp("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(t){return t.name}));Op(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map(function(t){return t.name})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[];for(var o=0,a=r.outputs;o1 nodes"),Np(0===l,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(l);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var h=0;h=0;)i.splice(i.indexOf(u),1);w.push(u)}},N=[],S=[],C=0,E=r.outputs;Cr?1:0});for(var V=0,j=W;V0)throw new vp("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 t=[],e=0,n=this.layers;e0)throw new vp(p.length+" of "+r+" weights are not set: "+p)}sf(l)},e.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 1.0.0",e.backend="TensorFlow.js",e},e.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=function t(e,n){if(null===e||void 0===e)return null;if("string"==typeof e)return Ip(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var r=[],i=e.length,o=0;o1)for(var s=0,u=a;s0){for(var f=[],d=0;d0&&t.apply(Cp(r),n)}function u(t){var n=t.name,o=cd(t,null!=e.customObjects?e.customObjects:{});o.setFastWeightInitDuringBuild(r),i[n]=o;for(var s=0,u=t.inboundNodes;s1)throw new vp("Found more than one ("+n.length+") load handlers for URL '"+t+"'");t=n[0]}return[2,function(t,e,n){return ap(this,void 0,void 0,function(){var r,i,o,a,s,u;return sp(this,function(l){switch(l.label){case 0:if(null==n&&(n={}),null==t.load)throw new vp("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,t.load()];case 1:if(r=l.sent(),null!=(i=r.modelTopology).model_config&&(i=i.model_config),o=null==n.strict||n.strict,a=null!=r.weightData&&null!=r.weightSpecs&&o,s=cd(hd(i),e,a),null!=r.weightData){if(null==r.weightSpecs)throw new vp("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");u=Ac.decodeWeights(r.weightData,r.weightSpecs),s.loadWeights(u,o),Ht(u)}return[2,s]}})})}(t,void 0,e)]})})}Fc.registerClass(Ld);var zd=function(t){function e(e){var n=t.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},n.trainable=!0,n._updatable=!0,n.built=!1,n.name=null!=e.name?e.name:hp("sequential_"),null!=e.layers)for(var r=0,i=e.layers;r0)&&(n=e.sourceLayer,r=e.nodeIndex),0===n.inboundNodes.length)return[e];var i=n.inboundNodes[r];if(0===i.inboundLayers.length)return i.inputTensors;for(var o=[],a=0;a 0 but got "+JSON.stringify(t.filters))},e}(gm),vm=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return rp(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!Lp(t.kernelSize,"number",1,2))throw new vp("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(ym);Fc.registerClass(vm);var bm=function(t){function e(e){var n=t.call(this,e)||this;if(n.inputSpec=[new uf({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new vp("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return rp(e,t),e.prototype.build=function(t){var e;if(4!==(t=ef(t)).length)throw new vp("Input should have rank 4; Received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new vp("The channel dimension of the inputs should be defined. Found `None`.");var r=t[n],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"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 uf({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return qt(function(){var e=tf(t);if(4!==e.shape.length)throw new vp("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+e.shape.length);var r,i,o=e.shape,a=o[0];"channelsFirst"===n.dataFormat?(r=2,i=3):(r=1,i=2);var s=o[r],u=o[i],l=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],f=[a,dm(s,p,l,n.padding),dm(u,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(e=qu(e,[0,2,3,1]));var d=Ss(e,n.kernel.read(),f,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(d=qu(d,[0,3,1,2])),null!=n.bias&&(d=Ih(d,n.bias.read(),n.dataFormat)),null!=n.activation&&(d=n.activation.apply(d)),d})},e.prototype.computeOutputShape=function(t){var e,n,r,i=(t=ef(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var o=this.kernelSize[0],a=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return i[e]=this.filters,i[n]=dm(i[n],s,o,this.padding),i[r]=dm(i[r],u,a,this.padding),i},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(vm);Fc.registerClass(bm);var wm=function(t){function e(e){return t.call(this,2,e)||this}return rp(e,t),e.className="SeparableConv2D",e}(function(t){function e(e,n){var r=t.call(this,e,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new vp("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new vp("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new vp("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=Yh(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=om(n.depthwiseRegularizer),r.depthwiseConstraint=Hp(n.depthwiseConstraint),r.pointwiseInitializer=Yh(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=om(n.pointwiseRegularizer),r.pointwiseConstraint=Hp(n.pointwiseConstraint),r}return rp(e,t),e.prototype.build=function(t){var e;if((t=ef(t)).length1)throw new vp("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(t)+".");for(var i=null==t[0]?null:t[0].slice(1),o=1;o1){var y=fh(1,s).concat([0]);e.push(qu(h,y)),l=!0}else e.push(h)}var v=n.mergeFunction(e),b=v.rank;if(l)if(null==b){var w=v.shape;m=[d=w[w.length-1]].concat(w.slice(0,w.length-1)),v=qu(v.reshape([-1,d]),[1,0]).reshape(m)}else b>1&&(y=[b-1].concat(fh(0,b-1)),v=qu(v,y));return v}return n.mergeFunction(t)})},e.prototype.computeOutputShape=function(t){var e;e=null==(t=t)[0]?null:t[0].slice(1);for(var n=1;n1)throw new vp("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}},e.prototype.mergeFunction=function(t){var e=this;return qt(function(){return bh(t,e.axis)})},e.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new vp("A `Concatenate` layer should be called on a list of inputs.");for(var e=t,n=e[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,o=e.slice(1);i3||n.length>3)throw new bp("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);if(e[r[0]]!==n[r[1]])throw new vp("Dimension incompatibility: "+e[r[0]]+" !== "+n[r[1]])},e.prototype.mergeFunction=function(t){if(2!==t.length)throw new vp("A `Dot` layer must be called on exactly 2 inputs, but received "+t.length+" input(s).");var e,n=t[0],r=t[1];return e=Array.isArray(this.axes)?this.axes.map(function(e,n){return Um(e,t[n].shape.length)}):[Um(this.axes,n.shape.length),Um(this.axes,r.shape.length)],this.normalize&&(n=Af(n,e[0]),r=Af(r,e[1])),function(t,e,n){if(t.shape.length>3||e.shape.length>3)throw new bp("batchDot is not implemented for tensors of 4D or higher rank yet");if(X.assert(t.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+t.shape.length}),X.assert(t.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+e.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===t.dtype||"complex64"===e.dtype)throw new bp("batchDot is not implemented for complex64-type Tensors yet.");var r=t.shape.length,i=e.shape.length;null==n&&(n=[r-1,i-2]);var o=n;return qt(function(){var n,a;if(r>i){n=r-i;for(var s=[],u=0;ur){for(n=i-r,s=[],u=0;u0){var p,h=[];for(u=p=r>i?r+i-3:r-1;u3||n.length>3)throw new bp("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);e.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var i=e.concat(n);return 1===i.length&&i.push(1),i},e.prototype.computeMask=function(t,e){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dot",e}(_m);function Vm(t,e,n,r,i,o){var a;if(void 0===o&&(o=.001),2===t.rank)a=ns(t,e,n,r,i,o);else if(3===t.rank)a=rs(t,e,n,r,i,o);else{if(4!==t.rank)throw new bp("batchNormalization is not implemented for array of rank "+t.rank+" yet");a=is(t,e,n,r,i,o)}return a}function jm(t,e,n,r,i){return void 0===i&&(i=.001),X.arraysEqual(r.slice().sort(),fh(0,t.rank-1))?function(t,e,n,r,i){return void 0===i&&(i=.001),qt(function(){var o=Js(t,r),a=o.mean,s=o.variance;return[Vm(t,a,s,n,e,i),a,s]})}(t,e,n,r,i):function(t,e,n,r,i){return void 0===i&&(i=.001),qt(function(){for(var o=Js(t,r),a=o.mean,s=o.variance,u=[],l=0,c=fh(0,t.rank);l=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new vp("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new uf({ndim:t.length,axes:(e={},e[n]=r,e)})];var i=[r];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0},e.prototype.call=function(t,e){var n=this;return qt(function(){var r=null!=e.training&&e.training,i=tf(t),o=i.shape,a=o.length,s=fh(0,a),u=n.axis>=0?n.axis:n.axis+a;s.splice(u,1);var l=xp(1,a);l[u]=o[u];var c=s.slice();c.sort();var p=!X.arraysEqual(c,fh(0,a).slice(0,a-1));if(!r)return function(){if(p){var t=n.movingMean.read().reshape(l),e=n.movingVariance.read().reshape(l),r=n.center?n.beta.read().reshape(l):null,o=n.scale?n.gamma.read().reshape(l):null;return Vm(i,t,e,r,o,n.epsilon)}return Vm(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=jm(i,n.gamma.read(),n.beta.read(),s,n.epsilon),f=h[0],d=h[1],m=h[2],g=function(t,e,n){qt(function(){var r=mp(1).sub(mp(n)),i=t.read(),o=i.sub(e).mul(r);t.write(i.sub(o))})};return g(n.movingMean,d,n.momentum),g(n.movingVariance,m,n.momentum),f})},e.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Xh(this.betaInitializer),gammaInitializer:Xh(this.gammaInitializer),movingMeanInitializer:Xh(this.movingMeanInitializer),movingVarianceInitializer:Xh(this.movingVarianceInitializer),betaRegularizer:rm(this.betaRegularizer),gammaRegularizer:rm(this.gammaRegularizer),betaConstraint:qp(this.betaConstraint),gammaConstraint:qp(this.gammaConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="BatchNormalization",e}(ff);Fc.registerClass(qm);var Gm=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)n.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new vp("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+e.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof e.padding[0])r=[e.padding[0],e.padding[0]],i=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new vp("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+e.padding[0].length+" array.");if(r=e.padding[0],2!==e.padding[1].length)throw new vp("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+e.padding[1].length+" array.");i=e.padding[1]}n.padding=[r,i]}return n.inputSpec=[new uf({ndim:4})],n}return rp(e,t),e.prototype.computeOutputShape=function(t){var e,n;return t=ef(t),"channelsFirst"===this.dataFormat?(e=null!=t[2]&&t[2]>=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])},e.prototype.call=function(t,e){var n=this;return qt(function(){return function(t,e,n){return qt(function(){if(4!==t.rank)throw new vp("temporalPadding expects input tensor to be 4-D, but received a "+t.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new vp("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new vp("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],$o(t,r)})}(tf(t),n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ZeroPadding2D",e}(ff);function Hm(t,e,n,r,i,o){return qt(function(){var a;Qp(i),function(t){Mp(Yp,"PoolMode",t)}(o),th(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==i&&(i="channelsLast"),null==o&&(o="max"),t=mm(t,i);var s="same"===r?"same":"valid";return a="max"===o?Ms(t,e,n,s):Ls(t,e,n,s),"channelsFirst"===i&&(a=qu(a,[0,3,1,2])),a})}Fc.registerClass(Gm);var Km=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=2),n=t.call(this,e)||this,"number"==typeof e.poolSize)n.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new vp("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));n.poolSize=e.poolSize}if(Fp(n.poolSize,"poolSize"),null==e.strides)n.strides=n.poolSize;else if("number"==typeof e.strides)n.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new vp("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));n.strides=e.strides}return Fp(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,th(n.padding),n.inputSpec=[new uf({ndim:3})],n}return rp(e,t),e.prototype.computeOutputShape=function(t){var e=fm((t=ef(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},e.prototype.call=function(t,e){var n=this;return qt(function(){n.invokeCallHook(t,e),t=mh(tf(t),2);var r=n.poolingFunction(tf(t),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return ia(r,[2])})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ff),$m=function(t){function e(e){return t.call(this,e)||this}return rp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return Qp(i),th(r),Hm(t,e,n,r,i,"max")},e.className="MaxPooling1D",e}(Km);Fc.registerClass($m);var Xm=function(t){function e(e){return t.call(this,e)||this}return rp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return Qp(i),th(r),Hm(t,e,n,r,i,"avg")},e.className="AveragePooling1D",e}(Km);Fc.registerClass(Xm);var Ym=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new vp("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides];return Fp(n.poolSize,"poolSize"),Fp(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Qp(n.dataFormat),th(n.padding),n.inputSpec=[new uf({ndim:4})],n}return rp(e,t),e.prototype.computeOutputShape=function(t){t=ef(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=fm(e,this.poolSize[0],this.padding,this.strides[0]),n=fm(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return qt(function(){return n.invokeCallHook(t,e),n.poolingFunction(tf(t),n.poolSize,n.strides,n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ff),Jm=function(t){function e(e){return t.call(this,e)||this}return rp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return Qp(i),th(r),Hm(t,e,n,r,i,"max")},e.className="MaxPooling2D",e}(Ym);Fc.registerClass(Jm);var Zm=function(t){function e(e){return t.call(this,e)||this}return rp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return Qp(i),th(r),Hm(t,e,n,r,i,"avg")},e.className="AveragePooling2D",e}(Ym);Fc.registerClass(Zm);var Qm=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new uf({ndim:3})],n}return rp(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new bp},e}(ff),tg=function(t){function e(e){return t.call(this,e||{})||this}return rp(e,t),e.prototype.call=function(t,e){return qt(function(){var e=tf(t);return Xs(e,1)})},e.className="GlobalAveragePooling1D",e}(Qm);Fc.registerClass(tg);var eg=function(t){function e(e){return t.call(this,e||{})||this}return rp(e,t),e.prototype.call=function(t,e){return qt(function(){var e=tf(t);return $s(e,1)})},e.className="GlobalMaxPooling1D",e}(Qm);Fc.registerClass(eg);var ng=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Qp(n.dataFormat),n.inputSpec=[new uf({ndim:4})],n}return rp(e,t),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(t,e){throw new bp},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ff),rg=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.call=function(t,e){var n=this;return qt(function(){var e=tf(t);return"channelsLast"===n.dataFormat?Xs(e,[1,2]):Xs(e,[2,3])})},e.className="GlobalAveragePooling2D",e}(ng);Fc.registerClass(rg);var ig=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e.prototype.call=function(t,e){var n=this;return qt(function(){var e=tf(t);return"channelsLast"===n.dataFormat?$s(e,[1,2]):$s(e,[2,3])})},e.className="GlobalMaxPooling2D",e}(ng);function og(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new vp("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=t.slice(t.length-r,t.length),t=t.slice(0,t.length-r)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function i(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=i(e),constants:n=i(n)}}function ag(t,e,n,r,i,o,a,s){return void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===s&&(s=!1),qt(function(){var u=e.shape.length;if(u<3)throw new vp("Input should be at least 3D, but is "+u+"D.");var l=[1,0].concat(fh(2,u));if(e=qu(e,l),null!=o)throw new bp("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=i&&((i=i.asType("bool").asType("float32")).rank===u-1&&(i=qo(i,-1)),i=qu(i,l)),r&&(e=ks(e,0),null!=i&&(i=ks(i,0)));var c,p,h=[],f=n,d=e.shape[0],m=ua(e);null!=i&&(p=ua(i));for(var g,y=function(e){var n=m[e],r=qt(function(){return t(n,f)});if(null==i)c=r[0],f=r[1];else{var o=qt(function(){var t=p[e],n=Ve(t).sub(t);return{output:r[0].mul(t).addStrict(f[0].mul(n)),newStates:f.map(function(e,i){return r[1][i].mul(t).addStrict(e.mul(n))})}});c=o.output,f=o.newStates}s&&h.push(c)},v=0;v1?xh(n,[1,t]):n}):e.cell.stateSize>1?[xh(n,[1,e.cell.stateSize])]:[n]})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);var n=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:n};var r=t.prototype.getConfig.call(this);return Object.assign(e,r),e},e.className="RNN",e}(ff);Fc.registerClass(sg);var ug=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return rp(e,t),e}(ff),lg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,Fp(n.units,"units"),n.activation=Qd(null==e.activation?n.DEFAULT_ACTIVATION:e.activation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=Yh(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Yh(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Yh(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=om(e.kernelRegularizer),n.recurrentRegularizer=om(e.recurrentRegularizer),n.biasRegularizer=om(e.biasRegularizer),n.kernelConstraint=Hp(e.kernelConstraint),n.recurrentConstraint=Hp(e.recurrentConstraint),n.biasConstraint=Hp(e.biasConstraint),n.dropout=ph([1,hh([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=ph([1,hh([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return rp(e,t),e.prototype.build=function(t){t=ef(t),this.kernel=this.addWeight("kernel",[t[t.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},e.prototype.call=function(t,e){var n=this;return qt(function(){if(2!==(t=t).length)throw new vp("SimpleRNNCell expects 2 input Tensors, got "+t.length+".");var r=t[1];t=t[0];var i,o=null!=e.training&&e.training;01){for(var o=[],a=0;a= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var n=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),t.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(t){var e=[(t=ef(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},e.prototype.call=function(t,e){var n=this;return qt(function(){return ag(function(t,r){return[tf(n.layer.call(t,e)),[]]},t=tf(t),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(yg);Fc.registerClass(vg);var bg="concat",wg=function(t){function e(e){var n=t.call(this,e)||this,r=e.layer.getConfig(),i={};i.className=e.layer.getClassName(),i.config=r,n.forwardLayer=cd(i),r.goBackwards=!0!==r.goBackwards;var o={};if(o.className=e.layer.getClassName(),o.config=r,n.backwardLayer=cd(o),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===e.mergeMode?bg:e.mergeMode,function(t){Mp(Jp,"BidirectionalMergeMode",t)}(n.mergeMode),e.weights)throw new bp("weights support is not implemented for Bidirectional layer yet.");return n._stateful=e.layer.stateful,n.returnSequences=e.layer.returnSequences,n.returnState=e.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=e.layer.inputSpec,n.numConstants=null,n}return rp(e,t),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(t){var e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))},e.prototype.computeOutputShape=function(t){var e,n,r,i=this.forwardLayer.computeOutputShape(t);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),e=i[0]):e=i[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[e].concat(r).concat(r.slice()):Cp(n)},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var o=og(e,r,i,this.numConstants);if(e=o.inputs,r=o.initialState,i=o.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==i)return t.prototype.apply.call(this,e,n);var a=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new vp("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,a.push.apply(a,r);var l=r.map(function(t){return new uf({shape:t.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=i)throw new bp("Support for constants in Bidirectional layers is not implemented yet.");for(var c=a[0]instanceof lf,p=0,h=a;p0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map(function(t){return e.read(t)})},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach(function(t,r){return n.write(t,e[r])})},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n=this.maxSize)throw new Error("Max index must be < array size ("+n+" vs. "+this.maxSize+")");this.writeMany(t,ua(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,i=t.map(function(t){return r+=t});if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var o=0===r?0:e.size/r,a=[];qt(function(){e=e.reshape([1,r,o]);for(var s=0;s1)for(var y=1;y1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.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 t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}(),Ay=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=t.placeholders,this._outputs=t.outputs,this.compile()}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map(function(e){return t[e].map(function(t){return t.id})});this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.placeholders.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.outputs.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isControlFlowModel",{get:function(){return this.graph.withControlFlow},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDynamicShapeModel",{get:function(){return this.graph.withDynamicShape},enumerable:!0,configurable:!0}),t.prototype.compile=function(t){if(!this.graph.withControlFlow&&!this.graph.withDynamicShape){var e=[],n=t||this.graph.placeholders,r=n.map(function(t){return t.name}).sort().join(this.SEPERATOR);if(!this.compiledMap.get(r)){for(var i=n.concat(this.graph.weights),o={};i.length>0;){var a=i.pop();o[a.name]=!0,e.push(a),a.children.forEach(function(t){!o[t.name]&&t.inputNames.every(function(t){var e=Vg(t)[0];return o[e]})&&i.push(t)})}this.compiledMap.set(r,e)}}},t.prototype.execute=function(t,e,n){var r=this;void 0===e&&(e=!0);var i=Object.keys(t).sort();this.checkInput(t,e),this.checkInputShapeAndType(t,e),this.compile(i.map(function(t){return r.graph.nodes[t]}));var o=this.calculateOutputs(n);this.checkOutput(this.compiledMap.get(i.join(this.SEPERATOR)),o);var a={};return qt(function(){for(var e=new ky(r._weightMap,a),n=zg({},r.weightMap,t),s=r.getFrozenTensorIds(n),u={},l=r.compiledMap.get(i.join(r.SEPERATOR)),c=0;c0?(c=this.processStack(i,o,e,a,l,u,n,s),[4,Promise.all(c)]):[3,3];case 2:return h.sent(),[3,1];case 3:return[2,a]}})})},t.prototype.processStack=function(t,e,n,r,i,o,a,s){for(var u=this,l=[],c=function(){var c=e.pop();n.currentContext=c.contexts;var h="";if("Enter"===c.node.op&&Ug("isConstant",c.node,r,n)&&(h=Vg(c.node.name,n)[0]),-1===t.indexOf(c.node)){var f=Iy(c.node,r,n);h||(h=Vg(c.node.name,n)[0]);var d=n.currentContext;f instanceof Promise?l.push(f.then(function(t){return r[h]=t,n.currentContext=d,u.checkTensorForDisposal(h,c.node,r,n,o,a,s),u.processChildNodes(c.node,e,n,r,i),t})):(r[h]=f,p.checkTensorForDisposal(h,c.node,r,n,o,a,s),p.processChildNodes(c.node,e,n,r,i))}else p.processChildNodes(c.node,e,n,r,i)},p=this;e.length>0;)c();return l},t.prototype.processChildNodes=function(t,e,n,r,i){t.children.forEach(function(t){var o=Vg(t.name,n)[0];i[o]||("Merge"===t.op?t.inputNames.some(function(t){return!!Wg(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every(function(t){return!!Wg(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})))})},t.prototype.calculateOutputs=function(t){return!t||t instanceof Array||(t=[t]),t||this.graph.outputs.map(function(t){return t.name})},t.prototype.findOutputs=function(t,e,n){return this.calculateOutputs(n).reduce(function(n,r){return n[r]=Wg(r,t,e),n},{})},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(t){return t.dispose()})})},t.prototype.checkInputShapeAndType=function(t,e){void 0===e&&(e=!0),this.placeholders.forEach(function(n){var r=t[n.name];if(e||r){var i=r[0];if(n.attrParams.shape&&n.attrParams.shape.value){var o=n.attrParams.shape.value,a=o.length===i.shape.length&&i.shape.every(function(t,e){return-1===o[e]||o[e]===t});X.assert(a,function(){return"The shape of dict['"+n.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+i.shape+"]"})}n.attrParams.dtype&&n.attrParams.dtype.value&&X.assert(i.dtype===n.attrParams.dtype.value,function(){return"The dtype of dict['"+n.name+"'] provided in model.execute(dict) must be "+n.attrParams.dtype.value+", but was "+i.dtype})}})},t.prototype.checkInput=function(t,e){var n=this;void 0===e&&(e=!0);var r=Object.keys(t),i=[],o=[];this.inputNodes.forEach(function(t){-1===r.indexOf(t)&&i.push(t)}),r.forEach(function(t){-1===n.inputNodes.indexOf(t)&&o.push(t)});var a=o.filter(function(t){return!n.graph.nodes[t]});if(i.length>0&&e)throw new Error("The dict provided in model.execute(dict) has the keys ["+r+"], but is missing the required keys: ["+i+"].");if(o.length>0&&e)throw new Error("The dict provided in model.execute(dict) has unused keys: ["+o+"]. Please provide only the following keys: ["+this.inputNodes+"].");if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] not part of model graph.")},t.prototype.checkOutput=function(t,e){var n=t.map(function(t){return t.name}),r=[];if(e.forEach(function(t){var e=qg(t)[0];-1===n.indexOf(e)&&r.push(e)}),r.length>0)throw new Error("The following outputs are not generated by the execution: ["+r+"].")},t}(),Ty="?tfjs-format=file",Ry="model.json",Dy=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=Ac.browserHTTPRequest(t,this.loadOptions);else{var e=Ac.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(Ac.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return Pg(this,void 0,void 0,function(){var t,e,n;return Bg(this,function(r){switch(r.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=r.sent(),e=t.modelTopology,this.version=e.versions.producer+"."+e.versions.minConsumer,n=Ac.decodeWeights(t.weightData,t.weightSpecs),this.executor=new Ay(cy.Instance.transformGraph(e)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),[2,!0]}})})},t.prototype.predict=function(t,e){return this.execute_(t,!0,this.outputNodes)},t.prototype.constructTensorMap=function(t){var e=t instanceof ut?[t]:t;if(e.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,n,r){return t[n]=e[r],t},{})},t.prototype.execute=function(t,e){return this.execute_(t,!1,e)},t.prototype.execute_=function(t,e,n){if(void 0===e&&(e=!0),n=n||this.outputNodes,(t instanceof ut||Array.isArray(t))&&(t=this.constructTensorMap(t)),this.executor.isControlFlowModel||this.executor.isDynamicShapeModel)throw new Error("The model contains control flow or dynamic shape ops, please use executeAsync method");var r=this.executor.execute(this.convertTensorMapToTensorsMap(t),e,n),i=Object.keys(r);return Array.isArray(n)&&n.length>1?n.map(function(t){return r[t]}):r[i[0]]},t.prototype.executeAsync=function(t,e){return Pg(this,void 0,void 0,function(){var n,r;return Bg(this,function(i){switch(i.label){case 0:if(!this.executor.isControlFlowModel&&!this.executor.isDynamicShapeModel)throw new Error("The model does not contain control flow or dynamic shape ops, please use execute method for better performance.");return e=e||this.outputNodes,(t instanceof ut||Array.isArray(t))&&(t=this.constructTensorMap(t)),[4,this.executor.executeAsync(this.convertTensorMapToTensorsMap(t),e)];case 1:return n=i.sent(),r=Object.keys(n),[2,Array.isArray(e)&&e.length>1?e.map(function(t){return n[t]}):n[r[0]]]}})})},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,n){return e[n]=[t[n]],e},{})},t.prototype.dispose=function(){this.executor.dispose()},t}();var Oy=function(t,e){return(Oy=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function _y(t,e){function n(){this.constructor=t}Oy(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function My(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function Ly(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),Uy=Py(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Wy=Py(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Vy=Py(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),jy=Py(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,o=-32;o>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),qy=Py(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Gy=Py(function(t){!function(e,n){var r,i=(0,eval)("this"),o=256,a=6,s="random",u=n.pow(o,a),l=n.pow(2,52),c=2*l,p=o-1;function h(t,h,g){var y=[],v=d(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,a=n&&n.plugins;return[+new Date,i,a,i.screen,m(e)]}}():t,3),y),b=new function(t){var e,n=t.length,r=this,i=0,a=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,d(m(b.S),e),(h.pass||g||function(t,e,r,i){return i&&(i.S&&f(i,b),t.state=function(){return f(b,{})}),r?(n[s]=t,e):t})(w,v,"global"in h?h.global:this==n,h.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",i=0;i0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function r(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function i(t,e){if(void 0===e&&(e=[]),null==e&&(e=[]),Array.isArray(t)||l(t))for(var n=0;n=-n&&t=n?i():setTimeout(a,s)}};a()})},e.inferFromImplicitShape=function(t,e){for(var n=1,r=-1,i=0;i=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o},e.parseAxisParam=s,e.squeezeShape=function(t,e){for(var n=[],r=[],i=null==e?null:s(e,t).sort(),o=0,a=0;aa)&&1===t[a]&&(n.push(t[a]),r.push(a)),i[o]<=a&&o++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}},e.getTypedArrayFromDType=function(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n},e.getArrayFromDType=function(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n},e.checkComputationForErrors=function(t,e,n){if("float32"===e)for(var r=0;r=0;--r)n[r]=n[r+1]*t[r+1];return n},e.toTypedArray=function(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=i(t)),n&&u(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}});zy(Ky);Ky.shuffle,Ky.clamp,Ky.nearestLargerEven,Ky.sum,Ky.randUniform,Ky.distSquared,Ky.assert,Ky.assertShapesMatch,Ky.assertNonNull,Ky.flatten,Ky.sizeFromShape,Ky.isScalarShape,Ky.arraysEqual,Ky.isInt,Ky.tanh,Ky.sizeToSquarishShape,Ky.createShuffledIndices,Ky.rightPad,Ky.repeatedTry,Ky.inferFromImplicitShape,Ky.parseAxisParam,Ky.squeezeShape,Ky.getTypedArrayFromDType,Ky.getArrayFromDType,Ky.checkComputationForErrors,Ky.checkConversionForErrors,Ky.hasEncodingLoss;var $y=Ky.isTypedArray,Xy=(Ky.bytesPerElement,Ky.bytesFromStringArray,Ky.isString,Ky.isBoolean,Ky.isNumber,Ky.inferDtype,Ky.isFunction,Ky.nearestDivisor,Ky.computeStrides,Ky.toTypedArray,Ky.toNestedArray,Ky.makeOnesTypedArray,Ky.makeZerosTypedArray,Ky.now,Ky.assertNonNegativeIntegerDimensions,Py(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var n=7;function r(t,e){var r;return r=Array.isArray(t)?parseFloat(t[0].toFixed(n))+" + "+parseFloat(t[1].toFixed(n))+"j":Ky.isString(t)?"'"+t+"'":parseFloat(t.toFixed(n)).toString(),Ky.rightPad(r,e)}function i(t){for(var e=[],n=0;n1)for(var p=0;p20){var h=3*l,f=Array.from(e.slice(0,h)),d=Array.from(e.slice(c-3*l,c));return"complex64"===o&&(f=i(f),d=i(d)),["["+f.map(function(t,e){return r(t,s[e])}).join(", ")+", ..., "+d.map(function(t,e){return r(t,s[c-3+e])}).join(", ")+"]"]}return["["+("complex64"===o?i(e):Array.from(e)).map(function(t,e){return r(t,s[e])}).join(", ")+"]"]}var m=n.slice(1),g=a.slice(1),y=a[0]*l,v=[];if(c>20){for(var b=0;b<3;b++){var w=(x=b*y)+y;v.push.apply(v,t(e.slice(x,w),m,o,g,s,!1))}v.push("...");for(b=c-3;b0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=o)return t;switch(t){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return t}}),u=i[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),f(n)?r.showHidden=n:n&&e._extend(r,n),y(r.showHidden)&&(r.showHidden=!1),y(r.depth)&&(r.depth=2),y(r.colors)&&(r.colors=!1),y(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=s),l(r,t,r.depth)}function s(t,e){var n=a.styles[e];return n?"["+a.colors[n][0]+"m"+t+"["+a.colors[n][1]+"m":t}function u(t,e){return t}function l(t,n,r){if(t.customInspect&&n&&N(n.inspect)&&n.inspect!==e.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(r,t);return g(i)||(i=l(t,i,r)),i}var o=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(g(e)){var n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return m(e)?t.stylize(""+e,"number"):f(e)?t.stylize(""+e,"boolean"):d(e)?t.stylize("null","null"):void 0}(t,n);if(o)return o;var a=Object.keys(n),s=function(t){var e={};return a.forEach(function(t,n){e[t]=!0}),e}();if(t.showHidden&&(a=Object.getOwnPropertyNames(n)),x(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(n);if(0===a.length){if(N(n)){var u=n.name?": "+n.name:"";return t.stylize("[Function"+u+"]","special")}if(v(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(w(n))return t.stylize(Date.prototype.toString.call(n),"date");if(x(n))return c(n)}var b,S="",C=!1,E=["{","}"];return h(n)&&(C=!0,E=["[","]"]),N(n)&&(S=" [Function"+(n.name?": "+n.name:"")+"]"),v(n)&&(S=" "+RegExp.prototype.toString.call(n)),w(n)&&(S=" "+Date.prototype.toUTCString.call(n)),x(n)&&(S=" "+c(n)),0!==a.length||C&&0!=n.length?r<0?v(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special"):(t.seen.push(n),b=C?function(t,e,n,r,i){for(var o=[],a=0,s=e.length;a60?n[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}(b,S,E)):E[0]+S+E[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function p(t,e,n,r,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(s=t.stylize("[Setter]","special")),I(r,i)||(a="["+i+"]"),s||(t.seen.indexOf(u.value)<0?(s=d(n)?l(t,u.value,null):l(t,u.value,n-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n")):s=t.stylize("[Circular]","special")),y(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function h(t){return Array.isArray(t)}function f(t){return"boolean"==typeof t}function d(t){return null===t}function m(t){return"number"==typeof t}function g(t){return"string"==typeof t}function y(t){return void 0===t}function v(t){return b(t)&&"[object RegExp]"===S(t)}function b(t){return"object"==typeof t&&null!==t}function w(t){return b(t)&&"[object Date]"===S(t)}function x(t){return b(t)&&("[object Error]"===S(t)||t instanceof Error)}function N(t){return"function"==typeof t}function S(t){return Object.prototype.toString.call(t)}function C(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(t){if(y(i)&&(i=process.env.NODE_DEBUG||""),t=t.toUpperCase(),!o[t])if(new RegExp("\\b"+t+"\\b","i").test(i)){var n=process.pid;o[t]=function(){var r=e.format.apply(e,arguments);console.error("%s %d: %s",t,n,r)}}else o[t]=function(){};return o[t]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=h,e.isBoolean=f,e.isNull=d,e.isNullOrUndefined=function(t){return null==t},e.isNumber=m,e.isString=g,e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=y,e.isRegExp=v,e.isObject=b,e.isDate=w,e.isError=x,e.isFunction=N,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=ev;var E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function I(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){var t,n;console.log("%s - %s",(n=[C((t=new Date).getHours()),C(t.getMinutes()),C(t.getSeconds())].join(":"),[t.getDate(),E[t.getMonth()],n].join(" ")),e.format.apply(e,arguments))},e.inherits=rv,e._extend=function(t,e){if(!e||!b(e))return t;for(var n=Object.keys(e),r=n.length;r--;)t[n[r]]=e[n[r]];return t};var k="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function A(t,e){if(!t){var n=new Error("Promise was rejected with a falsy value");n.reason=t,t=n}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(k&&t[k]){var e;if("function"!=typeof(e=t[k]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,k,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,n,r=new Promise(function(t,r){e=t,n=r}),i=[],o=0;o0?this.prefetch(e):this,r=[],i=0,[4,n.next()];case 1:o=a.sent(),a.label=2;case 2:return o.done?[3,4]:(r.push(o.value),++i>=t?[2,r]:[4,n.next()]);case 3:return o=a.sent(),[3,2];case 4:return[2,r]}})})},t.prototype.resolveFully=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:t=e.sent(),e.label=2;case 2:return t.done?[3,4]:[4,this.next()];case 3:return t=e.sent(),[3,2];case 4:return[2]}})})},t.prototype.resolveWhile=function(t){return My(this,void 0,void 0,function(){var e,n;return Ly(this,function(r){switch(r.label){case 0:return[4,this.next()];case 1:e=r.sent(),n=t(e.value),r.label=2;case 2:return e.done||!n?[3,4]:[4,this.next()];case 3:return e=r.sent(),n=t(e.value),[3,2];case 4:return[2]}})})},t.prototype.handleErrors=function(t){return new Iv(this,t)},t.prototype.filter=function(t){return new Cv(this,t)},t.prototype.map=function(t){return new Ev(this,t)},t.prototype.mapAsync=function(t){return new kv(this,t)},t.prototype.serialMapAsync=function(t){return new kv(this,t).serial()},t.prototype.flatmap=function(t){return new Tv(this,t)},t.prototype.forEachAsync=function(t){return My(this,void 0,void 0,function(){return Ly(this,function(e){return[2,this.map(t).resolveFully()]})})},t.prototype.serialForEach=function(t){return My(this,void 0,void 0,function(){return Ly(this,function(e){return[2,this.serialMapAsync(t).resolveWhile(function(t){return!0===t})]})})},t.prototype.rowMajorBatch=function(t,e){return void 0===e&&(e=!0),new Sv(this,t,e)},t.prototype.columnMajorBatch=function(t,e,n){return void 0===e&&(e=!0),void 0===n&&(n=uv),this.rowMajorBatch(t,e).map(function(t){return sv(t,n)})},t.prototype.concatenate=function(t,e){return new Rv(fv([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new Nv(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new xv(this,t)},t.prototype.prefetch=function(t){return new Ov(this,t)},t.prototype.shuffle=function(t,e){return new _v(this,t,e)},t.prototype.serial=function(){return new wv(this)},t}(),vv=function(t){function e(e){var n=t.call(this)||this;return n.items=e,n.trav=0,n}return _y(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t,e;return Ly(this,function(n){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],e=t instanceof ut?Wo(t):t,this.trav++,[2,{value:e,done:!1}])})})},e}(yv),bv=function(t){function e(e){var n=t.call(this)||this;return n.nextFn=e,n}return _y(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){try{return[2,this.nextFn()]}catch(t){throw t.message="Error thrown while iterating through a dataset: "+t.message,t}return[2]})})},e}(yv),wv=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.lastRead=Promise.resolve({value:null,done:!1}),n}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){return[2,this.upstream.next()]})})},e}(yv),xv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:return this.count++ Take"},e.prototype.next=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(yv),Sv=function(t){function e(e,n,r){void 0===r&&(r=!0);var i=t.call(this)||this;return i.upstream=e,i.batchSize=n,i.enableSmallLastBatch=r,i.lastRead=Promise.resolve({value:null,done:!1}),i}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){var t,e;return Ly(this,function(n){switch(n.label){case 0:t=[],n.label=1;case 1:return t.length0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return[2,{value:t,done:!1}]}})})},e}(yv),Cv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.predicate=n,r.lastRead=Promise.resolve({value:null,done:!1}),r}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(t=e.sent()).done||this.predicate(t.value)?[2,t]:(Ht(t.value),[3,0]);case 2:return[2]}})})},e}(yv),Ev=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Ly(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,{value:null,done:!0}];for(e=tv(t.value),n=this.transform(t.value),r=tv(n),i=0,o=e;i handleErrors"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,e.sent()];case 3:return t=e.sent(),this.handler(t)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},e}(yv),kv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Ly(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:return(t=s.sent()).done?[2,{value:null,done:!0}]:(e=tv(t.value),[4,this.transform(t.value)]);case 2:for(n=s.sent(),r=tv(n),i=0,o=e;i Flatmap"},e.prototype.pump=function(){return My(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Ly(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,!1];for(e=tv(t.value),n=this.transform(t.value),r=tv(n),this.outputQueue.pushAll(n),i=0,o=e;i Chained"},e.prototype.next=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return My(this,void 0,void 0,function(){var e,n;return Ly(this,function(r){switch(r.label){case 0:return[4,t];case 1:return r.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=r.sent()).done)return[2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),r.label=3;case 3:return[4,this.iterator.next()];case 4:return(n=r.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,n]}})})},e}(yv);(gv=mv||(mv={}))[gv.FAIL=0]="FAIL",gv[gv.SHORTEST=1]="SHORTEST",gv[gv.LONGEST=2]="LONGEST";var Dv=function(t){function e(e,n){void 0===n&&(n=mv.FAIL);var r=t.call(this)||this;return r.iterators=e,r.mismatchMode=n,r.count=0,r.currentPromise=null,r}return _y(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return My(this,void 0,void 0,function(){function e(t){return t instanceof yv?{value:t.next().then(function(t){return n++,t.done&&r++,t.value}),recurse:!1}:{value:null,recurse:!0}}var n,r,i;return Ly(this,function(o){switch(o.label){case 0:return[4,t];case 1:return o.sent(),n=0,r=0,[4,lv(this.iterators,e)];case 2:if(i=o.sent(),n===r)return[2,{value:null,done:!0}];if(r>0)switch(this.mismatchMode){case mv.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case mv.SHORTEST:return[2,{value:null,done:!0}];case mv.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){switch(t.label){case 0:return this.currentPromise=this.nextState(this.currentPromise),[4,this.currentPromise];case 1:return[2,t.sent()]}})})},e}(yv),Ov=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.bufferSize=n,r.buffer=new pv(n),r}return _y(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},e.prototype.refill=function(){for(;!this.buffer.isFull();){var t=this.upstream.next();this.buffer.push(t)}},e.prototype.next=function(){return this.refill(),this.buffer.shift()},e}(yv),_v=function(t){function e(e,n,r){var i=t.call(this,e,n)||this;return i.upstream=e,i.windowSize=n,i.upstreamExhausted=!1,i.random=Hy(r||X.now().toString()),i.lastRead=Promise.resolve({value:null,done:!1}),i}return _y(e,t),e.prototype.next=function(){return My(this,void 0,void 0,function(){var t=this;return Ly(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.randomInt=function(t){return Math.floor(this.random()*t)},e.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},e.prototype.serialNext=function(){return My(this,void 0,void 0,function(){var t,e;return Ly(this,function(n){switch(n.label){case 0:this.upstreamExhausted||this.refill(),n.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return(e=n.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return[2,{value:null,done:!0}]}})})},e}(Ov),Mv=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var n=this;void 0===e&&(e=!0);var r=this;return X.assert(t>0,function(){return"batchSize needs to be positive, but it is\n "+t}),Lv(function(){return My(n,void 0,void 0,function(){return Ly(this,function(n){switch(n.label){case 0:return[4,r.iterator()];case 1:return[2,n.sent().columnMajorBatch(t,e,Fv)]}})})},this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){var e,r;return Ly(this,function(i){switch(i.label){case 0:return[4,n.iterator()];case 1:return r=(e=i.sent()).concatenate,[4,t.iterator()];case 2:return[2,r.apply(e,[i.sent()])]}})})},this.size===1/0||t.size===1/0?1/0:null!=this.size&&null!=t.size?this.size+t.size:null)},t.prototype.filter=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().filter(function(e){return qt(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return My(this,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},t.prototype.forEach=function(t){return My(this,void 0,void 0,function(){return Ly(this,function(e){return Pt("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().map(function(e){return qt(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().mapAsync(t)]}})})},this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var n=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().prefetch(t)]}})})},this.size)},t.prototype.repeat=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){var e=this;return Ly(this,function(r){return[2,function(t,e){return new Rv(t,e)}(dv(function(){return My(e,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:return t={},[4,n.iterator()];case 1:return[2,(t.value=e.sent(),t.done=!1,t)]}})})}).take(t))]})})},null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,n=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().skip(t)]}})})},null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.sizet?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){switch(t.label){case 0:return[4,this.iterator()];case 1:return[2,t.sent().collect()]}})})},t.MAX_BUFFER_SIZE=1e4,t}();function Lv(t,e){return void 0===e&&(e=null),new(function(n){function r(){var t=null!==n&&n.apply(this,arguments)||this;return t.size=e,t}return _y(r,n),r.prototype.iterator=function(){return My(this,void 0,void 0,function(){return Ly(this,function(e){return[2,t()]})})},r}(Mv))}function Fv(t){return null===t?null:function(t){return null==t||ov(t)||Array.isArray(t)||"object"==typeof t&&t instanceof ut||$y(t)}(t[0])?{value:function(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof ut?oa(t):Te(t)}(t),recurse:!1}:{value:null,recurse:!0}}var zv=function(t){function e(e){var n=t.call(this)||this;return n.input=e,n}return _y(e,t),e.prototype.iterator=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){switch(e.label){case 0:return[4,this.input.iterator()];case 1:return t=e.sent(),[2,t.decodeUTF8().split("\n")]}})})},e}(Mv),Pv=Symbol("out"),Bv=Symbol("field"),Uv=Symbol("quote"),Wv=Symbol("quoteafterquote"),Vv=Symbol("quoteinquote"),jv=function(t){function e(e,n){var r=t.call(this)||this;return r.input=e,r.hasHeader=!0,r.fullColumnNames=null,r.columnNamesValidated=!1,r.columnConfigs=null,r.configuredColumnsOnly=!1,r.delimiter=",",r.base=new zv(e),n||(n={}),r.hasHeader=!1!==n.hasHeader,r.fullColumnNames=n.columnNames,r.columnConfigs=n.columnConfigs,r.configuredColumnsOnly=n.configuredColumnsOnly,r.delimiter=n.delimiter?n.delimiter:",",r}return _y(e,t),e.prototype.columnNames=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){switch(t.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:t.sent(),t.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},e.prototype.setColumnNames=function(){return My(this,void 0,void 0,function(){var t,e,n,r,i,o,a=this;return Ly(this,function(s){switch(s.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(t=s.sent(),!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&t&&X.assert(t.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+a.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),n=Object.keys(e).filter(function(t){return e[t]>1}),X.assert(0===n.length,function(){return"Duplicate column names found: "+n.toString()}),this.columnConfigs)for(r=0,i=Object.keys(this.columnConfigs);r Split('"+this.separator+"')"},e.prototype.pump=function(){return My(this,void 0,void 0,function(){var t,e,n,r,i;return Ly(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if((t=o.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],n=0,r=e.slice(0,-1);n Utf8"},e.prototype.pump=function(){return My(this,void 0,void 0,function(){var t,e,n;return Ly(this,function(r){switch(r.label){case 0:return[4,this.upstream.next()];case 1:return(t=r.sent()).done?[2,!1]:(e=t.value,n=Bt.get("IS_BROWSER")?this.decoder.decode(e,{stream:!0}):this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(n),[2,!0])}})})},e}(Av),Jv=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.file=e,r.options=n,X.assert(e instanceof Uint8Array||!!Bt.get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),r.offset=n.offset||0,r.chunkSize=n.chunkSize||1048576,r}return _y(e,t),e.prototype.summary=function(){return"FileChunks "+this.file},e.prototype.next=function(){return My(this,void 0,void 0,function(){var t,e,n=this;return Ly(this,function(r){switch(r.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise(function(t,e){var r=n.offset+n.chunkSize;if(n.file instanceof Uint8Array)t(new Uint8Array(n.file.slice(n.offset,r)));else{var i=new FileReader;i.onload=function(n){var r=i.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(r)},i.onabort=function(t){return e(new Error("Aborted"))},i.onerror=function(t){return e(new Error(t.type))};var o=n.file.slice(n.offset,r);i.readAsArrayBuffer(o)}n.offset=r}),e={},[4,t]);case 1:return[2,(e.value=r.sent(),e.done=!1,e)]}})})},e}($v);function Zv(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var Qv=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.input=e,r.options=n,r}return _y(e,t),e.prototype.iterator=function(){return My(this,void 0,void 0,function(){var t;return Ly(this,function(e){return Zv(this.input)&&Bt.get("IS_NODE")&&(t=require("fs"),this.input=t.readFileSync(this.input.substr(7))),[2,new Jv(this.input,this.options)]})})},e}(qv),tb=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.url=e,r.fileOptions=n,r}return _y(e,t),e.prototype.iterator=function(){return My(this,void 0,void 0,function(){return Ly(this,function(t){return Zv(this.url)?[2,new Qv(this.url,this.fileOptions).iterator()]:[2,function(t,e){return void 0===e&&(e={}),My(this,void 0,void 0,function(){var n,r,i,o;return Ly(this,function(a){switch(a.label){case 0:return Bt.get("IS_BROWSER")?[4,fetch(t)]:[3,5];case 1:return(n=a.sent()).ok?[4,n.blob()]:[3,3];case 2:return r=a.sent(),[2,new Jv(r,e)];case 3:throw new Error(n.statusText);case 4:return[3,9];case 5:if(i=require("node-fetch"),"string"!=typeof t)throw new Error("URL must be a string. Request objects are not supported in the node.js environment yet.");return[4,i(t)];case 6:return(n=a.sent()).ok?[4,n.buffer()]:[3,8];case 7:return o=a.sent(),[2,new Jv(o,e)];case 8:throw new Error(n.statusText);case 9:return[2]}})})}(this.url,this.fileOptions)]})})},e}(qv);var eb=Object.freeze({array:function(t){var e=this;return Lv(function(){return My(e,void 0,void 0,function(){return Ly(this,function(e){return[2,fv(t)]})})},t.length)},Dataset:Mv,zip:function(t){var e,n=this;if(!cv(t))throw new Error("The argument to zip() must be an object or array.");if(Array.isArray(t))for(var r=0;r