@tensorflow/tfjs-core
Version:
Hardware-accelerated JavaScript library for machine intelligence
17 lines • 373 kB
JavaScript
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e};function __awaiter(e,t,n,r){return new(n||(n=Promise))(function(o,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function s(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(i,s)}u((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}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,n=0,r=0;t>0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function clamp(e,t,n){return Math.max(e,Math.min(t,n))}function randUniform(e,t){return Math.random()*(t-e)+e}function distSquared(e,t){for(var n=0,r=0;r<e.length;r++){var o=Number(e[r])-Number(t[r]);n+=o*o}return n}function assert(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function assertShapesMatch(e,t,n){void 0===n&&(n=""),assert(arraysEqual(e,t),n+" 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))for(var n=0;n<e.length;++n)flatten(e[n],t);else t.push(e);return t}function inferShape(e){var t=e;if(isTypedArray(e))return[e.length];if(!Array.isArray(e))return[];for(var n=[];t instanceof Array;)n.push(t.length),t=t[0];return e instanceof Array&&deepAssertShapeConsistency(e,n,[]),n}function deepAssertShapeConsistency(e,t,n){if(n=n||[],e instanceof Array){assert(t.length>0,function(){return"Element arr["+n.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),assert(e.length===t[0],function(){return"Element arr["+n.join("][")+"] should have "+t[0]+" elements, but has "+e.length+" elements"});for(var r=t.slice(1),o=0;o<e.length;++o)deepAssertShapeConsistency(e[o],r,n.concat(o))}else assert(0===t.length,function(){return"Element arr["+n.join("][")+"] is a primitive, but should be an array of "+t[0]+" elements"})}function sizeFromShape(e){if(0===e.length)return 1;for(var t=e[0],n=1;n<e.length;n++)t*=e[n];return t}function isScalarShape(e){return 0===e.length}function arraysEqual(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])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){for(var t=Math.floor(Math.sqrt(e));t>1;--t)if(e%t==0)return[t,e/t];return[1,e]}function createShuffledIndices(e){for(var t=new Uint32Array(e),n=0;n<e;++n)t[n]=n;return shuffle(t),t}function rightPad(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function repeatedTry(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise(function(r,o){var a=0,i=function(){if(e())r();else{var s=t(++a);null!=n&&a>=n?o():setTimeout(i,s)}};i()})}function inferFromImplicitShape(e,t){for(var n=1,r=-1,o=0;o<e.length;++o)if(e[o]>=0)n*=e[o];else if(-1===e[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(e[o]<0)throw Error("Shapes can not be < 0. Found "+e[o]+" at dim "+o);if(-1===r){if(t>0&&t!==n)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===n)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+n);var a=e.slice();return a[r]=t/n,a}function squeezeShape(e,t){for(var n=[],r=[],o=0,a=0;a<e.length;++a){if(null!=t){if(t[o]===a&&1!==e[a])throw new Error("Can't squeeze axis "+a+" since its dim '"+e[a]+"' is not 1");(null==t[o]||t[o]>a)&&1===e[a]&&(n.push(e[a]),r.push(a)),t[o]<=a&&o++}1!==e[a]&&(n.push(e[a]),r.push(a))}return{newShape:n,keptDims:r}}function getTypedArrayFromDType(e,t){var n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t)}return n}function checkComputationForNaN(e,t,n){if("float32"===t)for(var r=0;r<e.length;r++)if(isNaN(e[r]))throw Error("The result of the '"+n+"' has NaNs.")}function checkConversionForNaN(e,t){if("float32"!==t)for(var n=0;n<e.length;n++)if(isNaN(e[n]))throw Error("NaN is not a valid value for dtype: '"+t+"'.")}function hasEncodingLoss(e,t){return"float32"!==t&&(("int32"!==t||"float32"===e)&&("bool"!==t||"bool"!==e))}function copyTypedArray(e,t,n){if(null==t||"float32"===t)return new Float32Array(e);if("int32"===t)return n&&checkConversionForNaN(e,t),new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),o=0;o<r.length;++o)0!==Math.round(e[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+t)}function isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function bytesPerElement(e){if("float32"===e||"int32"===e)return 4;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)}function nearestDivisor(e,t){for(var n=t;n<e;++n)if(e%n==0)return n;return e}function computeStrides(e){var t=e.length;if(t<2)return[];var n=new Array(t-1);n[t-2]=e[t-1];for(var r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function toTypedArray(e,t,n){return noConversionNeeded(e,t)?e:(Array.isArray(e)&&(e=flatten(e)),copyTypedArray(e,t,n))}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 n=makeZerosTypedArray(e,t),r=0;r<n.length;r++)n[r]=1;return n}function makeZerosTypedArray(e,t){if(null==t||"float32"===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("Can not measure time in this environment. You should run tf.js in the browser or in Node.js")}var util=Object.freeze({shuffle:shuffle,clamp:clamp,randUniform:randUniform,distSquared:distSquared,assert:assert,assertShapesMatch:assertShapesMatch,assertNonNull:assertNonNull,flatten:flatten,inferShape:inferShape,sizeFromShape:sizeFromShape,isScalarShape:isScalarShape,arraysEqual:arraysEqual,isInt:isInt,tanh:tanh,sizeToSquarishShape:sizeToSquarishShape,createShuffledIndices:createShuffledIndices,rightPad:rightPad,repeatedTry:repeatedTry,inferFromImplicitShape:inferFromImplicitShape,squeezeShape:squeezeShape,getTypedArrayFromDType:getTypedArrayFromDType,checkComputationForNaN:checkComputationForNaN,checkConversionForNaN:checkConversionForNaN,hasEncodingLoss:hasEncodingLoss,isTypedArray:isTypedArray,bytesPerElement:bytesPerElement,isFunction:isFunction,nearestDivisor:nearestDivisor,computeStrides:computeStrides,toTypedArray:toTypedArray,makeOnesTypedArray:makeOnesTypedArray,makeZerosTypedArray:makeZerosTypedArray,now:now}),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 n,r=this,o=this.backendTimer.time(function(){n=t()});return(Array.isArray(n)?n:[n]).forEach(function(t){var n=t.dataSync();checkComputationForNaN(n,t.dtype,e),o.then(function(o){r.logger.logKernelProfile(e,t,n,o.kernelMs)})}),n},e}(),Logger=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,n,r){var o=rightPad(r+"ms",9),a=rightPad(e,25),i=t.rank,s=t.size,u=rightPad(t.shape.toString(),14);console.log("%c"+a+"\t%c"+o+"\t%c"+i+"D "+u+"\t%c"+s,"font-weight:bold","color:red","color:blue","color: orange")},e}();function getFilteredNodesXToY(e,t,n){for(var r={},o={},a=0;a<t.length;a++)r[t[a].id]=!0;for(a=0;a<e.length;a++){var i=(m=e[a]).inputs;for(var s in i){for(var u=i[s],l=!1,c=0;c<t.length;c++)if(r[u.id]){r[m.output.id]=!0,l=!0,o[m.id]=!0;break}if(l)break}}var p={};p[n.id]=!0;var d={};for(a=e.length-1;a>=0;a--){i=(m=e[a]).inputs;var h=[];h.push(m.output);for(c=0;c<h.length;c++)if(p[h[c].id]){for(var s in i)p[i[s].id]=!0,d[m.id]=!0;break}}var f=[];for(a=0;a<e.length;a++){var m;if(o[(m=e[a]).id]&&d[m.id]){var g={};for(var s in m.inputs){var v=m.inputs[s];r[v.id]&&(g[s]=v)}var y=Object.assign({},m);y.inputs=g,y.output=m.output,f.push(y)}}return f}function backpropagateGradients(e,t){for(var n=t.length-1;n>=0;n--){var r=t[n],o=e[r.output.id];if(null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var a=r.gradient(o);for(var i in r.inputs){if(!(i in a))throw new Error("Cannot backprop through input "+i+". Available gradients found: "+Object.keys(a)+".");var s=a[i](),u=r.inputs[i];if(!arraysEqual(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+i+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}}}var FORMAT_LIMIT_NUM_VALS=20,FORMAT_NUM_FIRST_LAST_VALS=3,FORMAT_NUM_SIG_DIGITS=7;function tensorToString(e,t,n,r){var o=computeStrides(t),a=computeMaxSizePerColumn(e,t,o),i=t.length,s=subTensorToString(e,t,o,a),u=["Tensor"];return r&&(u.push(" dtype: "+n),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,n){var r=sizeFromShape(t),o=n[n.length-1],a=new Array(o).fill(0);if(t.length>1)for(var i=0;i<r/o;i++)for(var s=i*o,u=0;u<o;u++)a[u]=Math.max(a[u],valToString(e[s+u],0).length);return a}function valToString(e,t){return rightPad(parseFloat(e.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(),t)}function subTensorToString(e,t,n,r,o){void 0===o&&(o=!0);var a=t[0],i=t.length;if(0===i)return[e[0].toString()];if(1===i){if(a>FORMAT_LIMIT_NUM_VALS){var s=Array.from(e.subarray(0,FORMAT_NUM_FIRST_LAST_VALS)),u=Array.from(e.subarray(a-FORMAT_NUM_FIRST_LAST_VALS,a));return["["+s.map(function(e,t){return valToString(e,r[t])}).join(", ")+", ..., "+u.map(function(e,t){return valToString(e,r[a-FORMAT_NUM_FIRST_LAST_VALS+t])}).join(", ")+"]"]}return["["+Array.from(e).map(function(e,t){return valToString(e,r[t])}).join(", ")+"]"]}var l=t.slice(1),c=n.slice(1),p=n[0],d=[];if(a>FORMAT_LIMIT_NUM_VALS){for(var h=0;h<FORMAT_NUM_FIRST_LAST_VALS;h++){var f=(m=h*p)+p;d.push.apply(d,subTensorToString(e.subarray(m,f),l,c,r,!1))}d.push("...");for(h=a-FORMAT_NUM_FIRST_LAST_VALS;h<a;h++){f=(m=h*p)+p;d.push.apply(d,subTensorToString(e.subarray(m,f),l,c,r,h===a-1))}}else for(h=0;h<a;h++){var m;f=(m=h*p)+p;d.push.apply(d,subTensorToString(e.subarray(m,f),l,c,r,h===a-1))}var g=2===i?",":"";d[0]="["+d[0]+g;for(h=1;h<d.length-1;h++)d[h]=" "+d[h]+g;var v=",\n";for(h=2;h<i;h++)v+="\n";return d[d.length-1]=" "+d[d.length-1]+"]"+(o?"":v),d}var TensorBuffer=function(){function e(e,t,n){if(this.dtype=t,null!=n){var r=n.length,o=sizeFromShape(e);assert(r===o,"Length of values '"+r+"' does not match the size inferred by the shape '"+o+"'")}this.shape=e.slice(),this.values=n||getTypedArrayFromDType(t,sizeFromShape(e)),this.strides=computeStrides(e),this.size=sizeFromShape(e)}return e.prototype.set=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];0===t.length&&(t=[0]),assert(t.length===this.rank,"The number of provided coordinates ("+t.length+") must match the rank ("+this.rank+")");var r=this.locToIndex(t);this.values[r]=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 n=e[e.length-1],r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]},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],n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];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),n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];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;function setTensorTracker(e){trackerFn=e}function setOpHandler(e){opHandler=e}var Tensor=function(){function e(t,n,r,o){this.isDisposedInternal=!1,this.size=sizeFromShape(t),null!=r&&assert(this.size===r.length,"Based on the provided shape, ["+t+"], the tensor should have "+this.size+" values but has "+r.length),this.shape=t.slice(),this.dtype=n||"float32",this.strides=computeStrides(t),this.dataId=null!=o?o:{},this.id=e.nextId++,this.rankType=this.rank<5?this.rank.toString():"higher",trackerFn().registerTensor(this),null!=r&&trackerFn().write(this.dataId,r)}return e.make=function(t,n,r){return new e(t,r,n.values,n.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,n){return this.throwIfDisposed(),this.reshape([e,t,n])},e.prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),this.reshape([e,t,n,r])},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];assert(e.length===this.rank,"Number of coordinates in get() must match the rank of the tensor"),this.throwIfDisposed(),0===e.length&&(e=[0]);for(var n=e[e.length-1],r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.dataSync()[n]},e.prototype.buffer=function(){return opHandler.buffer(this.shape,this.dtype,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,n){return void 0===e&&(e=0),void 0===t&&(t=!1),void 0===n&&(n=!1),opHandler.cumsum(this,e,t,n)},e.prototype.squeeze=function(e){return this.throwIfDisposed(),opHandler.squeeze(this,e)},e.prototype.clone=function(){return this.throwIfDisposed(),opHandler.clone(this)},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,n){return void 0===t&&(t=!1),void 0===n&&(n=!1),this.throwIfDisposed(),opHandler.matMul(this,e,t,n)},e.prototype.dot=function(e){return this.throwIfDisposed(),opHandler.dot(this,e)},e.prototype.norm=function(e,t,n){return void 0===e&&(e="euclidean"),void 0===t&&(t=null),void 0===n&&(n=!1),this.throwIfDisposed(),opHandler.norm(this,e,t,n)},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(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),opHandler.concat([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,t){return void 0===t&&(t=0),opHandler.unstack(this,t)},e.prototype.pad=function(e,t){return void 0===t&&(t=0),opHandler.pad(this,e,t)},e.prototype.batchNormalization=function(e,t,n,r,o){return void 0===n&&(n=.001),this.throwIfDisposed(),opHandler.batchNormalization(this,e,t,n,r,o)},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.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.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.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.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,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),opHandler.conv1d(this,e,t,n,r,o,a)},e.prototype.conv2d=function(e,t,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),opHandler.conv2d(this,e,t,n,r,o,a)},e.prototype.conv2dTranspose=function(e,t,n,r,o){return this.throwIfDisposed(),opHandler.conv2dTranspose(this,e,t,n,r,o)},e.prototype.depthwiseConv2D=function(e,t,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),opHandler.depthwiseConv2d(this,e,t,n,r,o,a)},e.prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),opHandler.avgPool(this,e,t,n,r)},e.prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),opHandler.maxPool(this,e,t,n,r)},e.prototype.localResponseNormalization=function(e,t,n,r){return void 0===e&&(e=5),void 0===t&&(t=1),void 0===n&&(n=1),void 0===r&&(r=.5),opHandler.localResponseNormalization(this,e,t,n,r)},e.prototype.variable=function(e,t,n){return void 0===e&&(e=!0),this.throwIfDisposed(),Variable.variable(this,e,t,n)},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,n,r,o){return void 0===r&&(r=0),void 0===o&&(o=0),this.throwIfDisposed(),opHandler.stridedSlice(this,e,t,n,r,o)},e.nextId=0,e}();Object.defineProperty(Tensor,Symbol.hasInstance,{value:function(e){return!!e&&null!=e.shape&&null!=e.dtype}});var Variable=function(e){function t(n,r,o){void 0===r&&(r=!0);var a=e.call(this,n.shape,n.dtype,null,n.dataId)||this;a.trainable=r,a.name=o,null==a.name&&(a.name=t.nextVarId.toString(),t.nextVarId++);try{trackerFn().registerVariable(a)}catch(e){throw trackerFn().disposeTensor(a),e}return a}return __extends(t,e),t.variable=function(e,n,r,o){return void 0===n&&(n=!0),null!=o&&o!==e.dtype&&(e=e.asType(o)),new t(e,n,r)},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.nextVarId=0,t}(Tensor);Object.defineProperty(Variable,Symbol.hasInstance,{value:function(e){return e instanceof Tensor&&null!=e.assign&&e.assign instanceof Function}});var variable=Variable.variable;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 n=0;n<t.length;n++)if(t[n].id===e.id)return!0;return!1}function getTensorsInContainer(e){var t=[];return walkTensorContainer(e,t,new Set),t}function walkTensorContainer(e,t,n){if(null!=e)if(e instanceof Tensor)t.push(e);else if(isIterable(e)){var r=e;for(var o in r){var a=r[o];n.has(a)||(n.add(a),walkTensorContainer(a,t,n))}}}function isIterable(e){return Array.isArray(e)||"object"==typeof e}var Type,Engine=function(){function e(e,t,n){this.backend=e,this.safeMode=t,this.debugMode=n,this.registeredVariables={},this.refCounter=new WeakMap,this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numDataBuffers=0,this.gradientScopeCount=0,this.customGradientDepth=0,this.keepTensors=new Set,this.activeScope={track:[],name:"default scope"},this.scopeStack=[this.activeScope],this.profiler=new Profiler(e)}return e.prototype.tidy=function(e,t,n){var r=this;void 0===n&&(n=!1);var o,a=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");a=e}return this.scopedRun(function(){return r.startScope(a,n)},function(){return r.endScope(o,n)},function(){return(o=t())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o})},e.prototype.scopedRun=function(e,t,n){e();try{var r=n();return t(),r}catch(e){throw t(),e}},e.prototype.runKernel=function(e,t,n){var r,o=this,a=[],i=function(e){return a.push(e),e},s=this.activeScope.name;if(this.scopedRun(function(){return o.customGradientDepth++},function(){return o.customGradientDepth--},function(){r=o.debugMode()?o.profiler.profileKernel(s,function(){return e(o.backend,i)}):e(o.backend,i)}),this.shouldRecord()){var u={id:this.nextTapeNodeId++,name:s,inputs:t,output:Array.isArray(r)?r[0]:r};null!=n&&(u.gradient=function(e){return n(e,a)}),this.activeTape.push(u)}return r},e.prototype.registerTensor=function(e){var t=this.refCounter.has(e.dataId)?this.refCounter.get(e.dataId):0;this.numTensors++,0===t&&(this.numDataBuffers++,this.numBytes+=sizeFromShape(e.shape)*bytesPerElement(e.dtype),this.backend.register(e.dataId,e.shape,e.dtype)),this.refCounter.set(e.dataId,t+1),e instanceof Variable||this.track(e)},e.prototype.registerVariable=function(e){if(null!=this.registeredVariables[e.name])throw new Error("Variable with name "+e.name+" was already registered");this.registeredVariables[e.name]=e},e.prototype.disposeTensor=function(e){if(this.refCounter.has(e.dataId)){this.keepTensors.has(e.id)&&this.keepTensors.delete(e.id),this.numTensors--;var t=this.refCounter.get(e.dataId);t<=1?(this.refCounter.delete(e.dataId),this.backend.disposeData(e.dataId),this.numDataBuffers--,this.numBytes-=sizeFromShape(e.shape)*bytesPerElement(e.dtype)):this.refCounter.set(e.dataId,t-1)}},e.prototype.disposeVariables=function(){for(var e in this.registeredVariables){var t=this.registeredVariables[e];this.disposeTensor(t),delete this.registeredVariables[e]}},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.numTensors,e.numDataBuffers=this.numDataBuffers,e.numBytes=this.numBytes,e},e.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},e.prototype.addTapeNode=function(e,t,n){var r={};e.forEach(function(e,t){r[t]=e});var o={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:r,output:t,gradient:function(e){var t={};return n(e).forEach(function(e,n){t[n]=function(){return e}}),t}};this.activeTape.push(o)},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 n={track:[],name:"unnamed scope"};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),o=getTensorsInContainer(e);o.forEach(function(e){return r.add(e.id)});for(var a=0;a<this.activeScope.track.length;a++){var i=this.activeScope.track[a];r.has(i.id)||(null!=this.activeTape?o.push(i):i.dispose())}var s=this.scopeStack.pop();this.activeScope=0===this.scopeStack.length?{track:[],name:"default scope"}:this.scopeStack[this.scopeStack.length-1],o.forEach(function(e){!n.keepTensors.has(e.id)&&isTensorInList(e,s.track)&&n.track(e)})},e.prototype.gradients=function(e,t,n,r){var o=this;return void 0===r&&(r=!1),assert(t.length>0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var a=e();assert(a instanceof Tensor,"The result y returned by f() must be a tensor.");var i=getFilteredNodesXToY(o.activeTape,t,a);if(!r&&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[a.id]=null==n?ones(a.shape):n,backpropagateGradients(s,i),{value:a,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 n,r,o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];if(assert(o.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(){r=t.tidy(e.name,function(){var t=e.apply(void 0,o),r=t.value,a=t.gradFunc;return assert(r instanceof Tensor,"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),assert(isFunction(a),"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n=a,r},!0)}),t.shouldRecord()){t.addTapeNode(o,r,function(e){var t=n(e),r=Array.isArray(t)?t:[t];return assert(r.length===o.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(r.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."),r})}return r}},e.prototype.write=function(e,t){this.backend.write(e,t)},e.prototype.readSync=function(e){return this.backend.readSync(e)},e.prototype.read=function(e){return this.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,n;return __generator(this,function(r){switch(r.label){case 0:return t=now(),[4,this.backend.time(e)];case 1:return(n=r.sent()).wallMs=now()-t,[2,n]}})})},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 this.activeScope.track.push(e),e},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 URL_PROPERTIES=[{name:"DEBUG",type:Type.BOOLEAN},{name:"IS_BROWSER",type:Type.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:Type.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:Type.BOOLEAN},{name:"WEBGL_VERSION",type:Type.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:Type.BOOLEAN},{name:"BACKEND",type:Type.STRING}];function isWebGLVersionEnabled(e,t){var n;try{n=getWebGLRenderingContext(e,t)}catch(e){return!1}return null!=n&&(loseContext(n),!0)}function getWebGLDisjointQueryTimerVersion(e,t){if(0===e)return 0;var n,r=getWebGLRenderingContext(e,t);return n=hasExtension(r,"EXT_disjoint_timer_query_webgl2")&&2===e?2:hasExtension(r,"EXT_disjoint_timer_query")?1:0,null!=r&&loseContext(r),n}function isRenderToFloatTextureEnabled(e,t){if(0===e)return!1;var n=getWebGLRenderingContext(e,t);if(1===e){if(!hasExtension(n,"OES_texture_float"))return!1}else if(!hasExtension(n,"EXT_color_buffer_float"))return!1;createFloatTextureAndBindToFramebuffer(n,e);var r=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return loseContext(n),r}function isDownloadFloatTextureEnabled(e,t){if(0===e)return!1;var n=getWebGLRenderingContext(e,t);if(1===e){if(!hasExtension(n,"OES_texture_float"))return!1}else if(!hasExtension(n,"EXT_color_buffer_float"))return!1;createFloatTextureAndBindToFramebuffer(n,e),n.readPixels(0,0,1,1,n.RGBA,n.FLOAT,new Float32Array(4));var r=n.getError()===n.NO_ERROR;return loseContext(n),r}function isWebGLFenceEnabled(e,t){if(2!==e)return!1;var n=getWebGLRenderingContext(e,t),r=null!=n.fenceSync;return loseContext(n),r}function isChrome(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}var TENSORFLOWJS_FLAGS_PREFIX="tfjsflags";function getFeaturesFromURL(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=getQueryParams(window.location.search);if(TENSORFLOWJS_FLAGS_PREFIX in t){var n={};t[TENSORFLOWJS_FLAGS_PREFIX].split(",").forEach(function(e){var t=e.split(":"),r=t[0],o=t[1];n[r]=o}),URL_PROPERTIES.forEach(function(t){t.name in n&&(console.log("Setting feature override from URL "+t.name+": "+n[t.name]),t.type===Type.NUMBER?e[t.name]=+n[t.name]:t.type===Type.BOOLEAN?e[t.name]="true"===n[t.name]:t.type===Type.STRING?e[t.name]=n[t.name]:console.warn("Unknown URL param: "+t.name+"."))})}return e}function hasExtension(e,t){return null!=e.getExtension(t)}function getWebGLRenderingContext(e,t){if(0===e||!t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var n=document.createElement("canvas");return 1===e?n.getContext("webgl")||n.getContext("experimental-webgl"):n.getContext("webgl2")}function loseContext(e){if(null!=e){var t=e.getExtension("WEBGL_lose_context");if(null==t)throw new Error("Extension WEBGL_lose_context not supported on this browser.");t.loseContext()}}function createFloatTextureAndBindToFramebuffer(e,t){var n=e.createFramebuffer(),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);var o=2===t?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,o,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0)}function getQueryParams(e){var t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return decodeParam(t,n[0],n[1]),n.join("=")}),t}function decodeParam(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}var TEST_EPSILON_FLOAT32_ENABLED=.001,TEST_EPSILON_FLOAT32_DISABLED=.1,Environment=function(){function e(e){this.features={},this.registry={},null!=e&&(this.features=e),this.get("DEBUG")&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}return e.setBackend=function(e,t){if(void 0===t&&(t=!1),!(e in ENV.registry))throw new Error("Backend name '"+e+"' not found in registry");ENV.initBackend(e,t)},e.getBackend=function(){return ENV.initDefaultBackend(),ENV.backendName},e.disposeVariables=function(){ENV.engine.disposeVariables()},e.memory=function(){return ENV.engine.memory()},e.tidy=function(e,t,n){return void 0===n&&(n=!1),ENV.engine.tidy(e,t,n)},e.dispose=function(e){getTensorsInContainer(e).forEach(function(e){return e.dispose()})},e.keep=function(e){return ENV.engine.keep(e)},e.time=function(e){return ENV.engine.time(e)},e.prototype.get=function(e){return e in this.features?this.features[e]:(this.features[e]=this.evaluateFeature(e),this.features[e])},e.prototype.getFeatures=function(){return this.features},e.prototype.set=function(e,t){this.features[e]=t},e.prototype.getBestBackendName=function(){var e=this;if(0===Object.keys(this.registry).length)throw new Error("No backend found in registry.");return Object.keys(this.registry).map(function(t){return{name:t,entry:e.registry[t]}}).sort(function(e,t){return t.entry.priority-e.entry.priority})[0].name},e.prototype.evaluateFeature=function(e){if("DEBUG"===e)return!1;if("IS_BROWSER"===e)return"undefined"!=typeof window;if("IS_NODE"===e)return"undefined"!=typeof process&&void 0!==process.versions.node;if("IS_CHROME"===e)return isChrome();if("IS_TEST"===e)return!1;if("BACKEND"===e)return this.getBestBackendName();if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"===e){var t=this.get("WEBGL_VERSION");return 0===t?0:t>0?0:getWebGLDisjointQueryTimerVersion(t,this.get("IS_BROWSER"))}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===e)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!isMobile();if("HAS_WEBGL"===e)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===e)return isWebGLVersionEnabled(2,this.get("IS_BROWSER"))?2:isWebGLVersionEnabled(1,this.get("IS_BROWSER"))?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===e)return isRenderToFloatTextureEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===e)return isDownloadFloatTextureEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_FENCE_API_ENABLED"===e)return isWebGLFenceEnabled(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("TEST_EPSILON"===e)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?TEST_EPSILON_FLOAT32_ENABLED:TEST_EPSILON_FLOAT32_DISABLED;throw new Error("Unknown feature "+e+".")},e.prototype.setFeatures=function(e){this.features=Object.assign({},e)},e.prototype.reset=function(){this.features=getFeaturesFromURL(),null!=this.globalEngine&&(this.globalEngine=null)},e.prototype.initBackend=function(e,t){var n=this;void 0===t&&(t=!1),this.backendName=e,this.backend=this.findBackend(e),this.globalEngine=new Engine(this.backend,t,function(){return n.get("DEBUG")})},e.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},e.prototype.registerBackend=function(e,t,n,r){var o=this;if(void 0===n&&(n=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=r&&r(function(){return o.engine}),!1;try{var a=t();return this.registry[e]={backend:a,priority:n},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},e.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e]},Object.defineProperty(e.prototype,"engine",{get:function(){return this.initDefaultBackend(),this.globalEngine},enumerable:!0,configurable:!0}),e.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(this.get("BACKEND"),!1)},e}();function getGlobalNamespace(){var e;if("undefined"!=typeof window)e=window;else{if("undefined"==typeof process)throw new Error("Could not find a global object");e=process}return e}function getOrMakeEnvironment(){var e=getGlobalNamespace();return null==e.ENV&&(e.ENV=new Environment(getFeaturesFromURL()),setTensorTracker(function(){return e.ENV.engine})),e.ENV}var ENV=getOrMakeEnvironment(),environment=Object.freeze({Environment:Environment,ENV:ENV});function warn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];ENV.get("IS_TEST")||console.warn.apply(console,e)}function getReshaped(e,t,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(t.slice(0))).push(e[0]/n),o=o.concat(e.slice(1));else{o=o.concat(e[0]);for(var a=t.length,i=0;i<a;++i)o=o.concat([e[i+1]/t[i],t[i]]);o=o.concat(e.slice(a+1))}return o}function getPermuted(e,t,n){void 0===n&&(n=!0);var r=[];if(n){r.push(t);for(var o=t+1;o<e;++o)o<=2*t?(r.push(o),r.push(o-(t+1))):r.push(o)}else{var a=[],i=[];for(o=1;o<e;++o)o>=2*t+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i)}return r}function getReshapedPermuted(e,t,n,r){void 0===r&&(r=!0);var o=[];r?o.push(e[0]/n):o.push(e[0]*n);for(var a=1;a<e.length;++a)a<=t.length?r?o.push(t[a-1]*e[a]):o.push(e[a]/t[a-1]):o.push(e[a]);return o}function getSliceBeginCoords(e,t){for(var n=[0],r=0;r<t;++r)n.push(e[r][0]);return n}function getSliceSize(e,t,n){for(var r=e.slice(0,1),o=0;o<n;++o)r.push(e[o+1]-t[o][0]-t[o][1]);return r}function axesAreInnerMostDims(e,t){for(var n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function combineLocations(e,t,n){for(var r=e.length+t.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(e[a++]):o.push(t[i++]);return o}function computeOutAndReduceShapes(e,t){for(var n=[],r=e.length,o=0;o<r;o++)-1===t.indexOf(o)&&n.push(e[o]);return[n,t.map(function(t){return e[t]})]}function expandShapeToKeepDim(e,t){return combineLocations(e,t.map(function(e){return 1}),t)}function parseAxisParam(e,t){var n=t.length;return assert((e=null==e?t.map(function(e,t){return t}):[].concat(e)).every(function(e){return e>=-n&&e<n}),"All values in axis param must be in range [-"+n+", "+n+") 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?n+e:e})}function assertAxesAreInnerMostDims(e,t,n){assert(axesAreInnerMostDims(t,n),e+" suppo