UNPKG

@tensorflow-models/coco-ssd

Version:

Object detection model (coco-ssd) in TensorFlow.js

2 lines 967 kB
// @tensorflow/tfjs Copyright 2019 Google !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.tf=e.tf||{})}(this,function(exports){"use strict";var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)};function __awaiter(e,t,r,n){return new(r||(r=Promise))(function(a,o){function i(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){e.done?a(e.value):new r(function(t){t(e.value)}).then(i,s)}u((n=n.apply(e,t||[])).next())})}function __generator(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],n=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var contexts={},WEBGL_ATTRIBUTES={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function getWebGLContext(e){e in contexts||(document.createElement("canvas").addEventListener("webglcontextlost",function(t){t.preventDefault(),delete contexts[e]},!1),contexts[e]=getWebGLRenderingContext(e));var t=contexts[e];return t.isContextLost()?(delete contexts[e],getWebGLContext(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),contexts[e])}function getWebGLRenderingContext(e){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var t=document.createElement("canvas");return 1===e?t.getContext("webgl",WEBGL_ATTRIBUTES)||t.getContext("experimental-webgl",WEBGL_ATTRIBUTES):t.getContext("webgl2",WEBGL_ATTRIBUTES)}function isMobile(){var e=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(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}function shuffle(e){for(var t=e.length,r=0,n=0;t>0;)n=Math.random()*t|0,r=e[--t],e[t]=e[n],e[n]=r}function clamp(e,t,r){return Math.max(e,Math.min(t,r))}function nearestLargerEven(e){return e%2==0?e:e+1}function sum(e){for(var t=0,r=0;r<e.length;r++)t+=e[r];return t}function randUniform(e,t){var r=Math.random();return t*r+(1-r)*e}function distSquared(e,t){for(var r=0,n=0;n<e.length;n++){var a=Number(e[n])-Number(t[n]);r+=a*a}return r}function assert(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function assertShapesMatch(e,t,r){void 0===r&&(r=""),assert(arraysEqual(e,t),r+" Shapes "+e+" and "+t+" must match")}function assertNonNull(e){assert(null!=e,"The input to the tensor constructor must be a non-null value.")}function flatten(e,t){if(void 0===t&&(t=[]),Array.isArray(e)||isTypedArray(e))for(var r=0;r<e.length;++r)flatten(e[r],t);else t.push(e);return t}function sizeFromShape(e){if(0===e.length)return 1;for(var t=e[0],r=1;r<e.length;r++)t*=e[r];return t}function isScalarShape(e){return 0===e.length}function arraysEqual(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function isInt(e){return e%1==0}function tanh(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;var t=Math.exp(2*e);return(t-1)/(t+1)}function sizeToSquarishShape(e){var t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function createShuffledIndices(e){for(var t=new Uint32Array(e),r=0;r<e;++r)t[r]=r;return shuffle(t),t}function rightPad(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function repeatedTry(e,t,r){return void 0===t&&(t=function(e){return 0}),new Promise(function(n,a){var o=0,i=function(){if(e())n();else{var s=t(++o);null!=r&&o>=r?a():setTimeout(i,s)}};i()})}function inferFromImplicitShape(e,t){for(var r=1,n=-1,a=0;a<e.length;++a)if(e[a]>=0)r*=e[a];else if(-1===e[a]){if(-1!==n)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+a);n=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-1===n){if(t>0&&t!==r)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===r)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%r!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+r);var o=e.slice();return o[n]=t/r,o}function parseAxisParam(e,t){var r=t.length;return assert((e=null==e?t.map(function(e,t){return t}):[].concat(e)).every(function(e){return e>=-r&&e<r}),"All values in axis param must be in range [-"+r+", "+r+") but got axis "+e),assert(e.every(function(e){return isInt(e)}),"All values in axis param must be integers but got axis "+e),e.map(function(e){return e<0?r+e:e})}function squeezeShape(e,t){for(var r=[],n=[],a=null==t?null:parseAxisParam(t,e).sort(),o=0,i=0;i<e.length;++i){if(null!=a){if(a[o]===i&&1!==e[i])throw new Error("Can't squeeze axis "+i+" since its dim '"+e[i]+"' is not 1");(null==a[o]||a[o]>i)&&1===e[i]&&(r.push(e[i]),n.push(i)),a[o]<=i&&o++}1!==e[i]&&(r.push(e[i]),n.push(i))}return{newShape:r,keptDims:n}}function getTypedArrayFromDType(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(t)}return r}function getArrayFromDType(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else if("bool"===e)r=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);r=new Array(t)}return r}function checkComputationForErrors(e,t,r){if("float32"===t)for(var n=0;n<e.length;n++){var a=e[n];if(isNaN(a)||!isFinite(a))throw Error("The result of the '"+r+"' is "+a+".")}}function checkConversionForErrors(e,t){for(var r=0;r<e.length;r++){var n=e[r];if(isNaN(n)||!isFinite(n))throw Error("A tensor of type "+t+" being uploaded contains "+n+".")}}function hasEncodingLoss(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function bytesPerElement(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function bytesFromStringArray(e){if(null==e)return 0;var t=0;return e.forEach(function(e){return t+=2*e.length}),t}function isString(e){return"string"==typeof e||e instanceof String}function isBoolean(e){return"boolean"==typeof e}function isNumber(e){return"number"==typeof e}function inferDtype(e){return Array.isArray(e)?inferDtype(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":isNumber(e)?"float32":isString(e)?"string":isBoolean(e)?"bool":"float32"}function isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)}function nearestDivisor(e,t){for(var r=t;r<e;++r)if(e%r==0)return r;return e}function computeStrides(e){var t=e.length;if(t<2)return[];var r=new Array(t-1);r[t-2]=e[t-1];for(var n=t-3;n>=0;--n)r[n]=r[n+1]*e[n+1];return r}function toTypedArray(e,t,r){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=flatten(e)),r&&checkConversionForErrors(e,t),noConversionNeeded(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){for(var n=new Uint8Array(e.length),a=0;a<n.length;++a)0!==Math.round(e[a])&&(n[a]=1);return n}throw new Error("Unknown data type "+t)}function createNestedArray(e,t,r){var n=new Array;if(1===t.length)for(var a=t[0],o=0;o<a;o++)n[o]=r[e+o];else{a=t[0];var i=t.slice(1),s=i.reduce(function(e,t){return e*t});for(o=0;o<a;o++)n[o]=createNestedArray(e+o*s,i,r)}return n}function toNestedArray(e,t){if(0===e.length)return t[0];var r=e.reduce(function(e,t){return e*t});if(0===r)return[];if(r!==t.length)throw new Error("["+e+"] does not match the input size.");return createNestedArray(0,e,t)}function noConversionNeeded(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}function makeOnesTypedArray(e,t){for(var r=makeZerosTypedArray(e,t),n=0;n<r.length;n++)r[n]=1;return r}function makeZerosTypedArray(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type "+t)}function now(){if("undefined"!=typeof performance)return performance.now();if("undefined"!=typeof process){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}throw new Error("Cannot measure time in this environment. You should run tf.js in the browser or in Node.js")}function monitorPromisesProgress(e,t,r,n){!function(e){assert(null!=e&&Array.isArray(e)&&e.length>0,"promises must be a none empty array")}(e),function(e,t){assert(e>=0&&e<=1,"Progress fraction must be in range [0, 1], but got startFraction "+e),assert(t>=0&&t<=1,"Progress fraction must be in range [0, 1], but got endFraction "+t),assert(t>=e,"startFraction must be no more than endFraction, but got startFraction "+e+" and endFraction "+t)}(r=null==r?0:r,n=null==n?1:n);var a=0;return Promise.all(e.map(function(o){return o.then(function(o){var i=r+ ++a/e.length*(n-r);return t(i),o}),o}))}var util=Object.freeze({shuffle:shuffle,clamp:clamp,nearestLargerEven:nearestLargerEven,sum:sum,randUniform:randUniform,distSquared:distSquared,assert:assert,assertShapesMatch:assertShapesMatch,assertNonNull:assertNonNull,flatten:flatten,sizeFromShape:sizeFromShape,isScalarShape:isScalarShape,arraysEqual:arraysEqual,isInt:isInt,tanh:tanh,sizeToSquarishShape:sizeToSquarishShape,createShuffledIndices:createShuffledIndices,rightPad:rightPad,repeatedTry:repeatedTry,inferFromImplicitShape:inferFromImplicitShape,parseAxisParam:parseAxisParam,squeezeShape:squeezeShape,getTypedArrayFromDType:getTypedArrayFromDType,getArrayFromDType:getArrayFromDType,checkComputationForErrors:checkComputationForErrors,checkConversionForErrors:checkConversionForErrors,hasEncodingLoss:hasEncodingLoss,isTypedArray:isTypedArray,bytesPerElement:bytesPerElement,bytesFromStringArray:bytesFromStringArray,isString:isString,isBoolean:isBoolean,isNumber:isNumber,inferDtype:inferDtype,isFunction:isFunction,nearestDivisor:nearestDivisor,computeStrides:computeStrides,toTypedArray:toTypedArray,toNestedArray:toNestedArray,makeOnesTypedArray:makeOnesTypedArray,makeZerosTypedArray:makeZerosTypedArray,now:now,monitorPromisesProgress:monitorPromisesProgress}),Profiler=function(){function e(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Logger)}return e.prototype.profileKernel=function(e,t){var r,n=this,a=this.backendTimer.time(function(){r=t()});return(Array.isArray(r)?r:[r]).forEach(function(t){var r=t.dataSync();checkComputationForErrors(r,t.dtype,e),a.then(function(a){var o="";null!=a.getExtraProfileInfo&&(o=a.getExtraProfileInfo()),n.logger.logKernelProfile(e,t,r,a.kernelMs,o)})}),r},e}(),Logger=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,r,n,a){var o=rightPad(n+"ms",9),i=rightPad(e,25),s=t.rank,u=t.size,l=rightPad(t.shape.toString(),14);console.log("%c"+i+"\t%c"+o+"\t%c"+s+"D "+l+"\t%c"+u+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green")},e}(),FORMAT_LIMIT_NUM_VALS=20,FORMAT_NUM_FIRST_LAST_VALS=3,FORMAT_NUM_SIG_DIGITS=7;function tensorToString(e,t,r,n){var a=computeStrides(t),o=computeMaxSizePerColumn(e,t,r,a),i=t.length,s=subTensorToString(e,t,r,a,o),u=["Tensor"];return n&&(u.push(" dtype: "+r),u.push(" rank: "+i),u.push(" shape: ["+t+"]"),u.push(" values:")),u.push(s.map(function(e){return" "+e}).join("\n")),u.join("\n")}function computeMaxSizePerColumn(e,t,r,n){var a=sizeFromShape(t),o=n[n.length-1],i=new Array(o).fill(0),s=t.length,u="complex64"===r?createComplexTuples(e):e;if(s>1)for(var l=0;l<a/o;l++)for(var p=l*o,c=0;c<o;c++)i[c]=Math.max(i[c],valToString(u[p+c],0).length);return i}function valToString(e,t){return rightPad(Array.isArray(e)?parseFloat(e[0].toFixed(FORMAT_NUM_SIG_DIGITS))+" + "+parseFloat(e[1].toFixed(FORMAT_NUM_SIG_DIGITS))+"j":isString(e)?"'"+e+"'":parseFloat(e.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(),t)}function subTensorToString(e,t,r,n,a,o){void 0===o&&(o=!0);var i="complex64"===r?2:1,s=t[0],u=t.length;if(0===u)return"complex64"===r?[valToString(createComplexTuples(e)[0],0)]:[e[0].toString()];if(1===u){if(s>FORMAT_LIMIT_NUM_VALS){var l=FORMAT_NUM_FIRST_LAST_VALS*i,p=Array.from(e.slice(0,l)),c=Array.from(e.slice(s-FORMAT_NUM_FIRST_LAST_VALS*i,s));return"complex64"===r&&(p=createComplexTuples(p),c=createComplexTuples(c)),["["+p.map(function(e,t){return valToString(e,a[t])}).join(", ")+", ..., "+c.map(function(e,t){return valToString(e,a[s-FORMAT_NUM_FIRST_LAST_VALS+t])}).join(", ")+"]"]}return["["+("complex64"===r?createComplexTuples(e):Array.from(e)).map(function(e,t){return valToString(e,a[t])}).join(", ")+"]"]}var h=t.slice(1),d=n.slice(1),f=n[0]*i,m=[];if(s>FORMAT_LIMIT_NUM_VALS){for(var g=0;g<FORMAT_NUM_FIRST_LAST_VALS;g++){var y=(v=g*f)+f;m.push.apply(m,subTensorToString(e.slice(v,y),h,r,d,a,!1))}for(m.push("..."),g=s-FORMAT_NUM_FIRST_LAST_VALS;g<s;g++)y=(v=g*f)+f,m.push.apply(m,subTensorToString(e.slice(v,y),h,r,d,a,g===s-1))}else for(g=0;g<s;g++){var v;y=(v=g*f)+f,m.push.apply(m,subTensorToString(e.slice(v,y),h,r,d,a,g===s-1))}var x=2===u?",":"";for(m[0]="["+m[0]+x,g=1;g<m.length-1;g++)m[g]=" "+m[g]+x;var b=",\n";for(g=2;g<u;g++)b+="\n";return m[m.length-1]=" "+m[m.length-1]+"]"+(o?"":b),m}function createComplexTuples(e){for(var t=[],r=0;r<e.length;r+=2)t.push([e[r],e[r+1]]);return t}var TensorBuffer=function(){function e(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=sizeFromShape(e),null!=r){var n=r.length;assert(n===this.size,"Length of values '"+n+"' does not match the size inferred by the shape '"+this.size+"'.")}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||getArrayFromDType(t,sizeFromShape(this.shape)),this.strides=computeStrides(e)}return e.prototype.set=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];0===t.length&&(t=[0]),assert(t.length===this.rank,"The number of provided coordinates ("+t.length+") must match the rank ("+this.rank+")");var n=this.locToIndex(t);this.values[n]=e},e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];0===e.length&&(e=[0]);for(var r=e[e.length-1],n=0;n<e.length-1;++n)r+=this.strides[n]*e[n];return this.values[r]},e.prototype.locToIndex=function(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];for(var t=e[e.length-1],r=0;r<e.length-1;++r)t+=this.strides[r]*e[r];return t},e.prototype.indexToLoc=function(e){if(0===this.rank)return[];if(1===this.rank)return[e];for(var t=new Array(this.shape.length),r=0;r<t.length-1;++r)t[r]=Math.floor(e/this.strides[r]),e-=t[r]*this.strides[r];return t[t.length-1]=e,t},Object.defineProperty(e.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return Tensor.make(this.shape,{values:this.values},this.dtype)},e}(),trackerFn=null,opHandler=null,deprecationWarningFn=null;function setTensorTracker(e){trackerFn=e}function setOpHandler(e){opHandler=e}function setDeprecationWarningFn(e){deprecationWarningFn=e}var Tensor=function(){function e(e,t,r,n){this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=sizeFromShape(e),this.strides=computeStrides(e),this.dataId=null!=n?n:{},this.id=trackerFn().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",trackerFn().registerTensor(this),null!=r&&trackerFn().write(this.dataId,r)}return e.make=function(t,r,n){return new e(t,n,r.values,r.dataId)},e.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},e.prototype.asScalar=function(){return this.throwIfDisposed(),assert(1===this.size,"The array must have only 1 element."),this.reshape([])},e.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},e.prototype.as2D=function(e,t){return this.throwIfDisposed(),this.reshape([e,t])},e.prototype.as3D=function(e,t,r){return this.throwIfDisposed(),this.reshape([e,t,r])},e.prototype.as4D=function(e,t,r,n){return this.throwIfDisposed(),this.reshape([e,t,r,n])},e.prototype.as5D=function(e,t,r,n,a){return this.throwIfDisposed(),this.reshape([e,t,r,n,a])},e.prototype.asType=function(e){return this.throwIfDisposed(),opHandler.cast(this,e)},Object.defineProperty(e.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];deprecationWarningFn("Tensor.get() is deprecated. Use Tensor.array() and native array indexing instead."),assert(e.length===this.rank,"Number of coordinates in get() must match the rank of the tensor"),assert("complex64"!==this.dtype,"Tensor.get() is not supported for complex64 tensors yet."),this.throwIfDisposed(),0===e.length&&(e=[0]);for(var r=e[e.length-1],n=0;n<e.length-1;++n)r+=this.strides[n]*e[n];return this.dataSync()[r]},e.prototype.buffer=function(){return deprecationWarningFn("Tensor.buffer() is renamed to Tensor.bufferSync() in TensorFlow.js 1.0 and Tensor.buffer() will become an async function."),opHandler.buffer(this.shape,this.dtype,this.dataSync())},e.prototype.bufferSync=function(){return opHandler.buffer(this.shape,this.dtype,this.dataSync())},e.prototype.array=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(r){switch(r.label){case 0:return e=toNestedArray,t=[this.shape],[4,this.data()];case 1:return[2,e.apply(void 0,t.concat([r.sent()]))]}})})},e.prototype.arraySync=function(){return toNestedArray(this.shape,this.dataSync())},e.prototype.data=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.throwIfDisposed(),[2,trackerFn().read(this.dataId)]})})},e.prototype.dataSync=function(){return this.throwIfDisposed(),trackerFn().readSync(this.dataId)},e.prototype.dispose=function(){this.isDisposed||(trackerFn().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),e.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},e.prototype.toFloat=function(){return this.asType("float32")},e.prototype.toInt=function(){return this.asType("int32")},e.prototype.toBool=function(){return this.asType("bool")},e.prototype.print=function(e){return void 0===e&&(e=!1),opHandler.print(this,e)},e.prototype.reshape=function(e){return this.throwIfDisposed(),opHandler.reshape(this,e)},e.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape)},e.prototype.expandDims=function(e){return void 0===e&&(e=0),opHandler.expandDims(this,e)},e.prototype.cumsum=function(e,t,r){return void 0===e&&(e=0),void 0===t&&(t=!1),void 0===r&&(r=!1),opHandler.cumsum(this,e,t,r)},e.prototype.squeeze=function(e){return this.throwIfDisposed(),opHandler.squeeze(this,e)},e.prototype.clone=function(){return this.throwIfDisposed(),opHandler.clone(this)},e.prototype.oneHot=function(e,t,r){return this.throwIfDisposed(),opHandler.oneHot(this,e,t,r)},e.prototype.toString=function(e){return void 0===e&&(e=!1),tensorToString(this.dataSync(),this.shape,this.dtype,e)},e.prototype.tile=function(e){return this.throwIfDisposed(),opHandler.tile(this,e)},e.prototype.gather=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),opHandler.gather(this,e,t)},e.prototype.matMul=function(e,t,r){return void 0===t&&(t=!1),void 0===r&&(r=!1),this.throwIfDisposed(),opHandler.matMul(this,e,t,r)},e.prototype.dot=function(e){return this.throwIfDisposed(),opHandler.dot(this,e)},e.prototype.norm=function(e,t,r){return void 0===e&&(e="euclidean"),void 0===t&&(t=null),void 0===r&&(r=!1),this.throwIfDisposed(),opHandler.norm(this,e,t,r)},e.prototype.slice=function(e,t){return this.throwIfDisposed(),opHandler.slice(this,e,t)},e.prototype.reverse=function(e){return this.throwIfDisposed(),opHandler.reverse(this,e)},e.prototype.concat=function(t,r){return void 0===r&&(r=0),this.throwIfDisposed(),t instanceof e&&(t=[t]),opHandler.concat([this].concat(t),r)},e.prototype.split=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),opHandler.split(this,e,t)},e.prototype.stack=function(e,t){return void 0===t&&(t=0),opHandler.stack([this,e],t)},e.prototype.unstack=function(e){return void 0===e&&(e=0),opHandler.unstack(this,e)},e.prototype.pad=function(e,t){return void 0===t&&(t=0),opHandler.pad(this,e,t)},e.prototype.batchNormalization=function(e,t,r,n,a){return void 0===r&&(r=.001),deprecationWarningFn("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(e,t,a,n,r)},e.prototype.batchNorm=function(e,t,r,n,a){return void 0===a&&(a=.001),this.throwIfDisposed(),opHandler.batchNorm(this,e,t,r,n,a)},e.prototype.all=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.all(this,e,t)},e.prototype.any=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.any(this,e,t)},e.prototype.logSumExp=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.logSumExp(this,e,t)},e.prototype.sum=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.sum(this,e,t)},e.prototype.prod=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.prod(this,e,t)},e.prototype.mean=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.mean(this,e,t)},e.prototype.min=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.min(this,e,t)},e.prototype.max=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.max(this,e,t)},e.prototype.argMin=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),opHandler.argMin(this,e)},e.prototype.argMax=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),opHandler.argMax(this,e)},e.prototype.cast=function(e){return this.throwIfDisposed(),opHandler.cast(this,e)},e.prototype.add=function(e){return this.throwIfDisposed(),opHandler.add(this,e)},e.prototype.addStrict=function(e){return this.throwIfDisposed(),opHandler.addStrict(this,e)},e.prototype.atan2=function(e){return this.throwIfDisposed(),opHandler.atan2(this,e)},e.prototype.sub=function(e){return this.throwIfDisposed(),opHandler.sub(this,e)},e.prototype.subStrict=function(e){return this.throwIfDisposed(),opHandler.subStrict(this,e)},e.prototype.pow=function(e){return this.throwIfDisposed(),opHandler.pow(this,e)},e.prototype.powStrict=function(e){return this.throwIfDisposed(),opHandler.powStrict(this,e)},e.prototype.mul=function(e){return this.throwIfDisposed(),opHandler.mul(this,e)},e.prototype.mulStrict=function(e){return this.throwIfDisposed(),opHandler.mulStrict(this,e)},e.prototype.div=function(e){return this.throwIfDisposed(),opHandler.div(this,e)},e.prototype.floorDiv=function(e){return this.throwIfDisposed(),opHandler.floorDiv(this,e)},e.prototype.divStrict=function(e){return this.throwIfDisposed(),opHandler.divStrict(this,e)},e.prototype.minimum=function(e){return this.throwIfDisposed(),opHandler.minimum(this,e)},e.prototype.minimumStrict=function(e){return this.throwIfDisposed(),opHandler.minimumStrict(this,e)},e.prototype.maximum=function(e){return this.throwIfDisposed(),opHandler.maximum(this,e)},e.prototype.maximumStrict=function(e){return this.throwIfDisposed(),opHandler.maximumStrict(this,e)},e.prototype.mod=function(e){return this.throwIfDisposed(),opHandler.mod(this,e)},e.prototype.modStrict=function(e){return this.throwIfDisposed(),opHandler.modStrict(this,e)},e.prototype.squaredDifference=function(e){return this.throwIfDisposed(),opHandler.squaredDifference(this,e)},e.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),opHandler.squaredDifferenceStrict(this,e)},e.prototype.transpose=function(e){return this.throwIfDisposed(),opHandler.transpose(this,e)},e.prototype.notEqual=function(e){return this.throwIfDisposed(),opHandler.notEqual(this,e)},e.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),opHandler.notEqualStrict(this,e)},e.prototype.less=function(e){return this.throwIfDisposed(),opHandler.less(this,e)},e.prototype.lessStrict=function(e){return this.throwIfDisposed(),opHandler.lessStrict(this,e)},e.prototype.equal=function(e){return this.throwIfDisposed(),opHandler.equal(this,e)},e.prototype.equalStrict=function(e){return this.throwIfDisposed(),opHandler.equalStrict(this,e)},e.prototype.lessEqual=function(e){return this.throwIfDisposed(),opHandler.lessEqual(this,e)},e.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),opHandler.lessEqualStrict(this,e)},e.prototype.greater=function(e){return this.throwIfDisposed(),opHandler.greater(this,e)},e.prototype.greaterStrict=function(e){return this.throwIfDisposed(),opHandler.greaterStrict(this,e)},e.prototype.greaterEqual=function(e){return this.throwIfDisposed(),opHandler.greaterEqual(this,e)},e.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),opHandler.greaterEqualStrict(this,e)},e.prototype.logicalAnd=function(e){return this.throwIfDisposed(),opHandler.logicalAnd(this,e)},e.prototype.logicalOr=function(e){return this.throwIfDisposed(),opHandler.logicalOr(this,e)},e.prototype.logicalNot=function(){return this.throwIfDisposed(),opHandler.logicalNot(this)},e.prototype.logicalXor=function(e){return this.throwIfDisposed(),opHandler.logicalXor(this,e)},e.prototype.where=function(e,t){return this.throwIfDisposed(),opHandler.where(e,this,t)},e.prototype.neg=function(){return this.throwIfDisposed(),opHandler.neg(this)},e.prototype.ceil=function(){return this.throwIfDisposed(),opHandler.ceil(this)},e.prototype.floor=function(){return this.throwIfDisposed(),opHandler.floor(this)},e.prototype.sign=function(){return this.throwIfDisposed(),opHandler.sign(this)},e.prototype.exp=function(){return this.throwIfDisposed(),opHandler.exp(this)},e.prototype.expm1=function(){return this.throwIfDisposed(),opHandler.expm1(this)},e.prototype.log=function(){return this.throwIfDisposed(),opHandler.log(this)},e.prototype.log1p=function(){return this.throwIfDisposed(),opHandler.log1p(this)},e.prototype.sqrt=function(){return this.throwIfDisposed(),opHandler.sqrt(this)},e.prototype.rsqrt=function(){return this.throwIfDisposed(),opHandler.rsqrt(this)},e.prototype.square=function(){return this.throwIfDisposed(),opHandler.square(this)},e.prototype.reciprocal=function(){return this.throwIfDisposed(),opHandler.reciprocal(this)},e.prototype.abs=function(){return this.throwIfDisposed(),opHandler.abs(this)},e.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),opHandler.clipByValue(this,e,t)},e.prototype.relu=function(){return this.throwIfDisposed(),opHandler.relu(this)},e.prototype.elu=function(){return this.throwIfDisposed(),opHandler.elu(this)},e.prototype.selu=function(){return this.throwIfDisposed(),opHandler.selu(this)},e.prototype.leakyRelu=function(e){return void 0===e&&(e=.2),this.throwIfDisposed(),opHandler.leakyRelu(this,e)},e.prototype.prelu=function(e){return this.throwIfDisposed(),opHandler.prelu(this,e)},e.prototype.sigmoid=function(){return this.throwIfDisposed(),opHandler.sigmoid(this)},e.prototype.logSigmoid=function(){return this.throwIfDisposed(),opHandler.logSigmoid(this)},e.prototype.softplus=function(){return this.throwIfDisposed(),opHandler.softplus(this)},e.prototype.zerosLike=function(){return this.throwIfDisposed(),opHandler.zerosLike(this)},e.prototype.onesLike=function(){return this.throwIfDisposed(),opHandler.onesLike(this)},e.prototype.sin=function(){return this.throwIfDisposed(),opHandler.sin(this)},e.prototype.cos=function(){return this.throwIfDisposed(),opHandler.cos(this)},e.prototype.tan=function(){return this.throwIfDisposed(),opHandler.tan(this)},e.prototype.asin=function(){return this.throwIfDisposed(),opHandler.asin(this)},e.prototype.acos=function(){return this.throwIfDisposed(),opHandler.acos(this)},e.prototype.atan=function(){return this.throwIfDisposed(),opHandler.atan(this)},e.prototype.sinh=function(){return this.throwIfDisposed(),opHandler.sinh(this)},e.prototype.cosh=function(){return this.throwIfDisposed(),opHandler.cosh(this)},e.prototype.tanh=function(){return this.throwIfDisposed(),opHandler.tanh(this)},e.prototype.asinh=function(){return this.throwIfDisposed(),opHandler.asinh(this)},e.prototype.acosh=function(){return this.throwIfDisposed(),opHandler.acosh(this)},e.prototype.atanh=function(){return this.throwIfDisposed(),opHandler.atanh(this)},e.prototype.erf=function(){return this.throwIfDisposed(),opHandler.erf(this)},e.prototype.round=function(){return this.throwIfDisposed(),opHandler.round(this)},e.prototype.step=function(e){return void 0===e&&(e=0),this.throwIfDisposed(),opHandler.step(this,e)},e.prototype.softmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),opHandler.softmax(this,e)},e.prototype.logSoftmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),opHandler.logSoftmax(this,e)},e.prototype.resizeBilinear=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.image.resizeBilinear(this,e,t)},e.prototype.resizeNearestNeighbor=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),opHandler.image.resizeNearestNeighbor(this,e,t)},e.prototype.conv1d=function(e,t,r,n,a,o){return void 0===n&&(n="NWC"),void 0===a&&(a=1),this.throwIfDisposed(),opHandler.conv1d(this,e,t,r,n,a,o)},e.prototype.conv2d=function(e,t,r,n,a,o){return void 0===n&&(n="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),opHandler.conv2d(this,e,t,r,n,a,o)},e.prototype.conv2dTranspose=function(e,t,r,n,a){return this.throwIfDisposed(),opHandler.conv2dTranspose(this,e,t,r,n,a)},e.prototype.depthwiseConv2D=function(e,t,r,n,a,o){return void 0===n&&(n="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),opHandler.depthwiseConv2d(this,e,t,r,n,a,o)},e.prototype.separableConv2d=function(e,t,r,n,a,o){return void 0===a&&(a=[1,1]),void 0===o&&(o="NHWC"),this.throwIfDisposed(),opHandler.separableConv2d(this,e,t,r,n,a,o)},e.prototype.avgPool=function(e,t,r,n){return this.throwIfDisposed(),opHandler.avgPool(this,e,t,r,n)},e.prototype.maxPool=function(e,t,r,n){return this.throwIfDisposed(),opHandler.maxPool(this,e,t,r,n)},e.prototype.localResponseNormalization=function(e,t,r,n){return void 0===e&&(e=5),void 0===t&&(t=1),void 0===r&&(r=1),void 0===n&&(n=.5),opHandler.localResponseNormalization(this,e,t,r,n)},e.prototype.pool=function(e,t,r,n,a){return this.throwIfDisposed(),opHandler.pool(this,e,t,r,n,a)},e.prototype.variable=function(e,t,r){return void 0===e&&(e=!0),this.throwIfDisposed(),Variable.variable(this,e,t,r)},e.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),opHandler.unsortedSegmentSum(this,e,t)},e.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),opHandler.batchToSpaceND(this,e,t)},e.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),opHandler.spaceToBatchND(this,e,t)},e.prototype.topk=function(e,t){return void 0===e&&(e=1),void 0===t&&(t=!0),this.throwIfDisposed(),opHandler.topk(this,e,t)},e.prototype.stridedSlice=function(e,t,r,n,a,o,i,s){return void 0===n&&(n=0),void 0===a&&(a=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),opHandler.stridedSlice(this,e,t,r,n,a,o,i,s)},e.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),opHandler.depthToSpace(this,e,t)},e.prototype.fft=function(){return this.throwIfDisposed(),opHandler.spectral.fft(this)},e.prototype.ifft=function(){return this.throwIfDisposed(),opHandler.spectral.ifft(this)},e.prototype.rfft=function(){return this.throwIfDisposed(),opHandler.spectral.rfft(this)},e.prototype.irfft=function(){return this.throwIfDisposed(),opHandler.spectral.irfft(this)},e}();Object.defineProperty(Tensor,Symbol.hasInstance,{value:function(e){return!!e&&null!=e.dataId&&null!=e.shape&&null!=e.dtype}});var Variable=function(e){function t(t,r,n){void 0===r&&(r=!0);var a=e.call(this,t.shape,t.dtype,null,t.dataId)||this;a.trainable=r,a.name=n,null==a.name&&(a.name=trackerFn().nextVariableId().toString());try{trackerFn().registerVariable(a)}catch(e){throw trackerFn().disposeTensor(a),e}return a}return __extends(t,e),t.variable=function(e,r,n,a){return void 0===r&&(r=!0),null!=a&&a!==e.dtype&&(e=e.asType(a)),new t(e,r,n)},t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!arraysEqual(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");trackerFn().disposeTensor(this),this.dataId=e.dataId,trackerFn().registerTensor(this)},t}(Tensor);Object.defineProperty(Variable,Symbol.hasInstance,{value:function(e){return e instanceof Tensor&&null!=e.assign&&e.assign instanceof Function}});var UpcastInt32AndMap,UpcastBoolAndMap,UpcastFloat32AndMap,UpcastComplex64AndMap,variable=Variable.variable,e;function getFilteredNodesXToY(e,t,r){for(var n={},a={},o=0;o<t.length;o++)n[t[o].id]=!0;for(o=0;o<e.length;o++){var i=(f=e[o]).inputs;for(var s in i){for(var u=i[s],l=!1,p=0;p<t.length;p++)if(n[u.id]){f.outputs.forEach(function(e){return n[e.id]=!0}),l=!0,a[f.id]=!0;break}if(l)break}}var c={};c[r.id]=!0;var h={};for(o=e.length-1;o>=0;o--)for(i=(f=e[o]).inputs,p=0;p<f.outputs.length;p++)if(c[f.outputs[p].id]){for(var s in i)c[i[s].id]=!0,h[f.id]=!0;break}var d=[];for(o=0;o<e.length;o++){var f;if(a[(f=e[o]).id]&&h[f.id]){var m={};for(var s in f.inputs){var g=f.inputs[s];n[g.id]&&(m[s]=g)}var y=Object.assign({},f);y.inputs=m,y.outputs=f.outputs,d.push(y)}}return d}function backpropagateGradients(e,t){for(var r=function(r){var n=t[r],a=[];if(n.outputs.forEach(function(t){var r=e[t.id];if(null!=r)a.push(r);else{var n=Tensor.make(t.shape,{values:makeZerosTypedArray(t.size,t.dtype)},t.dtype);a.push(n)}}),null==n.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+n.name+".");var o=n.gradient(1===n.outputs.length?a[0]:a);for(var i in n.inputs){if(!(i in o))throw new Error("Cannot backprop through input "+i+". Available gradients found: "+Object.keys(o)+".");var s=o[i]();if("float32"!==s.dtype)throw new Error("Error in gradient for op "+n.name+". The gradient of input "+i+" must have 'float32' dtype, but has '"+s.dtype+"'");var u=n.inputs[i];if(!arraysEqual(s.shape,u.shape))throw new Error("Error in gradient for op "+n.name+". The gradient of input '"+i+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}},n=t.length-1;n>=0;n--)r(n)}e=exports.Rank||(exports.Rank={}),e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(UpcastInt32AndMap||(UpcastInt32AndMap={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(UpcastBoolAndMap||(UpcastBoolAndMap={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(UpcastFloat32AndMap||(UpcastFloat32AndMap={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(UpcastComplex64AndMap||(UpcastComplex64AndMap={}));var upcastTypeMap={float32:UpcastFloat32AndMap,int32:UpcastInt32AndMap,bool:UpcastBoolAndMap,complex64:UpcastComplex64AndMap};function upcastType(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error("Can not upcast "+e+" with "+t)}return upcastTypeMap[e][t]}function sumOutType(e){return upcastType(e,"int32")}function makeTypesMatch(e,t){if(e.dtype===t.dtype)return[e,t];var r=upcastType(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function assertTypesMatch(e,t){assert(e.dtype===t.dtype,"The dtypes of the first("+e.dtype+") and second("+t.dtype+") input must match")}function isTensorInList(e,t){for(var r=0;r<t.length;r++)if(t[r].id===e.id)return!0;return!1}function getTensorsInContainer(e){var t=[];return walkTensorContainer(e,t,new Set),t}function walkTensorContainer(e,t,r){if(null!=e)if(e instanceof Tensor)t.push(e);else if(isIterable(e)){var n=e;for(var a in n){var o=n[a];r.has(o)||(r.add(o),walkTensorContainer(o,t,r))}}}function isIterable(e){return Array.isArray(e)||"object"==typeof e}var Type,Engine=function(){function e(e,t,r){this.backend=e,this.safeMode=t,this.debugMode=r,this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.profiling=!1,this.gradientScopeCount=0,this.customGradientDepth=0,this.scopeStack=[],this.keepTensors=new Set,this.tensorInfo=new WeakMap,this.profiler=new Profiler(e),this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return e.prototype.moveData=function(e){this.write(e,this.readSync(e))},e.prototype.tidy=function(e,t,r){var n=this;void 0===r&&(r=!1);var a,o=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=e}return this.scopedRun(function(){return n.startScope(o,r)},function(){return n.endScope(a,r)},function(){return(a=t())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a})},e.prototype.scopedRun=function(e,t,r){e();try{var n=r();return t(),n}catch(e){throw t(),e}},e.prototype.nextTensorId=function(){return e.nextTensorId++},e.prototype.nextVariableId=function(){return e.nextVariableId++},e.prototype.runKernel=function(e,t,r){var n,a=this,o=[],i=function(e){return o.push(e),e},s=null!=this.activeScope?this.activeScope.name:"",u=this.numBytes,l=this.numTensors;if(this.scopedRun(function(){return a.customGradientDepth++},function(){return a.customGradientDepth--},function(){n=a.debugMode()?a.profiler.profileKernel(s,function(){return e(a.backend,i)}):e(a.backend,i)}),this.shouldRecord()){var p={id:this.nextTapeNodeId++,name:s,inputs:t,outputs:Array.isArray(n)?n:[n]};null!=r&&(p.gradient=function(e){return r(e,o)}),this.activeTape.push(p)}return this.profiling&&this.activeProfile.kernels.push({name:s,bytesAdded:this.numBytes-u,totalBytesSnapshot:this.numBytes,tensorsAdded:this.numTensors-l,totalTensorsSnapshot:this.numTensors,inputShapes:Object.keys(t).map(function(e){return t[e].shape}),outputShape:Array.isArray(n)?n.map(function(e){return e.shape}):n.shape}),n},e.prototype.registerTensor=function(e){var t=this.tensorInfo.has(e.dataId)?this.tensorInfo.get(e.dataId).refCount:0;if(this.numTensors++,"string"===e.dtype&&this.numStringTensors++,0===t){this.numDataBuffers++;var r=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(r=sizeFromShape(e.shape)*bytesPerElement(e.dtype)),this.tensorInfo.set(e.dataId,{backend:this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.numBytes+=r,this.backend.register(e.dataId,e.shape,e.dtype)}this.tensorInfo.get(e.dataId).refCount++,e instanceof Variable||this.track(e)},e.prototype.registerVariable=function(e){if(null!=this.registeredVariables[e.name])throw new Error("Variable with name "+e.name+" was already registered");this.registeredVariables[e.name]=e},e.prototype.disposeTensor=function(e){if(this.tensorInfo.has(e.dataId)){this.keepTensors.has(e.id)&&this.keepTensors.delete(e.id),this.numTensors--,"string"===e.dtype&&this.numStringTensors--;var t=this.tensorInfo.get(e.dataId);t.refCount<=1?("complex64"!==e.dtype&&(this.numBytes-=t.bytes),this.numDataBuffers--,t.backend.disposeData(e.dataId),this.tensorInfo.delete(e.dataId)):this.tensorInfo.get(e.dataId).refCount--}},e.prototype.disposeVariables=function(){for(var e in this.registeredVariables){var t=this.registeredVariables[e];this.disposeTensor(t),delete this.registeredVariables[e]}},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.numTensors,e.numDataBuffers=this.numDataBuffers,e.numBytes=this.numBytes,this.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},e.prototype.profile=function(e){return __awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(n){return this.profiling=!0,t=this.numBytes,r=this.numTensors,this.activeProfile.kernels=[],this.activeProfile.result=e(),this.profiling=!1,this.activeProfile.peakBytes=Math.max.apply(Math,this.activeProfile.kernels.map(function(e){return e.totalBytesSnapshot})),this.activeProfile.newBytes=this.numBytes-t,this.activeProfile.newTensors=this.numTensors-r,[2,this.activeProfile]})})},e.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},e.prototype.addTapeNode=function(e,t,r){var n={};e.forEach(function(e,t){n[t]=e});var a={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:n,outputs:[t],gradient:function(e){var t={};return r(e).forEach(function(e,r){t[r]=function(){return e}}),t}};this.activeTape.push(a)},e.prototype.keep=function(e){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var r={track:[],name:"unnamed scope"};e&&(r.name=e),this.scopeStack.push(r),this.activeScope=r},e.prototype.endScope=function(e,t){var r=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var n=new Set(this.keepTensors),a=getTensorsInContainer(e);a.forEach(function(e){return n.add(e.id)});for(var o=0;o<this.activeScope.track.length;o++){var i=this.activeScope.track[o];n.has(i.id)||(null!=this.activeTape?a.push(i):i.dispose())}var s=this.scopeStack.pop();this.activeScope=0===this.scopeStack.length?null:this.scopeStack[this.scopeStack.length-1],a.forEach(function(e){!r.keepTensors.has(e.id)&&isTensorInList(e,s.track)&&r.track(e)})},e.prototype.gradients=function(e,t,r,n){var a=this;if(void 0===n&&(n=!1),assert(t.length>0,"gradients() received an empty list of xs."),null!=r&&"float32"!==r.dtype)throw new Error("dy must have 'float32' dtype, but has '"+r.dtype+"'");return this.tidy("gradients",function(){var o=e();assert(o instanceof Tensor,"The result y returned by f() must be a tensor.");var i=getFilteredNodesXToY(a.activeTape,t,o);if(!n&&0===i.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var s={};return s[o.id]=null==r?ones(o.shape):r,backpropagateGradients(s,i),{value:o,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return assert(isFunction(e),"The f passed in customGrad(f) must be a function."),function(){for(var r,n,a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];return assert(a.every(function(e){return e instanceof Tensor}),"The args passed in customGrad(f)(x1, x2,...) must all be tensors"),t.scopedRun(function(){return t.customGradientDepth++},function(){return t.customGradientDepth--},function(){n=t.tidy(e.name,function(){var t=e.apply(void 0,a),n=t.value,o=t.gradFunc;return assert(n instanceof Tensor,"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),assert(isFunction(o),"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r=o,n},!0)}),t.shouldRecord()&&t.addTapeNode(a,n,function(e){var t=r(e),n=Array.isArray(t)?t:[t];return assert(n.length===a.length,"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),assert(n.every(function(e){return e instanceof Tensor}),"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."),n}),n}},e.prototype.write=function(e,t){var r=this.tensorInfo.get(e);if("string"===r.dtype){var n=bytesFromStringArray(t);this.numBytes+=n-r.bytes,r.bytes=n}this.backend!==r.backend&&(r.backend.disposeData(e),r.backend=this.backend,this.backend.register(e,r.shape,r.dtype)),this.backend.write(e,t)},e.prototype.readSync=function(e){return this.tensorInfo.get(e).backend.readSync(e)},e.prototype.read=function(e){return this.tensorInfo.get(e).backend.read(e)},e.prototype.fromPixels=function(e,t){return this.backend.fromPixels(e,t)},e.prototype.time=function(e){return __awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(n){switch(n.label){case 0:return t=now(),[4,this.backend.time(e)];case 1:return(r=n.sent()).wallMs=now()-t,[2,r]}})})},e.prototype.track=function(e){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {op();...}); to avoid memory leaks.");return null!=this.activeScope&&this.activeScope.track.push(e),e},e.nextTensorId=0,e.nextVariableId=0,e}();function ones(e){var t=makeOnesTypedArray(sizeFromShape(e),"float32");return Tensor.make(e,{values:t})}!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(Type||(Type={}));var MAX_TEXTURE_SIZE,MAX_TEXTURES_IN_SHADER,URL_PROPERTIES=[{name:"DEBUG",type:Type.BOOLEAN},{name:"IS_BROWSER",type:Type.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:Type.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:Type.BOOLEAN},{name:"WEBGL_PACK",type:Type.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:Type.BOOLEAN},{name:"WEBGL_PACK_CLIP",type:Type.BOOLEAN},{name:"WEBGL_PACK_DEPTHWISECONV",type:Type.BOOLEAN},{name:"WEBGL_PACK_BINARY_OPERATIONS",type:Type.BOOLEAN},{name:"WEBGL_PACK_ARRAY_OPERATIONS",type:Type.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:Ty