text: /**
   * @license
   * Copyright 2019 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.
   * =============================================================================
   */
  !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).tf=t.tf||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t,e,n,r){return new(n||(n=Promise))(function(o,a){function i(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(i,s)}u((r=r.apply(t,e||[])).next())})}function o(t,e){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=e.call(t,i)}catch(t){a=[6,t],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])}}}var a=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},t.prototype.get=function(t){return t in this.flags?this.flags[t]:(this.flags[t]=this.evaluateFlag(t),this.flags[t])},t.prototype.getNumber=function(t){return this.get(t)},t.prototype.getBool=function(t){return this.get(t)},t.prototype.getFlags=function(){return this.flags},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},t.prototype.setFlags=function(t){this.flags=Object.assign({},t)},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e=i(this.global.location.search);if("tfjsflags"in e)e.tfjsflags.split(",").forEach(function(e){var n=e.split(":"),r=n[0],o=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,o)})}},t}();function i(t){var e={};return t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}(e,n[0],n[1]),n.join("=")}),e}function s(e){t.ENV=e}t.ENV=null;var u=Object.freeze({Environment:a,getQueryParams:i,get ENV(){return t.ENV},setEnvironmentGlobal:s});function l(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function c(t,e,n){return Math.max(t,Math.min(e,n))}function h(t){return t%2==0?t:t+1}function p(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function d(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function f(t,e,n){void 0===n&&(n=""),d(y(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})}function v(t){d(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})}function m(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||_(t)&&!n)for(var r=0;r<t.length;++r)m(t[r],e,n);else e.push(t);return e}function g(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function y(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function x(t){return t%1==0}function b(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function w(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function C(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function E(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise(function(r,o){var a=0,i=function(){if(t())r();else{var s=e(++a);null!=n&&a>=n?o():setTimeout(i,s)}};i()})}function N(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(t[o]>=0)n*=t[o];else if(-1===t[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(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var a=t.slice();return a[r]=e/n,a}function R(t,e){var n=e.length;return d((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&t<n}),function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t}),d(t.every(function(t){return x(t)}),function(){return"All values in axis param must be integers but got axis "+t}),t.map(function(t){return t<0?n+t:t})}function I(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||o?null:R(e,t).sort(),i=0,s=0;s<t.length;++s){if(null!=a){if(a[i]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==a[i]||a[i]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function k(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function S(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function A(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function T(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function D(t,e){return"complex64"!==e&&(("float32"!==e||"complex64"===t)&&(("int32"!==e||"float32"===t||"complex64"===t)&&("bool"!==e||"bool"!==t)))}function _(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function O(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function F(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=t.length}),e}function M(t){return"string"==typeof t||t instanceof String}function B(t){return"boolean"==typeof t}function P(t){return"number"==typeof t}function L(t){return Array.isArray(t)?L(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":P(t)?"float32":M(t)?"string":B(t)?"bool":"float32"}function V(t){return!!(t&&t.constructor&&t.call&&t.apply)}function W(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function U(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function z(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=m(t)),n&&A(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)}function G(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array;if(1===n.length)for(var a=n[0],i=0;i<a;i++)o[i]=r[e+i];else{a=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(i=0;i<a;i++)o[i]=t(e+i*u,s,r)}return o}(0,t,e)}function H(t,e){for(var n=q(t,e),r=0;r<n.length;r++)n[r]=1;return n}function q(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function $(){return t.ENV.platform.now()}function K(t){t.forEach(function(e){d(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function j(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.encode(e,n)}function X(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.decode(e,n)}var Y=Object.freeze({shuffle:l,clamp:c,nearestLargerEven:h,sum:p,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o}return n},assert:d,assertShapesMatch:f,assertNonNull:v,flatten:m,sizeFromShape:g,isScalarShape:function(t){return 0===t.length},arraysEqual:y,isInt:x,tanh:b,sizeToSquarishShape:w,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return l(e),e},rightPad:C,repeatedTry:E,inferFromImplicitShape:N,parseAxisParam:R,squeezeShape:I,getTypedArrayFromDType:k,getArrayFromDType:S,checkConversionForErrors:A,isValidDtype:T,hasEncodingLoss:D,isTypedArray:_,bytesPerElement:O,bytesFromStringArray:F,isString:M,isBoolean:B,isNumber:P,inferDtype:L,isFunction:V,nearestDivisor:W,computeStrides:U,toTypedArray:z,toNestedArray:G,makeOnesTypedArray:H,makeZerosTypedArray:q,now:$,assertNonNegativeIntegerDimensions:K,fetch:function(e,n){return t.ENV.platform.fetch(e,n)},encodeString:j,decodeString:X}),Q=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new J)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,a=this.backendTimer.time(function(){r=n()});return(Array.isArray(r)?r:[r]).forEach(function(n){n.data().then(function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))return console.warn("Found "+o+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),a.then(function(a){var i="";null!=a.getExtraProfileInfo&&(i=a.getExtraProfileInfo()),o.logger.logKernelProfile(t,n,r,a.kernelMs,e,i)})})}),r},t}();var J=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,a){var i=C(r+"ms",9),s=C(t,25),u=e.rank,l=e.size,c=C(e.shape.toString(),14),h="";for(var p in o){var d=o[p].shape,f=d.length;h+=p+": "+f+"D "+(f>0?d:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+h+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),Z=20,tt=3,et=7;function nt(t,e,n,r){var o=U(e),a=function(t,e,n,r){var o=g(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?at(t):t;if(s>1)for(var l=0;l<o/a;l++)for(var c=l*a,h=0;h<a;h++)i[h]=Math.max(i[h],rt(u[c+h],0,n).length);return i}(t,e,n,o),i=e.length,s=function t(e,n,r,o,a,i){void 0===i&&(i=!0);var s="complex64"===r?2:1;var u=n[0];var l=n.length;if(0===l){if("complex64"===r){var c=at(e);return[rt(c[0],0,r)]}return"bool"===r?[ot(e[0])]:[e[0].toString()]}if(1===l){if(u>Z){var h=tt*s,p=Array.from(e.slice(0,h)),d=Array.from(e.slice(u-tt*s,u));return"complex64"===r&&(p=at(p),d=at(d)),["["+p.map(function(t,e){return rt(t,a[e],r)}).join(", ")+", ..., "+d.map(function(t,e){return rt(t,a[u-tt+e],r)}).join(", ")+"]"]}var f="complex64"===r?at(e):Array.from(e);return["["+f.map(function(t,e){return rt(t,a[e],r)}).join(", ")+"]"]}var v=n.slice(1);var m=o.slice(1);var g=o[0]*s;var y=[];if(u>Z){for(var x=0;x<tt;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,!1))}y.push("...");for(var x=u-tt;x<u;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,x===u-1))}}else for(var x=0;x<u;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,x===u-1))}var C=2===l?",":"";y[0]="["+y[0]+C;for(var x=1;x<y.length-1;x++)y[x]=" "+y[x]+C;var E=",\n";for(var x=2;x<l;x++)E+="\n";y[y.length-1]=" "+y[y.length-1]+"]"+(i?"":E);return y}(t,e,n,o,a),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+i),u.push("  shape: ["+e+"]"),u.push("  values:")),u.push(s.map(function(t){return"    "+t}).join("\n")),u.join("\n")}function rt(t,e,n){return C(Array.isArray(t)?parseFloat(t[0].toFixed(et))+" + "+parseFloat(t[1].toFixed(et))+"j":M(t)?"'"+t+"'":"bool"===n?ot(t):parseFloat(t.toFixed(et)).toString(),e)}function ot(t){return 0===t?"false":"true"}function at(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var it=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=g(t),null!=n){var o=n.length;d(o===this.size,function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'."})}if("complex64"===e)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=n||S(e,this.size),this.strides=U(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),d(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var o=this.locToIndex(n);this.values[o]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var a=o[r];if(a<0||a>=this.shape[n]){var i="Requested out of range element at "+t+".   Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return ct.make(this.shape,{values:this.values},this.dtype)},t}(),st=null,ut=null,lt=null;var ct=function(){function t(t,e,n,r,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=g(t),this.strides=U(t),this.dataId=null!=r?r:{},this.id=st().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",st().registerTensor(this,o),null!=n&&st().write(o,this.dataId,n)}return t.make=function(e,n,r,o){var a=n.values;return null!=n.values&&"string"===r&&M(n.values[0])&&(a=n.values.map(function(t){return j(t)})),new t(e,r,a,n.dataId,o)},t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),d(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o])},t.prototype.asType=function(t){return this.throwIfDisposed(),ut.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,ut.buffer(this.shape,this.dtype,t)]}})})},t.prototype.bufferSync=function(){return ut.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,G(this.shape,t)]}})})},t.prototype.arraySync=function(){return G(this.shape,this.dataSync())},t.prototype.data=function(){return r(this,void 0,void 0,function(){var t,e;return o(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=st().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map(function(t){return X(t)})]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,t]}})})},t.prototype.dataSync=function(){this.throwIfDisposed();var t=st().readSync(this.dataId);if("string"===this.dtype)try{return t.map(function(t){return X(t)})}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},t.prototype.bytes=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,st().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)]}})})},t.prototype.dispose=function(){this.isDisposed||(st().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),ut.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),ut.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),ut.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),ut.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),ut.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),ut.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),ut.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),nt(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),ut.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),ut.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),ut.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),ut.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),ut.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),ut.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),ut.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),ut.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),ut.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),ut.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),ut.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),ut.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),lt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n)},t.prototype.batchNorm=function(t,e,n,r,o){return void 0===o&&(o=.001),this.throwIfDisposed(),ut.batchNorm(this,t,e,n,r,o)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ut.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),ut.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),ut.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),ut.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),ut.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),ut.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),ut.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),ut.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),ut.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),ut.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),ut.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),ut.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),ut.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),ut.div(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),ut.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),ut.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),ut.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),ut.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),ut.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),ut.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),ut.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),ut.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),ut.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),ut.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),ut.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),ut.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),ut.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),ut.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),ut.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),ut.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),ut.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),ut.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),ut.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),ut.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),ut.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),ut.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),ut.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),ut.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),ut.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),ut.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),ut.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),ut.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),ut.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),ut.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),ut.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),ut.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),ut.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),ut.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),ut.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),ut.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),ut.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),ut.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),ut.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),ut.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),ut.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),ut.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),ut.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),ut.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),ut.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),ut.relu(this)},t.prototype.elu=function(){return this.throwIfDisposed(),ut.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),ut.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),ut.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),ut.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),ut.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),ut.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),ut.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),ut.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),ut.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),ut.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),ut.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),ut.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),ut.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),ut.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),ut.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),ut.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),ut.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),ut.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),ut.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),ut.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),ut.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),ut.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),ut.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),ut.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),ut.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),ut.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),ut.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),ut.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),ut.conv1d(this,t,e,n,r,o,a)},t.prototype.conv2d=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),ut.conv2d(this,t,e,n,r,o,a)},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),ut.conv2dTranspose(this,t,e,n,r,o)},t.prototype.depthwiseConv2D=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),ut.depthwiseConv2d(this,t,e,n,r,o,a)},t.prototype.separableConv2d=function(t,e,n,r,o,a){return void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),ut.separableConv2d(this,t,e,n,r,o,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),ut.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),ut.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),ut.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),ut.pool(this,t,e,n,r,o)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),ht.variable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),ut.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),ut.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),ut.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),ut.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),ut.stridedSlice(this,t,e,n,r,o,a,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),ut.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),ut.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),ut.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),ut.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),ut.spectral.irfft(this)},t}();Object.defineProperty(ct,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var ht=function(t){function e(e,n,r){void 0===n&&(n=!0);var o=t.call(this,e.shape,e.dtype,null,e.dataId)||this;o.trainable=n,o.name=r,null==o.name&&(o.name=st().nextVariableId().toString());try{st().registerVariable(o)}catch(t){throw st().disposeTensor(o),t}return o}return n(e,t),e.variable=function(t,n,r,o){return void 0===n&&(n=!0),null!=o&&o!==t.dtype&&(t=t.asType(o)),new e(t,n,r)},e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!y(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");st().disposeTensor(this),this.dataId=t.dataId,st().registerTensor(this)},e.prototype.dispose=function(){st().disposeVariable(this),this.isDisposedInternal=!0},e}(ct);Object.defineProperty(ht,Symbol.hasInstance,{value:function(t){return t instanceof ct&&null!=t.assign&&t.assign instanceof Function}});var pt,dt,ft,vt,mt,gt=ht.variable;(pt=t.Rank||(t.Rank={})).R0="R0",pt.R1="R1",pt.R2="R2",pt.R3="R3",pt.R4="R4",pt.R5="R5",pt.R6="R6",function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(dt||(dt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(ft||(ft={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(vt||(vt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(mt||(mt={}));var yt={float32:vt,int32:dt,bool:ft,complex64:mt};function xt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return yt[t][e]}function bt(t){return xt(t,"int32")}function wt(t,e){if(t.dtype===e.dtype)return[t,e];var n=xt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Ct(t,e){d(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})}function Et(t){var e=[];return function t(e,n,r){if(null==e)return;if(e instanceof ct)return void n.push(e);if(o=e,!Array.isArray(o)&&"object"!=typeof o)return;var o;var a=e;for(var i in a){var s=a[i];r.has(s)||(r.add(s),t(s,n,r))}}(t,e,new Set),e}var Nt,Rt=Object.freeze({makeTypesMatch:wt,assertTypesMatch:Ct,isTensorInList:function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1},getTensorsInContainer:Et}),It=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),kt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new It}return t.prototype.ready=function(){return r(this,void 0,void 0,function(){var t,e,n;return o(this,function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then(function(){})];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}})})},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory)},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},t.prototype.setBackend=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){switch(o.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=o.sent(),[3,3];case 2:r=n,o.label=3;case 3:if(!r)return[2,!1];o.label=4;case 4:return this.backendInstance=this.registry[t],this.profiler=new Q(this.backendInstance),[2,!0]}})})},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var o=++this.pendingBackendInitId,a=r.then(function(n){return!(o<e.pendingBackendInitId)&&(e.registry[t]=n,e.pendingBackendInit=null,!0)}).catch(function(n){return!(o<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),!1)});return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority})},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,a=r.asyncInit;if(a||o)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){this.write(t,e,this.readSync(e))},t.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun(function(){return r.startScope(o)},function(){return r.endScope(n)},function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n})},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=ct.make(t.shape,{dataId:t.dataId},t.dtype);return this.addTapeNode([t],e,function(t){return[t.toFloat()]}),e},t.prototype.runKernel=function(t,e,n){var r,o=this,a=[],i=this.isTapeOn(),s=null!=this.state.activeScope?this.state.activeScope.name:"",u=function(t){i&&(a=t.map(function(t){return o.keep(o.clone(t))}))},l=this.state.numBytes,c=this.state.numTensors;if(this.scopedRun(function(){return o.state.kernelDepth++},function(){return o.state.kernelDepth--},function(){r=o.ENV.getBool("DEBUG")?o.profiler.profileKernel(s,e,function(){return t(o.backend,u)}):t(o.backend,u)}),i){var h={id:this.state.nextTapeNodeId++,name:s,inputs:e,outputs:Array.isArray(r)?r:[r],saved:a};null!=n&&(h.gradient=function(t){return n(t,a)}),this.state.activeTape.push(h)}return this.state.profiling&&this.state.activeProfile.kernels.push({name:s,bytesAdded:this.state.numBytes-l,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-c,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(t){return e[t].shape}),outputShape:Array.isArray(r)?r.map(function(t){return t.shape}):r.shape}),r},t.prototype.registerTensor=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*O(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:null!=e?e:this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r,null!=e?e.register(t.dataId,t.shape,t.dtype):this.backend.register(t.dataId,t.shape,t.dtype)}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof ht||this.track(t)},t.prototype.registerVariable=function(t){if(null!=this.state.registeredVariables[t.name])throw new Error("Variable with name "+t.name+" was already registered");this.state.registeredVariables[t.name]=t},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var o={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e=n(t),r={};return e.forEach(function(t,e){r[e]=function(){return t}}),r}};this.state.activeTape.push(o)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=Et(t),r=new Set(n.map(function(t){return t.id})),o=0;o<this.state.activeScope.track.length;o++){var a=this.state.activeScope.track[o];a.kept||r.has(a.id)||a.dispose()}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(t){t.kept||t.scopeId!==i.id||e.track(t)})},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),d(e.length>0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",t)});d(a instanceof ct,function(){return"The result y returned by f() must be a tensor."});var i=function(t,e,n){for(var r={},o={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var i=(f=t[a]).inputs;for(var s in i){for(var u=i[s],l=!1,c=0;c<e.length;c++)if(r[u.id]){f.outputs.forEach(function(t){return r[t.id]=!0}),l=!0,o[f.id]=!0;break}if(l)break}}var h={};h[n.id]=!0;var p={};for(a=t.length-1;a>=0;a--)for(i=(f=t[a]).inputs,c=0;c<f.outputs.length;c++)if(h[f.outputs[c].id]){for(var s in i)h[i[s].id]=!0,p[f.id]=!0;break}var d=[];for(a=0;a<t.length;a++){var f;if(o[(f=t[a]).id]&&p[f.id]){var v={};for(var s in f.inputs){var m=f.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},f);g.inputs=v,g.outputs=f.outputs,d.push(g)}}return d}(this.state.activeTape,e,a);if(!r&&0===i.length&&e.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.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(t=a.shape,r=H(g(t),"float32"),ct.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=ct.make(e.shape,{values:q(e.size,e.dtype)},e.dtype);a.push(r)}}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var i=o.gradient(1===o.outputs.length?a[0]:a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n(function(){return i[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!y(r.shape,a.shape))throw new Error("Error in gradient for op "+o.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,i,function(t){return o.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===o.state.gradientDepth&&(o.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),o.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return d(V(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];d(r.every(function(t){return t instanceof ct}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"});var a={};return r.forEach(function(t,e){a[e]=t}),e.runKernel(function(e,o){return d((n=t.apply(void 0,r.concat([o]))).value instanceof ct,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),d(V(n.gradFunc),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."}),n.value},a,function(t,e){var o=n.gradFunc(t,e),a=Array.isArray(o)?o:[o];d(a.length===r.length,function(){return"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(...)."}),d(a.every(function(t){return t instanceof ct}),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."});var i={};return a.forEach(function(t,e){i[e]=function(){return t}}),i})}},t.prototype.write=function(t,e,n){var r=this.state.tensorInfo.get(e),o=r.backend;if(t=t||this.backend,"string"===r.dtype){var a=F(n);this.state.numBytes+=a-r.bytes,r.bytes=a}t!==o&&(o.disposeData(e),r.backend=t,t.register(e,r.shape,r.dtype)),t.write(e,n)},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},t.prototype.fromPixels=function(t,e){return this.backend.fromPixels(t,e)},t.prototype.time=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){switch(r.label){case 0:return e=$(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=$()-e,[2,n]}})})},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new It,this.registry)this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}();var St=function(){var t=function(){if(null==Nt){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}Nt=t}return Nt}();if(null==t._tfengine){var e=new a(t);t._tfengine=new kt(e)}return s(t._tfengine.ENV),st=function(){return t._tfengine},t._tfengine}();function At(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}t.ENV.registerFlag("DEBUG",function(){return!1},function(t){t&&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.")}),t.ENV.registerFlag("IS_BROWSER",function(){return At()}),t.ENV.registerFlag("IS_NODE",function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}),t.ENV.registerFlag("IS_CHROME",function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),t.ENV.registerFlag("PROD",function(){return!1}),t.ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return t.ENV.getBool("DEBUG")}),t.ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),t.ENV.registerFlag("IS_TEST",function(){return!1});var Tt,Dt,_t={},Ot={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ft(t,e){_t[t]=e}function Mt(t){t in _t||(_t[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=Bt(t);if(e.addEventListener("webglcontextlost",function(e){e.preventDefault(),delete _t[t]},!1),1===t)return e.getContext("webgl",Ot)||e.getContext("experimental-webgl",Ot);return e.getContext("webgl2",Ot)}(t));var e=_t[t];return e.isContextLost()?(delete _t[t],Mt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),_t[t])}function Bt(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function Pt(t,e){return[e,t]}function Lt(t){var e=g(t);return w(Math.ceil(e/4))}function Vt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Wt(e,n){var r,o,a,i,s,u,l,c,h,p=e;return 2===t.ENV.getNumber("WEBGL_VERSION")?(r=p.R32F,o=p.R16F,a=p.RGBA16F,i=p.RGBA32F,s=p.RED,u=4,l=1,c=p.HALF_FLOAT,h=p.FLOAT):(r=e.RGBA,o=e.RGBA,a=e.RGBA,i=p.RGBA,s=e.RGBA,u=4,l=4,c=null!=n?n.HALF_FLOAT_OES:null,h=e.FLOAT),{internalFormatFloat:r,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:s,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:l,textureTypeHalfFloat:c,textureTypeFloat:h}}function Ut(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+qt(t,e))}(t),r}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Tt||(Tt={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Dt||(Dt={}));var zt=5.96e-8,Gt=65504;function Ht(e){return!!(t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||zt<Math.abs(e)&&Math.abs(e)<Gt)}function qt(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function $t(t,e,n){return ve(t,e,function(){return t.getExtension(n)},'Extension "'+n+'" not supported on this browser.')}function Kt(t,e,n){var r=ve(t,e,function(){return t.createShader(t.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(Ut(t,e,function(){return t.shaderSource(r,n)}),Ut(t,e,function(){return t.compileShader(r)}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function jt(t,e,n){var r=ve(t,e,function(){return t.createShader(t.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(Ut(t,e,function(){return t.shaderSource(r,n)}),Ut(t,e,function(){return t.compileShader(r)}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=Qt.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],o=t.split("\n"),a=o.length.toString().length+2,i=o.map(function(t,e){return C((e+1).toString(),a)+t}),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var l=i.slice(0,r-1),c=i.slice(r-1,r),h=i.slice(r);console.log(l.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+C(c[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var Xt,Yt,Qt=/ERROR: [0-9]+:([0-9]+):/g;function Jt(t,e){return ve(t,e,function(){return t.createProgram()},"Unable to create WebGLProgram.")}function Zt(t,e,n){if(Ut(t,e,function(){return t.linkProgram(n)}),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function te(t,e,n){if(Ut(t,e,function(){return t.validateProgram(n)}),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function ee(t,e,n){var r=ve(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return Ut(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),Ut(t,e,function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function ne(t,e,n){var r=ve(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return Ut(t,e,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)}),Ut(t,e,function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function re(t,e){return ve(t,e,function(){return t.createTexture()},"Unable to create WebGLTexture.")}function oe(e,n){var r=t.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||n<=0){var o="["+e+"x"+n+"]";throw new Error("Requested texture size "+o+" is invalid.")}if(e>r||n>r){o="["+e+"x"+n+"]";throw new Error("Requested texture size "+o+" greater than WebGL maximum on this browser / GPU "+("["+r+"x"+r+"]")+".")}}function ae(t,e){return ve(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ie(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Ut(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o)}),Ut(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)}),Ut(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function se(t,e,n,r){me(t,r),Ut(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function ue(t,e,n,r){return ve(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function le(t,e,n){return t.getUniformLocation(e,n)}function ce(t,e,n,r,o,a){Ut(t,e,function(){return se(t,e,r,a)}),Ut(t,e,function(){return t.uniform1i(o,a)})}function he(t,e,n,r){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Ut(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function pe(t,e,n){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Ut(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function de(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+fe(t,e))}function fe(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function ve(t,e,n,r){var o=Ut(t,e,function(){return n()});if(null==o)throw new Error(r);return o}function me(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+n+"]")+".")}function ge(t,e){return void 0===e&&(e=2),g(t.slice(0,t.length-e))}function ye(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function xe(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[ge(t)].concat(ye(t))),e}function be(e,n){var r;void 0===n&&(n=!1);var o=t.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n&&(o*=2,1===(e=e.map(function(t,n){return n>=e.length-2?h(e[n]):e[n]})).length&&(e=[2,e[0]])),2!==e.length){var a=I(e);e=a.newShape}var i=g(e);if(e.length<=1&&i<=o)return[1,i];if(2===e.length&&e[0]<=o&&e[1]<=o)return e;if(3===e.length&&e[0]*e[1]<=o&&e[2]<=o)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=o&&e[1]*e[2]<=o)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=o&&e[3]<=o)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=o&&e[1]*e[2]*e[3]<=o)return[e[0],e[1]*e[2]*e[3]];if(n){var s=ge(e),u=2,l=2;return e.length&&(u=(r=ye(e))[0],l=r[1]),w(i=s*(u/2)*(l/2)).map(function(t){return 2*t})}return w(i)}function we(t){return t%2==0}function Ce(t,e){if(y(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(we(n)&&we(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&we(t[0])&&we(e[0])}function Ee(t){if(null==Xt){var e=Mt(t);Xt=e.getParameter(e.MAX_TEXTURE_SIZE)}return Xt}function Ne(t){if(null==Yt){var e=Mt(t);Yt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Yt)}function Re(t){if(0===t)return 0;var e=Mt(t);return Ie(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ie(e,"EXT_disjoint_timer_query")?1:0}function Ie(t,e){return null!=t.getExtension(e)}function ke(t){try{if(null!=Mt(t))return!0}catch(t){return!1}return!1}function Se(t){if(0===t)return!1;var e=Mt(t);if(1===t){if(!Ie(e,"OES_texture_float"))return!1}else if(!Ie(e,"EXT_color_buffer_float"))return!1;return Te(e)}function Ae(t){if(0===t)return!1;var e=Mt(t);if(1!==t){if(Ie(e,"EXT_color_buffer_float"))return Te(e);if(Ie(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Wt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var o=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(o),a}(e,n)}return!1}return!!Ie(e,"OES_texture_float")&&(!!Ie(e,"WEBGL_color_buffer_float")&&Te(e))}function Te(t){var e=Wt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n);t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),o}function De(t){return 2===t&&null!=Mt(t).fenceSync}var _e=Object.freeze({callAndCheck:Ut,canBeRepresented:Ht,getWebGLErrorMessage:qt,getExtensionOrThrow:$t,createVertexShader:Kt,createFragmentShader:jt,createProgram:Jt,linkProgram:Zt,validateProgram:te,createStaticVertexBuffer:ee,createStaticIndexBuffer:ne,getNumChannels:function(){return 2===t.ENV.getNumber("WEBGL_VERSION")?1:4},createTexture:re,validateTextureSize:oe,createFramebuffer:ae,bindVertexBufferToProgramAttribute:ie,bindTextureUnit:se,unbindTextureUnit:function(t,e,n){me(t,n),Ut(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:ue,getProgramUniformLocation:le,bindTextureToProgramUniformSampler:ce,bindCanvasToFramebuffer:function(t,e){Ut(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Ut(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Ut(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:he,unbindColorTextureFromFramebuffer:pe,validateFramebuffer:de,getFramebufferErrorMessage:fe,getBatchDim:ge,getRowsCols:ye,getShapeAs3D:xe,getTextureShapeFromLogicalShape:be,isReshapeFree:Ce,getWebGLMaxTextureSize:Ee,resetMaxTextureSize:function(){Xt=null},resetMaxTexturesInShader:function(){Yt=null},getMaxTexturesInShader:Ne,getWebGLDisjointQueryTimerVersion:Re,hasExtension:Ie,isWebGLVersionEnabled:ke,isCapableOfRenderingToFloatTexture:Se,isDownloadFloatTextureEnabled:Ae,isWebGLFenceEnabled:De});function Oe(e){t.ENV.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Fe(t,e){return St.tidy(t,e)}function Me(t){Et(t).forEach(function(t){return t.dispose()})}function Be(t){return St.keep(t)}function Pe(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];t.ENV.getBool("IS_TEST")||console.warn.apply(console,e)}function Le(e,n){var r=e;if(_(e))return"string"===n?[]:[e.length];if(!Array.isArray(e))return[];for(var o=[];Array.isArray(r)||_(r)&&"string"!==n;)o.push(r.length),r=r[0];return Array.isArray(e)&&t.ENV.getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){r=r||[];if(!Array.isArray(e)&&!_(e))return void d(0===n.length,function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"});d(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"});d(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});var o=n.slice(1);for(var a=0;a<e.length;++a)t(e[a],o,r.concat(a))}(e,o,[]),o}function Ve(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function We(e,n,r,o){if(void 0===o&&(o="numeric"),e instanceof ct)return Ve(o,e.dtype,n,r),e;var a=L(e);if("string"!==a&&["bool","int32","float32"].indexOf(o)>=0&&(a=o),Ve(o,a,n,r),null==e||!_(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){var i=null==e?"null":e.constructor.name;throw new Error("Argument '"+n+"' passed to '"+r+"' must be a Tensor or TensorLike, but got '"+i+"'")}var s=Le(e,a);_(e)||Array.isArray(e)||(e=[e]);var u="string"!==a?z(e,a,t.ENV.getBool("DEBUG")):m(e,[],!0);return ct.make(s,{values:u},a)}function Ue(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return We(t,e+"["+r+"]",n)},r)}function ze(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function Ge(t,e,n){for(var r=t.length+e.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[a++]):o.push(e[i++]);return o}function He(t,e){for(var n=[],r=t.length,o=0;o<r;o++)-1===e.indexOf(o)&&n.push(t[o]);return[n,e.map(function(e){return t[e]})]}function qe(t,e){return Ge(t,e.map(function(t){return 1}),e)}function $e(t,e,n){d(ze(e,n),function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."})}function Ke(t,e){if(ze(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach(function(t){return n.push(t)}),n}function je(t){return t.map(function(t,e){return[e,t]}).sort(function(t,e){return t[1]-e[1]}).map(function(t){return t[0]})}function Xe(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function Ye(t,e){var n=t[0].length;t.forEach(function(t,e){d(t.length===n,function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"})}),d(e>=0&&e<n,function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."});var r=t[0];t.forEach(function(t,o){for(var a=0;a<n;a++)d(a===e||t[a]===r[a],function(){return"Error in concat"+n+"D: Shape of tensors["+o+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+o+"."})})}function Qe(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function Je(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];St.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),St.endScope(o),o}catch(t){throw St.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}t.ENV.registerFlag("HAS_WEBGL",function(){return t.ENV.getNumber("WEBGL_VERSION")>0}),t.ENV.registerFlag("WEBGL_VERSION",function(){return ke(2)?2:ke(1)?1:0}),t.ENV.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===t.ENV.get("WEBGL_VERSION")}),t.ENV.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),t.ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK",function(){return t.ENV.getBool("HAS_WEBGL")}),t.ENV.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_CLIP",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_REDUCE",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_LAZILY_UNPACK",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_CONV_IM2COL",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ee(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ne(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var e=t.ENV.getNumber("WEBGL_VERSION");return 0===e?0:Re(e)}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(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))));var e}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Se(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!t.ENV.getBool("WEBGL_FORCE_F16_TEXTURES")&&t.ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),t.ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ae(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return De(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),lt=Oe;var Ze=Je({complex_:function(t,e){var n=We(t,"real","complex"),r=We(e,"imag","complex");return f(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),St.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),tn=Je({real_:function(t){var e=We(t,"input","real");return St.runKernel(function(t){return t.real(e)},{$input:e})}}),en=Je({imag_:function(t){var e=We(t,"input","imag");return St.runKernel(function(t){return t.imag(e)},{$input:e})}});function nn(t,e,n){return rn(t,e,Le(t,n),n)}function rn(e,n,r,o){if(null==o&&(o=L(e)),"complex64"===o)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=n){K(n);var a=g(n),i=g(r);d(a===i,function(){return"Based on the provided shape, ["+n+"], the tensor should have "+a+" values but has "+i});for(var s=0;s<r.length;++s){var u=r[s],l=s!==r.length-1||u!==g(n.slice(s));d(r[s]===n[s]||!l,function(){return"Error creating a new Tensor. Inferred shape ("+r+") does not match the provided shape ("+n+"). "})}}return _(e)||Array.isArray(e)||(e=[e]),n=n||r,e="string"!==o?z(e,o,t.ENV.getBool("DEBUG")):m(e,[],!0),ct.make(n,{values:e},o)}function on(t,e){if((_(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&_(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return rn(t,[],[],e)}function an(t,e){v(t);var n=Le(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return rn(t,null,n,e)}function sn(t,e,n){if(v(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=Le(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return rn(t,e,r,n)}function un(t,e,n){if(v(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=Le(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return rn(t,e,r,n)}function ln(t,e,n){if(v(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=Le(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return rn(t,e,r,n)}function cn(t,e,n){if(v(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=Le(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return rn(t,e,r,n)}function hn(t,e,n){if(v(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=Le(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return rn(t,e=e||r,r,n)}function pn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=pn(t,"float32"),r=dn(t,"float32");return Ze(n,r)}var o=H(g(t),e);return ct.make(t,{values:o},e)}function dn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=dn(t,"float32"),r=dn(t,"float32");return Ze(n,r)}var o=q(g(t),e);return ct.make(t,{values:o},e)}function fn(t,e,n){return St.runKernel(function(r){return r.fill(t,e,n)},{})}function vn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return St.runKernel(function(r){return r.linspace(t,e,n)},{})}function mn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return dn([0],r);var o=q(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return an(o,r)}var gn=Je({onesLike_:function(t){var e=We(t,"x","onesLike");if("complex64"===e.dtype){var n=gn(tn(e)),r=yn(en(e));return Ze(n,r)}return St.runKernel(function(t){return t.onesLike(e)},{$x:e},function(t,e){return{$x:function(){return yn(t)}}})}}),yn=Je({zerosLike_:function(t){var e=We(t,"x","zerosLike");return St.runKernel(function(t){return t.zerosLike(e)},{$x:e},function(t,e){return{$x:function(){return yn(t)}}})}});var xn=Je({concat_:function(t,e){void 0===e&&(e=0),d(t.length>=1,function(){return"Pass at least one tensor to concat"});var n=Ue(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n          with dtype "+t.dtype+". ")}),e=R(e,n[0].shape)[0];var r=Qe(n.map(function(t){return t.shape}),e);if(0===g(r))return nn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var o=n.map(function(t){return t.shape});Ye(o,e);var a=n;return St.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=o.map(function(t){return t[e]});return Nn(t,n,e).map(function(t){return function(){return t}})})}}),bn=Je({concat1d_:function(t){return xn(t,0)}}),wn=Je({concat2d_:function(t,e){return xn(t,e)}}),Cn=Je({concat3d_:function(t,e){return xn(t,e)}}),En=Je({concat4d_:function(t,e){return xn(t,e)}}),Nn=Je({split_:function(t,e,n){void 0===n&&(n=0);var r,o=We(t,"x","split");return n=R(n,o.shape)[0],"number"==typeof e?(d(o.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(o.shape[n]/e)):(d(o.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),St.runKernel(function(t){return t.split(o,r,n)},{$x:o},function(t){return{$x:function(){return xn(t,n)}}})}});"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Rn(t,e){return t(e={exports:{}},e.exports),e.exports}var In=Rn(function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.alea=a}(0,t,!1)}),kn=Rn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a}(0,t,!1)}),Sn=Rn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a}(0,t,!1)}),An=Rn(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a}(0,t,!1)}),Tn=Rn(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o}(e,t)}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a}(0,t,!1)}),Dn=Rn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a}(0,t,!1)}),_n=Rn(function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),l=n.pow(2,52),c=2*l,h=a-1;function p(t,h,p){var g=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==a?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,m(e)]}}():t,3),g),x=new d(g),b=function(){for(var t=x.g(i),e=u,n=0;t<l;)t=(t+n)*a,e*=a,n=x.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,v(m(x.S),e),(h.pass||p||function(t,e,r,o){return o&&(o.S&&f(o,x),t.state=function(){return f(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function d(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o<a;)s[o]=o++;for(o=0;o<a;o++)s[o]=s[i=h&i+t[o%n]+(e=s[o])],s[i]=e;(r.g=function(t){for(var e,n=0,o=r.i,i=r.j,s=r.S;t--;)e=s[o=h&o+1],n=n*a+s[h&(s[o]=s[i=h&i+e])+(s[i]=e)];return r.i=o,r.j=i,n})(a)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function v(t,e){for(var n,r=t+"",o=0;o<r.length;)e[h&o]=h&(n^=19*e[h&o])+r.charCodeAt(o++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=p,v(n.random(),e),t.exports){t.exports=p;try{r=require("crypto")}catch(t){}}}([],Math)});_n.alea=In,_n.xor128=kn,_n.xorwow=Sn,_n.xorshift7=An,_n.xor4096=Tn,_n.tychei=Dn;var On=_n.alea,Fn=function(){function t(t,e,n,r,o){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var a=o||Math.random();this.random=On(a.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var o=void 0,a=void 0,i=void 0;do{i=(o=2*this.random()-1)*o+(a=2*this.random()-1)*a}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Mn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=On(o.toString()),this.randn=new Fn(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,o,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(o=this.randu())<e||Math.log(o)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),Bn=function(){function t(t,e,n,r){var o=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==o.dtype||"float32"===o.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=On(r)}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}();function Pn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",K(t),new it(t,e,n)}function Ln(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Vn=Je({batchToSpaceND_:function(t,e,n){var r=We(t,"x","batchToSpaceND"),o=e.reduce(function(t,e){return t*e});return d(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),d(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length  "+e.length}),d(r.shape[0]%o==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o}),St.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Wn=Je({cast_:function(t,e){var n=We(t,"x","cast");if(!T(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return St.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Un=Je({clone_:function(t){var e=We(t,"x","clone",null);return St.runKernel(function(t){return ct.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),zn=Je({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=We(t,"x","cumsum"),a=Ke([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=Xe(1,o.rank)[0],u=St.runKernel(function(t){return t.cumsum(i,s,n,r)},{permutedX:i},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),Gn=Je({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=We(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return d(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+o+" and "+e+"  for depthToSpace with input shape\n      "+r.shape}),d(a*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+a+" and "+e+" for depthToSpace with input shape\n          "+r.shape}),d(i%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape}),St.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Hn=Je({expandDims_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","expandDims",null);d(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(d(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),rr(n,r)}}),qn=Je({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=Pn([t,e],r),a=t<=e?t:e,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return sr(Hn(s,0),[n[0],1,1]);if(2===n.length)return sr(Hn(Hn(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return sr(Hn(Hn(Hn(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),$n=Je({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=We(t,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=St.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===i?u.as1D():u}}),Kn=Je({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var o=We(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),St.runKernel(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return{$indices:function(){return dn(o.shape,"float32")}}}).reshape(a)}}),jn=Je({pad_:function(t,e,n){void 0===n&&(n=0);var r=We(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o=e.map(function(t){return t[0]});return St.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape)}}})}}),Xn=Je({pad1d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),jn(t,[e],n)}}),Yn=Je({pad2d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),jn(t,e,n)}}),Qn=Je({pad3d_:function(t,e,n){return void 0===n&&(n=0),d(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),jn(t,e,n)}}),Jn=Je({pad4d_:function(t,e,n){return void 0===n&&(n=0),d(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),jn(t,e,n)}}),Zn=Je({rand_:function(t,e,n){var r=g(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r)}for(var a=0;a<r;a++)o[a]=e();return ct.make(t,{values:o},n)}}),tr=Je({randomNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new Fn(e,n,r,!1,o),i=Pn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),er=Je({randomGamma_:function(t,e,n,r,o){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var a=new Mn(e,n,r,o),i=Pn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),nr=Je({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=Pn(t,r),i=new Bn(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),rr=Je({reshape_:function(t,e){var n=We(t,"x","reshape",null);return e=N(e,n.size),d(n.size===g(e),function(){return"new shape and old shape must have the same number of elements."}),St.runKernel(function(t){return t.reshape(n,e)},{$x:n},function(t){return{$x:function(){return t.reshape(n.shape)}}})}}),or=Je({spaceToBatchND_:function(t,e,n){var r=We(t,"x","spaceToBatchND");return d(r.rank>=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),d(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),d(r.shape.reduce(function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),St.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),ar=Je({squeeze_:function(t,e){var n=We(t,"x","squeeze");return rr(n,I(n.shape,e).newShape)}}),ir=Je({stack_:function(t,e){void 0===e&&(e=0);var n=Ue(t,"tensors","stack");if(d(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,o=n[0].shape,a=n[0].dtype;d(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){f(o,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){d(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=n.map(function(t){return t.expandDims(e)});return xn(i,e)}}),sr=Je({tile_:function(t,e){var n=We(t,"x","tile",null);return d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),St.runKernel(function(t,r){var o=t.tile(n,e);return r([n]),o},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=yn(r);if(1===r.rank)for(var o=0;o<e[0];++o)n=n.add(t.slice([o*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(o=0;o<e[0];++o)for(var a=0;a<e[1];++a)n=n.add(t.slice([o*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(var i=0;i<e[2];++i)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(i=0;i<e[2];++i)for(var s=0;s<e[3];++s)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}})}}),ur=Je({truncatedNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new Fn(e,n,r,!0,o),i=Pn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),lr=Je({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=We(t,"x","unstack");return d(e>=-n.shape.length&&e<n.shape.length,function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"}),e<0&&(e+=n.shape.length),St.runKernel(function(t){return t.unstack(n,e)},{$x:n},function(t){return{$x:function(){return ir(t,e)}}})}}),cr=function(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return n=We(t,"x","setdiff1d"),r=We(e,"y","setdiff1d"),d(n.dtype===r.dtype,function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."}),d(1===n.rank,function(){return"x should be 1D tensor, but got x ("+n.shape+")."}),d(1===r.rank,function(){return"y should be 1D tensor, but got y ("+r.shape+")."}),[4,n.data()];case 1:return a=o.sent(),[4,r.data()];case 2:for(i=o.sent(),s=new Set(i),u=0,h=0;h<a.length;h++)s.has(a[h])||u++;for(l=new it([u],n.dtype),c=new it([u],"int32"),h=0,p=0;h<a.length;h++)s.has(a[h])||(l.values[p]=a[h],c.values[p]=h,p++);return[2,[l.toTensor(),c.toTensor()]]}})})};function hr(t,e,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(e.slice(0))).push(t[0]/n),o=o.concat(t.slice(1));else{o=o.concat(t[0]);for(var a=e.length,i=0;i<a;++i)o=o.concat([t[i+1]/e[i],e[i]]);o=o.concat(t.slice(a+1))}return o}function pr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var o=e+1;o<t;++o)o<=2*e?(r.push(o),r.push(o-(e+1))):r.push(o)}else{var a=[],i=[];for(o=1;o<t;++o)o>=2*e+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 dr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?o.push(e[a-1]*t[a]):o.push(t[a]/e[a-1]):o.push(t[a]);return o}function fr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function vr(t,e,n){for(var r=t.slice(0,1),o=0;o<n;++o)r.push(t[o+1]-e[o][0]-e[o][1]);return r}function mr(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],o=1,a=0;a<n.length-1;++a)o*=n[a];var i=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=i[a],s.push(i[a]);var l=U(t.shape).map(function(t){return t/u}).concat([1]).slice(0,r);return[s,o,u,l]}var gr=30;function yr(t){return t<=gr?t:W(t,Math.floor(Math.sqrt(t)))}function xr(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank<o)throw new Error(a+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(a+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(a+" update.rank != "+(o+t.length-r));for(var i=0;i<o;++i)if(n.shape[i]!==e.shape[i])throw new Error(a+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-o;++i)if(n.shape[i+o]!==t[i+r])throw new Error(a+" updates.shape["+(i+o)+"] ("+n.shape[i+o]+") != shape["+(i+o)+"] ("+t[i+o]+")")}(n,e,t)}function br(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,o=n.length,a=1,i=r;i<o;++i)a*=n[i];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:a,strides:U(n.slice(0,r)).concat([1]),outputSize:g(n)}}function wr(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function Cr(t,e,n){for(var r=[],o=0;o<t.length;o++)r[o]=Math.ceil((e[o]-t[o])/n[o]);return r}function Er(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=c(0,a,s-1)}function Nr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?c(0,a,s):c(-1,a,s-1)}function Rr(t,e,n){for(var r=n.length,o=0;o<n.length;o++)if(n[o]>1){r=o;break}for(o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0}function Ir(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}function kr(t,e){d(V(t),function(){return"The f passed in variableGrads(f) must be a function"}),d(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof ht}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var n=null!=e;if(!n)for(var r in e=[],St.registeredVariables)e.push(St.registeredVariables[r]);var o=n?e.filter(function(t){return!t.trainable}):null,a=e.length;d((e=e.filter(function(t){return t.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var i=St.gradients(t,e,null,!0),s=i.value,u=i.grads;d(u.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),d(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e])}),null!=o&&o.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Sr(t){return St.customGrad(t)}function Ar(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.")}var Tr=Je({softmax_:function(t,e){void 0===e&&(e=-1);var n=We(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Sr(function(t,n){var r=t.logSumExp([e],!0),o=t.toFloat().sub(r).exp();return n([o]),{value:o,gradFunc:function(t,n){var r=n[0],o=t.mul(r);return o.sub(o.sum([e],!0).mul(r))}}})(n)}}),Dr=Je({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=We(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Sr(function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),_r=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),Or=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t){t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights;throw new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.isNaN=function(t){throw new Error("Not yet implemented")},t.prototype.isInf=function(t){throw new Error("Not yet implemented")},t.prototype.isFinite=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.fusedConv2d=function(t,e,n,r,o,a){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.avgPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPool3dBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPool3dBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,o,a){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,o,a){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.diag=function(t){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function Fr(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var a=n-1-o,i=t[a]||1;(e[e.length-1-o]||1)>1&&1===i&&r.unshift(a)}return r}function Mr(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],a=e.length-r-1,i=e[a];(null==o||1===o&&i>1)&&n.unshift(a)}return n}function Br(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var a=t[t.length-o-1];null==a&&(a=1);var i=e[e.length-o-1];if(null==i&&(i=1),1===a)n.unshift(i);else if(1===i)n.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a)}}return n}function Pr(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=zr(e),l=u[0],c=u[1];if("channelsLast"===i)s=[l,c,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[l,c,t[1],t[1]]}return Vr(t,s,n,r,o,a,!1,i)}function Lr(t,e,n,r,o,a,i){void 0===i&&(i="NDHWC");var s,u,l=Gr(e),c=l[0],h=l[1],p=l[2];if("NDHWC"===i)u="channelsLast",s=[c,h,p,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[c,h,p,t[1],t[1]]}return Wr(t,s,n,r,o,!1,u,a)}function Vr(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],h=u[2],p=u[3];if("channelsLast"===s)l=t[0],c=t[1],h=t[2],p=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=t[0],p=t[1],c=t[2],h=t[3]}var f,v=e[0],m=e[1],g=e[3],y=zr(n),b=y[0],w=y[1],C=zr(r),E=C[0],N=C[1],R=Hr(v,E),I=Hr(m,N),k=function(t,e,n,r,o,a,i,s){var u,l,c;if("number"==typeof t){var h=0===t?"VALID":"NUMBER";u={top:t,bottom:t,left:t,right:t,type:h};var p=function(t,e,n,r,o){null==r&&(r=Ur(t,e,n));var a=t[0],i=t[1],s=qr((a-e+2*r)/n+1,o);d(x(s),function(){return"The output # of rows ("+s+") must be an integer. Change the stride and/or zero pad parameters"});var u=qr((i-e+2*r)/n+1,o);return d(x(u),function(){return"The output # of columns ("+u+") must be an integer. Change the stride and/or zero pad parameters"}),[s,u]}([e,n],a,r,t,s);l=p[0],c=p[1]}else if("same"===t){l=Math.ceil(e/r),c=Math.ceil(n/o);var f=Math.max(0,(l-1)*r+a-e),v=Math.max(0,(c-1)*o+i-n),m=Math.floor(f/2),g=f-m,y=Math.floor(v/2),b=v-y;u={top:m,bottom:g,left:y,right:b,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((e-a+1)/r),c=Math.ceil((n-i+1)/o)}return{padInfo:u,outHeight:l,outWidth:c}}(o,c,h,b,w,R,I,a),S=k.padInfo,A=k.outHeight,T=k.outWidth,D=i?g*p:g;return"channelsFirst"===s?f=[l,D,A,T]:"channelsLast"===s&&(f=[l,A,T,D]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:h,inChannels:p,outHeight:A,outWidth:T,outChannels:D,padInfo:S,strideHeight:b,strideWidth:w,filterHeight:v,filterWidth:m,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:E,dilationWidth:N,inShape:t,outShape:f,filterShape:e}}function Wr(t,e,n,r,o,a,i,s){void 0===a&&(a=!1),void 0===i&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],l=u[0],c=u[1],h=u[2],p=u[3],f=u[4];if("channelsLast"===i)l=t[0],c=t[1],h=t[2],p=t[3],f=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);l=t[0],f=t[1],c=t[2],h=t[3],p=t[4]}var v,m=e[0],g=e[1],y=e[2],b=e[4],w=Gr(n),C=w[0],E=w[1],N=w[2],R=Gr(r),I=R[0],k=R[1],S=R[2],A=Hr(m,I),T=Hr(g,k),D=Hr(y,S),_=function(t,e,n,r,o,a,i,s,u,l,c){var h,p,f,v;if("number"==typeof t){var m=0===t?"VALID":"NUMBER";h={top:t,bottom:t,left:t,right:t,front:t,back:t,type:m};var g=function(t,e,n,r,o,a){null==o&&(o=Ur(t,e,r));var i=t[0],s=t[1],u=t[2],l=qr((i-e+2*o)/r+1,a);d(x(l),function(){return"The output # of depths ("+l+") must be an integer. Change the stride and/or zero pad parameters"});var c=qr((s-e+2*o)/r+1,a);d(x(c),function(){return"The output # of rows ("+c+") must be an integer. Change the stride and/or zero pad parameters"});var h=qr((u-e+2*o)/r+1,a);return d(x(h),function(){return"The output # of columns ("+h+") must be an integer. Change the stride and/or zero pad parameters"}),[l,c,h,n]}([e,n,r,1],s,1,o,t,c);p=g[0],f=g[1],v=g[2]}else if("same"===t){p=Math.ceil(e/o),f=Math.ceil(n/a),v=Math.ceil(r/i);var y=(p-1)*o+s-e,b=(f-1)*a+u-n,w=(v-1)*i+l-r,C=Math.floor(y/2),E=y-C,N=Math.floor(b/2),R=b-N,I=Math.floor(w/2),k=w-I;h={top:N,bottom:R,left:I,right:k,front:C,back:E,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((e-s+1)/o),f=Math.ceil((n-u+1)/a),v=Math.ceil((r-l+1)/i)}return{padInfo:h,outDepth:p,outHeight:f,outWidth:v}}(o,c,h,p,C,E,N,A,T,D,s),O=_.padInfo,F=_.outDepth,M=_.outHeight,B=_.outWidth,P=a?b*f:b;return"channelsFirst"===i?v=[l,P,F,M,B]:"channelsLast"===i&&(v=[l,F,M,B,P]),{batchSize:l,dataFormat:i,inDepth:c,inHeight:h,inWidth:p,inChannels:f,outDepth:F,outHeight:M,outWidth:B,outChannels:P,padInfo:O,strideDepth:C,strideHeight:E,strideWidth:N,filterDepth:m,filterHeight:g,filterWidth:y,effectiveFilterDepth:A,effectiveFilterHeight:T,effectiveFilterWidth:D,dilationDepth:I,dilationHeight:k,dilationWidth:S,inShape:t,outShape:v,filterShape:e}}function Ur(t,e,n,r){void 0===r&&(r=1);var o=Hr(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function zr(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function Gr(t){return"number"==typeof t?[t,t,t]:t}function Hr(t,e){return e<=1?t:t+(t-1)*(e-1)}function qr(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function $r(t){var e=zr(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Kr(t,e){return $r(t)||$r(e)}function jr(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function Xr(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=dn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a}if(!D(t.dtype,e))return ct.make(t.shape,{dataId:t.dataId},e);if("complex64"===t.dtype){var i=n.real(t);a=i.cast(e);return i.dispose(),a}if("int32"===e)return n.int(t);if("bool"===e){var s=on(0,t.dtype);a=n.notEqual(t,s);return s.dispose(),a}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Yr(t,e){return ct.make(e,{dataId:t.dataId},t.dtype)}function Qr(t,e,n){var r=(e-t)/(n-1),o=q(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return an(o,"float32")}var Jr=Object.freeze({castTensor:Xr,reshapeTensor:Yr,linspaceImpl:Qr,upcastType:xt,axesAreInnerMostDims:ze,combineLocations:Ge,computeOutAndReduceShapes:He,expandShapeToKeepDim:qe,assertAxesAreInnerMostDims:$e,getAxesPermutation:Ke,getUndoAxesPermutation:je,getInnerMostAxes:Xe,getBroadcastDims:Fr,getReductionAxes:Mr,assertAndGetBroadcastShape:Br,assertParamsConsistent:Ye,computeOutShape:Qe,computePool2DInfo:Pr,computePool3DInfo:Lr,computeConv2DInfo:Vr,computeConv3DInfo:Wr,computeDefaultPad:Ur,tupleValuesAreOne:$r,eitherStridesOrDilationsAreOne:Kr,convertConv2DDataFormat:jr});function Zr(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function to(t,e){return{real:t[2*e],imag:t[2*e+1]}}function eo(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function no(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function ro(t,e,n,r,o){for(var a=Array.from(e).map(function(t,e){return{score:t,boxIndex:e}}).filter(function(t){return t.score>o}).sort(function(t,e){return e.score-t.score}),i=[],s=0;s<a.length;s++){var u=a[s],l=u.score,c=u.boxIndex;if(l<o)break;for(var h=!1,p=i.length-1;p>=0;--p){if(oo(t,c,i[p])>=r){h=!0;break}}if(!h&&(i.push(c),i.length>=n))break}return an(i,"int32")}function oo(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),d=(s-a)*(u-i),f=(h-l)*(p-c);if(d<=0||f<=0)return 0;var v=Math.max(a,l),m=Math.max(i,c),g=Math.min(s,h),y=Math.min(u,p),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(d+f-x)}function ao(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a})}function io(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=Pn(n,t.dtype);for(r=0;r<o.values.length;++r){for(var a=o.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=a[s]%t.shape[s];var u=t.locToIndex(i);o.values[r]=t.values[u]}return o.toTensor()}function so(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],l=k(n,s*r),c=k("int32",s*r),h=0;h<s;h++){for(var p=h*u,d=t.subarray(p,p+u),f=[],v=0;v<d.length;v++)f.push({value:d[v],index:v});f.sort(function(t,e){return e.value-t.value});var m=h*r,g=l.subarray(m,m+r),y=c.subarray(m,m+r);for(v=0;v<r;v++)g[v]=f[v].value,y[v]=f[v].index}var x=e.slice();return x[x.length-1]=r,[nn(l,x,n),nn(c,x,"int32")]}function uo(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=Pn(t,"int32"),a=Pn([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=o.indexToLoc(n[r]),s=r*t.length;a.values.set(i,s)}return a.toTensor()}var lo=function(){return function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();")});var r=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n      void main() {\n        "+n.join("\n        ")+"\n\n        float result = "+r+";\n        setOutput(result);\n      }\n    "}}(),co=function(){return function(t,e){this.outputShape=[],this.usesPackedTextures=!0,this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")});var r=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n      void main() {\n        "+n.join("\n        ")+"\n\n        vec4 result = "+r+";\n        setOutput(result);\n      }\n    "}}(),ho=function(){return function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,a=t.inSize,i=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+r+";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < "+r+"; i++) {\n          int inIdx = "+u+";\n          float candidate = getA(batch, inIdx);\n          if (candidate "+s+" bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    "}}();function po(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function fo(t,e){return 1===e?[t]:po(t,e)}function vo(){var e,n,r,o,a,i,s,u,l,c;return 2===t.ENV.getNumber("WEBGL_VERSION")?(e="#version 300 es",n="in",r="out",o="in",a="texture",i="outputColor",s="out vec4 outputColor;",u="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 0. || val == 0.) ? false : true;\n      }\n    ",l="",c="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(e="",n="attribute",r="varying",o="varying",a="texture2D",i="gl_FragColor",s="",u="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n    ",l="\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    ",c="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:e,attribute:n,varyingVs:r,varyingFs:o,texture2D:a,output:i,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function mo(t,e,n){void 0===n&&(n="index");var r=U(e);return r.map(function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"}).join("")}function go(t){var e=U(t).map(function(t){return t.toString()});return"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n  }\n"}var yo="\n  const float FLOAT_MAX = 1.70141184e38;\n  const float FLOAT_MIN = 1.17549435e-38;\n\n  lowp vec4 encode_float(highp float v) {\n    if (isnan(v)) {\n      return vec4(255, 255, 255, 255);\n    }\n\n    highp float av = abs(v);\n\n    if(av < FLOAT_MIN) {\n      return vec4(0.0, 0.0, 0.0, 0.0);\n    } else if(v > FLOAT_MAX) {\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n    } else if(v < -FLOAT_MAX) {\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n    }\n\n    highp vec4 c = vec4(0,0,0,0);\n\n    highp float e = floor(log2(av));\n    highp float m = exp2(fract(log2(av))) - 1.0;\n\n    c[2] = floor(128.0 * m);\n    m -= c[2] / 128.0;\n    c[1] = floor(32768.0 * m);\n    m -= c[1] / 32768.0;\n    c[0] = floor(8388608.0 * m);\n\n    highp float ebias = e + 127.0;\n    c[3] = floor(ebias / 2.0);\n    ebias -= c[3] * 2.0;\n    c[2] += floor(ebias) * 128.0;\n\n    c[3] += 128.0 * step(0.0, -v);\n\n    return c / 255.0;\n  }\n";function xo(t,e,n,r){var o=[];t.forEach(function(t){var e=g(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"))});var a,i,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?wo(t):bo(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Fr(t.shapeInfo.logicalShape,e.logicalShape),l=So(s),c=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+h[t+c]+" = 0;"}).join("\n");var p="";p=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+c]}).join(", ");var d="return outputValue;",f=1===g(t.shapeInfo.logicalShape),v=1===g(e.logicalShape);if(1!==i||f||v){if(f&&!v)d=1===s?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(u.length){var m=i-2,y=i-1;u.indexOf(m)>-1&&u.indexOf(y)>-1?d="return vec4(outputValue.x);":u.indexOf(m)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(y)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return"\n    vec4 "+a+"() {\n      "+l+" coords = getOutputCoords();\n      "+n+"\n      vec4 outputValue = get"+o+"("+p+");\n      "+d+"\n    }\n  "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&y(i,a))return"\n      float "+o+"() {\n        return sampleTexture("+n+", resultUV);\n      }\n    ";var l,c=So(u),h=Fr(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,d=["x","y","z","w","u","v"];l=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map(function(t){return"coords."+d[t+p]+" = 0;"}).join("\n");var f="";f=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+d[e+p]}).join(", ");return"\n    float "+o+"() {\n      "+c+" coords = getOutputCoords();\n      "+l+"\n      return get"+r+"("+f+");\n    }\n  "}(t,e));return r}(t,e,r)}).join("\n"),l=e.texShape,c=vo(),h=function(t){return"\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+t.texture2D+"(textureSampler, uv).r;\n    }\n  "}(c),p=function(t){return t.version+"\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    "+t.varyingFs+" vec2 resultUV;\n    "+t.defineOutput+"\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    #define isnan(value) isnan_custom(value)\n    "+t.defineSpecialNaN+"\n    bvec4 isnan_custom(vec4 val) {\n      return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n    }\n\n    "+t.defineSpecialInf+"\n    "+t.defineRound+"\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    "+Co+"\n    "+Eo+"\n    "+No+"\n  "}(c);return e.isPacked?(a=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(1===n[0])return"\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * "+n[1]+".0);\n      }\n    ";if(1===n[1])return"\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * "+n[0]+".0);\n      }\n    ";return"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n    }\n  "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y(t,e))return"\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n      }\n    ";var r=Math.ceil(t[1]/2);return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec2(r, c);\n    }\n  "}(t,e);case 3:return n=t,r=e,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Math.ceil(n[2]/2),i=a*Math.ceil(n[1]/2),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+o[0]+", "+o[1]+"));\n      int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n      int b = index / "+i+";\n      index -= b * "+i+";\n\n      int r = 2 * (index / "+a+");\n      int c = imod(index, "+a+") * 2;\n\n      return ivec3(b, r, c);\n    }\n  ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u<t.length-1;u++)a*=t[t.length-u-1],i="\n      int b"+u+" = index / "+a+";\n      index -= b"+u+" * "+a+";\n    "+i,s="b"+u+", "+s;return"\n    ivec"+t.length+" getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n      "+i+"\n\n      int b = index / "+o+";\n      index -= b * "+o+";\n\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec"+t.length+"("+s+");\n    }\n  "}(t,e)}var n,r,o,a,i}(e.logicalShape,l),i=function(t){return"\n    void setOutput(vec4 val) {\n      "+t.output+" = val;\n    }\n  "}(c)):(a=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){if(1===e[0])return"\n      int getOutputCoords() {\n        return int(resultUV.x * "+e[1]+".0);\n      }\n    ";if(1===e[1])return"\n      int getOutputCoords() {\n        return int(resultUV.y * "+e[0]+".0);\n      }\n    ";return"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      return resTexRC.x * "+e[1]+" + resTexRC.y;\n    }\n  "}(0,e);case 2:return function(t,e){if(y(t,e))return"\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n      }\n    ";if(1===t[1])return"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ";if(1===t[0])return"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ";return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      int r = index / "+t[1]+";\n      int c = index - r * "+t[1]+";\n      return ivec2(r, c);\n    }\n  "}(t,e);case 3:return n=e,r=mo(["r","c","d"],t),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      "+r+"\n      return ivec3(r, c, d);\n    }\n  ";case 4:return function(t,e){var n=mo(["r","c","d","d2"],t);return"\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      "+n+"\n      return ivec4(r, c, d, d2);\n    }\n  "}(t,e);case 5:return function(t,e){var n=mo(["r","c","d","d2","d3"],t);return"\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n                             "+e[1]+"));\n\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  "}(t,e);case 6:return function(t,e){var n=mo(["r","c","d","d2","d3","d4"],t);return"\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,l),i=function(t){return"\n    void setOutput(float val) {\n      "+t.output+" = vec4(val, 0, 0, 0);\n    }\n  "}(c)),r&&(p+=Ro),[p,h,i,s,a,u,n].join("\n")}function bo(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===o&&1===a)return"\n      float "+n+"() {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=t.shapeInfo.texShape,s=i[0],u=i[1],l=Io(e);return"\n    float "+n+"() {\n      vec2 uv = uvFromFlat("+s+", "+u+", "+l+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n      float "+n+"(int index) {\n        "+ko(t)+"\n      }\n    ";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===a&&1===o)return"\n      float "+n+"(int index) {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=Io(e);if(1===a)return"\n      float "+n+"(int index) {\n        vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+o+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";if(1===o)return"\n      float "+n+"(int index) {\n        vec2 uv = vec2((float(index + "+i+") + 0.5) / "+a+".0, 0.5);\n        return sampleTexture("+e+", uv);\n      }\n    ";return"\n    float "+n+"(int index) {\n      vec2 uv = uvFromFlat("+o+", "+a+", index + "+i+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape;if(null!=o&&y(e,o)){var a=o[0],i=o[1];return"\n    float "+r+"(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n      return sampleTexture("+n+", uv);\n    }\n  "}var s=I(e),u=s.newShape,l=s.keptDims,c=u;if(c.length<e.length){var h=Ao(t,c);return"\n      "+bo(h)+"\n      float "+r+"(int row, int col) {\n        return "+r+"("+To(["row","col"],l)+");\n      }\n    "}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n        "+ko(t)+"\n      }\n    ";var p=o[0],d=o[1],f=Io(n);if(1===d)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+f+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";if(1===p)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+f+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+d+".0, 0.5);\n      return sampleTexture("+n+", uv);\n    }\n  ";return"\n  float "+r+"(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * "+e[1]+" + col + "+f+";\n    vec2 uv = uvFromFlat("+p+", "+d+", index);\n    return sampleTexture("+n+", uv);\n  }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[1]*e[2],a=e[2],i=I(e),s=i.newShape,u=i.keptDims,l=s;if(l.length<e.length){var c=Ao(t,l);return"\n        "+bo(c)+"\n        float "+r+"(int row, int col, int depth) {\n          return "+r+"("+To(["row","col","depth"],u)+");\n        }\n      "}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3("+o+", "+a+", 1)));\n        "+ko(t)+"\n      }\n    ";var h=t.shapeInfo.texShape,p=h[0],d=h[1],f=t.shapeInfo.flatOffset;if(d===o&&null==f)return"\n        float "+r+"(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2("+a+", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2("+d+".0, "+p+".0);\n          return sampleTexture("+n+", uv);\n        }\n      ";if(d===a&&null==f)return"\n    float "+r+"(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+d+".0, "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";var v=Io(n);return"\n      float "+r+"(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * "+o+" + col * "+a+" + depth + "+v+";\n        vec2 uv = uvFromFlat("+p+", "+d+", index);\n        return sampleTexture("+n+", uv);\n      }\n  "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[3],a=e[2]*o,i=e[1]*a,s=I(e),u=s.newShape,l=s.keptDims;if(u.length<e.length){var c=Ao(t,u);return"\n      "+bo(c)+"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        return "+r+"("+To(["row","col","depth","depth2"],l)+");\n      }\n    "}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4("+i+", "+a+", "+o+", 1)));\n        "+ko(t)+"\n      }\n    ";var h=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,d=p[0],f=p[1];if(f===i&&null==h)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3("+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+f+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(f===o&&null==h)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3("+e[1]*e[2]+", "+e[2]+", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+f+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var v=Io(n);return"\n    float "+r+"(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+i+" + col * "+a+" +\n          depth * "+o+" + depth2;\n      vec2 uv = uvFromFlat("+d+", "+f+", index + "+v+");\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[4],a=e[3]*o,i=e[2]*a,s=e[1]*i,u=I(e),l=u.newShape,c=u.keptDims;if(l.length<e.length){var h=Ao(t,l);return"\n      "+bo(h)+"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+r+"("+To(["row","col","depth","depth2","depth3"],c)+");\n      }\n    "}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+s+", "+i+", "+a+", "+o+")) +\n          depth3;\n        "+ko(t)+"\n      }\n    ";var p=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,f=d[0],v=d[1];if(v===s&&null==p)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4("+i+", "+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+v+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(v===o&&null==p)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]+",\n               "+e[2]*e[3]+", "+e[3]+", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+v+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var m=Io(n);return"\n    float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+s+" + col * "+i+" + depth * "+a+" +\n          depth2 * "+o+" + depth3 + "+m+";\n      vec2 uv = uvFromFlat("+f+", "+v+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=I(e),a=o.newShape,i=o.keptDims;if(a.length<e.length){var s=Ao(t,a);return"\n      "+bo(s)+"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+r+"("+To(["row","col","depth","depth2","depth3","depth4"],i)+");\n      }\n    "}var u=e[5],l=e[4]*u,c=e[3]*l,h=e[2]*c,p=e[1]*h;if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4("+p+", "+h+", "+c+", "+l+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+u+", 1)));\n        "+ko(t)+"\n      }\n    ";var d=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,v=f[0],m=f[1];if(m===p&&null==d)return"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4("+h+", "+c+", "+l+", "+u+")) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+m+".0, "+v+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(m===u&&null==d)return"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]*e[4]+",\n               "+e[2]*e[3]*e[4]+",\n               "+e[3]*e[4]+",\n               "+e[4]+")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+m+".0, "+v+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var g=Io(n);return"\n    float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+p+" + col * "+h+" + depth * "+c+" +\n          depth2 * "+l+" + depth3 * "+u+" + depth4 + "+g+";\n      vec2 uv = uvFromFlat("+v+", "+m+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function wo(t){var e,n,r;switch(t.shapeInfo.logicalShape.length){case 0:return e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=vo(),"\n    vec4 "+n+"() {\n      return "+r.texture2D+"("+e+", halfCR);\n    }\n  ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=vo();return"\n    vec4 "+n+"(int index) {\n      vec2 uv = packedUVfrom1D(\n        "+o[0]+", "+o[1]+", index);\n      return "+a.texture2D+"("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=o[0],i=o[1],s=vo();if(null!=o&&y(e,o))return"\n      vec4 "+r+"(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n        return "+s.texture2D+"("+n+", uv);\n      }\n    ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=Math.ceil(e[1]/2);return"\n    vec4 "+r+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+l+", "+u[0]+", "+u[1]+", row, col);\n      return "+s.texture2D+"("+n+", uv);\n    }\n  "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0]){var i=e.slice(1),s=Ao(t,i);return"\n        "+wo(s)+"\n        vec4 "+r+"(int b, int row, int col) {\n          return "+r+"("+To(["b","row","col"],[1,2])+");\n        }\n      "}var u=a[0],l=a[1],c=Math.ceil(e[2]/2),h=c*Math.ceil(e[1]/2),p=vo();return"\n    vec4 "+r+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+u+", "+l+", "+h+", "+c+", b, row, col);\n      return "+p.texture2D+"("+n+", uv);\n    }\n  "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],u=i[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),h="int b, int row, int col",p="b * "+c+" + (row / 2) * "+l+" + (col / 2)",d=2;d<n-1;d++)h="int b"+d+", "+h,c*=e[n-d-1],p="b"+d+" * "+c+" + "+p;var f=vo();return"\n    vec4 "+o+"("+h+") {\n      int index = "+p+";\n      int texR = index / "+u+";\n      int texC = index - texR * "+u+";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n      return "+f.texture2D+"("+r+", uv);\n    }\n  "}(t)}}var Co="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n  int texelIndex = index / 2;\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Eo="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n  int texNumC, int row, int col) {\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",No="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n    int texelsInBatch, int texelsInLogicalRow, int b,\n    int row, int col) {\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Ro="\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n";function Io(t){return"offset"+t}function ko(t){var e=t.name,n=g(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n    for (int i = 0; i < "+n+"; i++) {\n      if (i == index) {\n        return "+e+"[i];\n      }\n    }\n  "}function So(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function Ao(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function To(t,e){return e.map(function(e){return t[e]}).join(", ")}var Do=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,d(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,l=u.length,c=So(l),h=fo("coords",l);if(1===a){var p=So(s=l+1);i="\n        "+p+" sourceLocR = "+p+"("+h.join()+", 0);\n        ++"+h[l-1]+";\n        "+p+" sourceLocG = "+p+"("+h.join()+", 0);\n        ++"+h[l-2]+";\n        "+p+" sourceLocA = "+p+"("+h.join()+", 0);\n        --"+h[l-1]+";\n        "+p+" sourceLocB = "+p+"("+h.join()+", 0);\n        --"+h[l-2]+";"}else s=l,i="\n        "+c+" sourceLocR = coords;\n        ++"+h[l-1]+";\n        "+c+" sourceLocG = coords;\n        ++"+h[l-2]+";\n        "+c+" sourceLocA = coords;\n        --"+h[l-1]+";\n        "+c+" sourceLocB = coords;\n        --"+h[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),v="."+f[s-1],m=f.map(function(t){return"int "+t}),g=fo("sourceLocR",s-1).concat("inIdx.r"),y=fo("sourceLocG",s-1).concat("inIdx.g"),x=fo("sourceLocB",s-1).concat("inIdx.b"),b=fo("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n                             getBestIndicesAChannel("+y.join()+"),\n                             getBestIndicesAChannel("+x.join()+"),\n                             getBestIndicesAChannel("+b.join()+")));",E="vec4(\n            getAChannel("+g.join()+"),\n            hasNextCol ? getAChannel("+y.join()+") : 0.,\n            hasNextRow ? getAChannel("+x.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",N=r?"":"\n      float getBestIndicesAChannel("+m.join()+") {\n        return getChannel(getBestIndicesA("+f.join()+"),\n                                          vec2("+f.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+m.join()+") {\n        return getChannel(getA("+f.join()+"),\n                               vec2("+f.slice(-2).join()+"));\n      }\n      "+N+"\n      void main() {\n        "+c+" coords = getOutputCoords();\n        bool hasNextCol = "+h[l-1]+" < "+(u[l-1]-1)+";\n        bool hasNextRow = "+h[l-2]+" < "+(u[l-2]-1)+";\n        "+i+"\n        ivec4 srcIdx = ivec4(sourceLocR"+v+", sourceLocG"+v+",\n          sourceLocB"+v+", sourceLocA"+v+") * "+e+";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = "+E+";\n\n        for (int i = 0; i < "+e+"; i++) {\n          inIdx = srcIdx;\n          "+C+"\n          vec4 candidate = "+E+";\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\n                           replace.y  ? candidate.y : bestValue.y,\n                           replace.z  ? candidate.z : bestValue.z,\n                           replace.w  ? candidate.w : bestValue.w);\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n          srcIdx++;\n        }\n        setOutput(bestIndex);\n      }\n    "}}(),_o=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n      const ivec2 pads = ivec2("+l+", "+c+");\n      const float avgMultiplier = float("+h+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+s+";\n            wR += "+a+") {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+u+";\n            wC+= "+i+") {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Oo=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=c-1-t.padInfo.front,f=h-1-t.padInfo.top,v=p-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n      const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n      const float avgMultiplier = float("+m+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < "+c+";\n            wD += "+s+") {\n          float dyD = float(dyDCorner + wD) / "+o+".0;\n\n          if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < "+h+";\n              wR += "+u+") {\n            float dyR = float(dyRCorner + wR) / "+a+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < "+p+";\n                wC += "+l+") {\n              float dyC = float(dyCCorner + wC) / "+i+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n              dotProd += dyValue * avgMultiplier;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Fo=function(){return function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Br(t,e),Br(t,n);var i="0.0";null!=r&&(Br(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Br(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = "+i+";\n        float scale = "+s+";\n        float inv = scale * inversesqrt(variance + float("+a+"));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    "}}(),Mo=function(){return function(t,e,n,r,o,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Br(t,e),Br(t,n);var i="vec4(0.0)";null!=r&&(Br(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Br(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        vec4 offset = "+i+";\n        vec4 scale = "+s+";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    "}}(),Bo="return areal * breal - aimag * bimag;",Po="return areal * bimag + aimag * breal;",Lo=function(){return function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Br(e,n),this.userCode="\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        "+t+"\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    "}}(),Vo="return a + b;",Wo="return a - b;",Uo="return a * b;",zo="return (a < 0.) ? b * a : a;",Go=function(){return function(t,e,n){this.variableNames=["A","B"],this.outputShape=Br(e,n),this.userCode="\n      float binaryOperation(float a, float b) {\n        "+t+"\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    "}}(),Ho="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",qo=function(){return function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Br(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===g(this.outputShape))a="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else if(a="\n          "+So(o)+" coords = getOutputCoords();\n        ",1===o)a+="\n            result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ";else{var i=fo("coords",o);a+="\n            bool nextRowOutOfBounds =\n              ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n            bool nextColOutOfBounds =\n              ("+i[o-1]+" + 1) >= "+this.outputShape[o-1]+";\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          "}this.userCode="\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        "+t+"\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        "+a+"\n\n        setOutput(result);\n      }\n    "}}(),$o=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      uniform float minVal;\n      uniform float maxVal;\n\n      void main() {\n        float value = getAAtOutCoords();\n        if (isnan(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, minVal, maxVal));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ko=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      uniform float minVal;\n      uniform float maxVal;\n\n      void main() {\n        vec4 value = getAAtOutCoords();\n\n        if (any(isnan(value))) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),jo=function(){return function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    "}}(),Xo=function(){return function(t){this.outputShape=[],this.outputShape=Qe(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var o=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+o+"));")}var a=e.length,i=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        "+r.join("\n        ")+"\n      }\n    "}}(),Yo=function(){return function(t,e){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=Qe(t,e);var n=this.outputShape,r=n.length,o=So(r),a=fo("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var l=i[e],c="vec2("+i.slice(-2).join()+")",h=i.join(),p="if ("+l+" < "+s[0]+")\n          return getChannel(getT0("+h+"), "+c+");";for(u=1;u<s.length;u++){var d=s[u-1];p+="\n        else if ("+l+" < "+s[u]+") {\n          "+l+" -= "+d+";\n          return getChannel(getT"+u+"("+h+"), "+c+");\n        }"}var f=s.length;p+="\n        else {\n          "+l+" -= "+s[s.length-1]+";\n          return getChannel(getT"+f+"("+h+"), "+c+");\n        }",this.userCode="\n      float getValue("+i.map(function(t){return"int "+t})+") {\n        "+p+"\n      }\n\n      void main() {\n        "+o+" coords = getOutputCoords();\n        vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n        if (++"+a[r-1]+" < "+n[r-1]+") {\n          result.g = getValue("+a+");\n        }\n        if (++"+a[r-2]+" < "+n[r-2]+") {\n          result.a = getValue("+a+");\n        }\n        if ("+a[r-2]+" < "+n[r-2]+" &&\n            --"+a[r-1]+" < "+n[r-1]+") {\n          result.b = getValue("+a+");\n        }\n        setOutput(result);\n      }\n    "}}(),Qo=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a="channelsLast"===t.dataFormat;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int d2 = coords.w;\n\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+o+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              if ("+a+") {\n                float dyValue = getDy(b, yR, yC, d2);\n                float xValue = getX(b, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              } else {\n                float dyValue = getDy(b, d2, yR, yC);\n                float xValue = getX(b, d1, xR, xC);\n                dotProd += (xValue * dyValue);\n              }\n\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Jo=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode="\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords["+c+"];\n\n        ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n              if ("+a+") {\n                float xValue = getDy(batch, idyR, idyC, d2);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              } else {\n                float xValue = getDy(batch, d2, idyR, idyC);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Zo=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=t.padInfo.left;this.userCode="\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n            int xF = wF + yF * "+e+" - "+o+";\n\n            if (xF < 0 || xF >= "+t.inDepth+") {\n              continue;\n            }\n\n            for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n              int xR = wR + yR * "+n+" - "+a+";\n\n              if (xR < 0 || xR >= "+t.inHeight+") {\n                continue;\n              }\n\n              for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n                int xC = wC + yC * "+r+" - "+i+";\n\n                if (xC < 0 || xC >= "+t.inWidth+") {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ta=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+e+"; wF++) {\n          float dyF = float(dyFCorner + wF) / "+o+".0;\n\n          if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = "+e+" - 1 - wF;\n\n          for (int wR = 0; wR < "+n+"; wR++) {\n            float dyR = float(dyRCorner + wR) / "+a+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = "+n+" - 1 - wR;\n\n            for (int wC = 0; wC < "+r+"; wC++) {\n              float dyC = float(dyCCorner + wC) / "+i+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = "+r+" - 1 - wC;\n\n              for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ea=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * "+a+" + dm;\n\n        float dotProd = 0.0;\n\n        // TO DO: Vec4 over the batch size\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+o+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),na=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            // TO DO: Vec4 over the channelMul\n            for (int dm = 0; dm < "+s+"; dm++) {\n              int d2 = d1 * "+s+" + dm;\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ra=function(){return function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.padInfo.top,a=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,h=t.filterWidth,p=4*Math.floor(t.inChannels/4),d=t.inChannels%4,f="channelsLast"===t.dataFormat,v=f?1:2,m=f?2:3,g=f?3:1,y="",x="";n&&(y=r?"float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          "+n+"\n        }":"\n          float activation(float x) {\n            "+n+"\n          }\n        ",x="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+y+"\n\n      const ivec2 strides = ivec2("+i+", "+s+");\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords["+g+"];\n\n        ivec2 xRCCorner =\n            ivec2(coords["+v+"], coords["+m+"]) * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+c+"; wR++) {\n          int xR = xRCorner + wR * "+u+";\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+h+"; wC++) {\n            int xC = xCCorner + wC * "+l+";\n\n            if (xC < 0 || xC >= "+t.inWidth+") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < "+p+"; d1 += 4) {\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              if ("+f+") {\n                vec4 xValues = vec4(\n                  getX(batch, xR, xC, d1),\n                  getX(batch, xR, xC, d1 + 1),\n                  getX(batch, xR, xC, d1 + 2),\n                  getX(batch, xR, xC, d1 + 3)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec4 xValues = vec4(\n                  getX(batch, d1, xR, xC),\n                  getX(batch, d1 + 1, xR, xC),\n                  getX(batch, d1 + 2, xR, xC),\n                  getX(batch, d1 + 3, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n\n            if ("+(1===d)+") {\n\n              if ("+f+") {\n                dotProd +=\n                    getX(batch, xR, xC, "+p+") *\n                    getW(wR, wC, "+p+", d2);\n              } else {\n                dotProd +=\n                    getX(batch, "+p+", xR, xC) *\n                    getW(wR, wC, "+p+", d2);\n              }\n\n            } else if ("+(2===d)+") {\n              vec2 wValues = vec2(\n                getW(wR, wC, "+p+", d2),\n                getW(wR, wC, "+p+" + 1, d2)\n              );\n\n              if ("+f+") {\n                vec2 xValues = vec2(\n                  getX(batch, xR, xC, "+p+"),\n                  getX(batch, xR, xC, "+p+" + 1)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec2 xValues = vec2(\n                  getX(batch, "+p+", xR, xC),\n                  getX(batch, "+p+" + 1, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            } else if ("+(3===d)+") {\n              vec3 wValues = vec3(\n                getW(wR, wC, "+p+", d2),\n                getW(wR, wC, "+p+" + 1, d2),\n                getW(wR, wC, "+p+" + 2, d2)\n              );\n\n              if ("+f+") {\n                vec3 xValues = vec3(\n                  getX(batch, xR, xC, "+p+"),\n                  getX(batch, xR, xC, "+p+" + 1),\n                  getX(batch, xR, xC, "+p+" + 2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec3 xValues = vec3(\n                  getX(batch, "+p+", xR, xC),\n                  getX(batch, "+p+" + 1, xR, xC),\n                  getX(batch, "+p+" + 2, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            }\n          }\n        }\n\n        float result = dotProd;\n        "+b+"\n        "+x+"\n        setOutput(result);\n      }\n    "}}(),oa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,h=t.filterHeight,p=t.filterWidth,d=4*Math.floor(t.inChannels/4),f=t.inChannels%4;this.userCode="\n      const ivec3 strides = ivec3("+o+", "+a+", "+i+");\n      const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+c+"; wF++) {\n          int xF = xFCorner + wF * "+s+";\n\n          if (xF < 0 || xF >= "+t.inDepth+") {\n            continue;\n          }\n\n          for (int wR = 0; wR < "+h+"; wR++) {\n            int xR = xRCorner + wR * "+u+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+p+"; wC++) {\n              int xC = xCCorner + wC * "+l+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+d+"; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if ("+(1===f)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+d+") *\n                  getW(wF, wR, wC, "+d+", d2);\n              } else if ("+(2===f)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+d+"),\n                  getX(batch, xF, xR, xC, "+d+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+d+", d2),\n                  getW(wF, wR, wC, "+d+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3===f)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+d+"),\n                  getX(batch, xF, xR, xC, "+d+" + 1),\n                  getX(batch, xF, xR, xC, "+d+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+d+", d2),\n                  getW(wF, wR, wC, "+d+" + 1, d2),\n                  getW(wF, wR, wC, "+d+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),aa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 strides = ivec2("+a+", "+i+");\n      const ivec2 pads = ivec2("+r+", "+o+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / "+h+";\n        int q = d2 - d1 * "+h+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < "+l+"; wR++) {\n          int xR = xRCorner + wR * "+s+";\n\n          if (xR < 0 || xR >= "+e+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+c+"; wC++) {\n            int xC = xCCorner + wC * "+u+";\n\n            if (xC < 0 || xC >= "+n+") {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ia=function(){return function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=c,d="int xR; int xC; int xCOffset;",f=0;f<l;f++)for(var v=0;v<c;v++)d+="\n          vec4 xTexelR"+f+"C"+2*v+" = vec4(0.);\n          vec4 wR"+f+"C"+v+" = vec4(0.);\n          vec4 xR"+f+"C"+v+" = vec4(0.);";for(f=0;f<l;f++)for(var m=0;m<p;m++){if(d+="\n          xR = xRCorner + "+f*s+";\n          xC = xCCorner + "+(v=2*m)*u+";\n        ",1===i){if(v<c&&(d+=o%2==1?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+f+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+f+"C"+v+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n                  xR"+f+"C"+v+" = vec4(previous.zw, xTexelR"+f+"C"+v+".xy);\n                } else {\n                  xR"+f+"C"+v+" = vec4(0, 0, xTexelR"+f+"C"+v+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n                  xTexelR"+f+"C"+v+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+f+"C"+v+" = vec4(0.);\n                }\n\n                xR"+f+"C"+v+" = xTexelR"+f+"C"+v+";\n              ",v+1<c)){var g=o%2==0?h(u):u;u%2==0&&o%2==1||u%2!=0&&o%2!=1?(d+="\n                  xCOffset = xC + "+o%2+" + "+g+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+f+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",u>1&&(d+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+e+" &&\n                      xCOffset >= 0 && xCOffset < "+n+") {\n                      xTexelR"+f+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+f+"C"+v+" = vec4(0.);\n                    }\n                  "),d+="\n                  xR"+f+"C"+(v+1)+" = vec4(\n                    xTexelR"+f+"C"+v+".zw, xTexelR"+f+"C"+(v+2)+".xy);\n                "):d+="\n                  xCOffset = xC + "+g+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+f+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+f+"C"+(v+1)+" = xTexelR"+f+"C"+(v+2)+";\n                "}}else v<c&&(d+="\n              if(xR >= 0 && xR < "+e+") {\n            ",o%2==1?(d+="\n                xCOffset = xC + 1 - "+i+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+f+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+f+"C"+v+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+n+") {\n                  xTexelR"+f+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+f+"C"+(v+2)+" = vec4(0.);\n                }\n\n                xR"+f+"C"+v+" = vec4(\n                  xTexelR"+f+"C"+v+".zw, xTexelR"+f+"C"+(v+2)+".zw);\n              ",v+1<c&&(d+="\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + "+i+";\n                  if(xCOffset >= 0 && xCOffset < "+n+") {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR"+f+"C"+(v+1)+" = vec4(xTexelR"+f+"C"+(v+2)+".xy, final.xy);\n                ")):(d+="\n                if(xC >= 0 && xC < "+n+") {\n                  xTexelR"+f+"C"+v+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+f+"C"+v+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+i+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+f+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+f+"C"+(v+2)+" = vec4(0.);\n                }\n\n                xR"+f+"C"+v+" = vec4(\n                  xTexelR"+f+"C"+v+".xy, xTexelR"+f+"C"+(v+2)+".xy);\n              ",v+1<c&&(d+="\n                  xR"+f+"C"+(v+1)+" = vec4(\n                    xTexelR"+f+"C"+v+".zw, xTexelR"+f+"C"+(v+2)+".zw);\n                ")),d+="}");v<c&&(d+="\n            vec4 wTexelR"+f+"C"+v+" = getW("+f+", "+v+", d1, q);\n            wR"+f+"C"+v+" = vec4(wTexelR"+f+"C"+v+".xz, wTexelR"+f+"C"+v+".xz);\n          ",v+1<c&&(d+="\n              vec4 wTexelR"+f+"C"+(v+1)+" = getW("+f+", "+(v+1)+", d1, q);\n              wR"+f+"C"+(v+1)+" =\n                vec4(wTexelR"+f+"C"+(v+1)+".xz, wTexelR"+f+"C"+(v+1)+".xz);"))}for(f=0;f<l;f++)for(v=0;v<c;v++)d+="result += xR"+f+"C"+v+" * wR"+f+"C"+v+";";this.userCode="\n      const ivec2 strides = ivec2("+a+", "+i+");\n      const ivec2 pads = ivec2("+r+", "+o+");\n\n      void main() {\n\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2;\n        int q = 0;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        vec4 result = vec4(0.);\n\n        "+d+"\n\n        setOutput(result);\n      }\n    "}}(),sa=function(){return function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],i=t[1],s=t[2],u=t[3],l=e[0],c=n[0],h=n[1];this.outputShape=[l,c,h,u];var p="bilinear"===r?1:0,d=[i-1+".0",s-1+".0"],f=d[0],v=d[1],m=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio","y1*"+f+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+f],g=m[0],y=m[1],x=m[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n      const float height_ratio = float("+g+");\n      const float width_ratio = float("+w+");\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= "+a+") {\n          return;\n        }\n\n        float height_scale = "+y+";\n        float width_scale = "+C+";\n\n        float in_y = "+x+";\n        if( in_y < 0.0 || in_y > "+f+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n        float in_x = "+E+";\n        if( in_x < 0.0 || in_x > "+v+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if("+p+" == 1) {\n          // Compute the four integer indices.\n          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n          float top = topLeft + (topRight - topLeft) * fracCR.x;\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n          float newValue = top + (bottom - top) * fracCR.y;\n          setOutput(newValue);\n        } else {\n          // Compute the coordinators of nearest neighbor point.\n          ivec2 sourceNearestCR = ivec2(floor(\n            sourceFracIndexCR + vec2(0.5,0.5)));\n          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n          setOutput(newValue);\n        }\n      }\n    "}}(),ua=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n      int getIndex(int i) {\n        "+(n?"return "+o+" -i - 1;":"return i;")+"\n      }\n\n      void main() {\n        "+So(r)+" coords = getOutputCoords();\n        int end = "+la(r,"coords")+";\n        float val = 0.0;\n        for (int i = "+o+" - 1; i >= 0; i -= 1) {\n          int idx = getIndex(i);\n          if (idx "+a+" end) {\n            continue;\n          }\n          if (idx == end && "+e+") {\n            continue;\n          }\n          "+la(r,"coords")+" = idx;\n          val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n        }\n        setOutput(val);\n      }\n    "}}();function la(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var ca=function(){return function(t,e){this.variableNames=["A"];var n=vo();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+mo(["r","c","d"],t)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+e[0]+", "+e[1]+"));\n        int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getA(rc.x, rc.y, rc.z);\n        }\n\n        "+n.output+" = result;\n      }\n    "}}(),ha=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=vo();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+mo(["r","c","d"],t)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+e[0]+", "+e[1]+"));\n        int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n        }\n\n        "+n.output+" = result;\n      }\n    "}}(),pa=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = "+this.getHeightCoordString()+";\n      int w = "+this.getWidthCoordString()+";\n      int d = "+this.getDepthCoordString()+";\n\n      int in_h = h / "+e+";\n      int offset_h = imod(h, "+e+");\n      int in_w = w / "+e+";\n      int offset_w = imod(w, "+e+");\n      int offset_d = (offset_h * "+e+" + offset_w) *\n        "+this.getOutputDepthSize()+";\n      int in_d = d + offset_d;\n\n      float result = "+this.getInputSamplingString()+";\n      setOutput(result);\n    }\n  "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),da=function(){return function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n      void main() {\n          ivec2 coords = getOutputCoords();\n          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n          setOutput(val);\n      }\n    "}}(),fa=function(){return function(t){this.variableNames=["A"];var e=vo();this.outputShape=t,this.userCode="\n      "+yo+"\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+e.output+" = encode_float(x);\n      }\n    "}}(),va=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=vo();this.outputShape=t,this.userCode="\n      "+yo+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        "+e.output+" = encode_float(x);\n      }\n    "}}(),ma=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=vo(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n      "+go(t)+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        int flatIndex = getFlatIndex(coords);\n        int offset = imod(flatIndex, 4);\n\n        flatIndex = idiv(flatIndex, 4, 1.);\n        \n        int r = flatIndex / "+a+";\n        int c = imod(flatIndex, "+a+");\n        vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n        vec4 values = "+r.texture2D+"(A, uv);\n\n        float result;\n\n        if(offset == 0) {\n          result = values[0];\n        } else if(offset == 1) {\n          result = values[1];\n        } else if(offset == 2) {\n          result = values[2];\n        } else {\n          result = values[3];\n        }\n\n        "+r.output+" = vec4("+i+", 0., 0., 0.);\n      }\n    "}}(),ga=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=vo(),o=e[0],a=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;i+="\n          localCoords = coords;\n          if(localCoords[2] + "+l+" < "+t[2]+") {\n            localCoords[2] += "+l+";\n            if(localCoords[1] + "+u+" < "+t[1]+") {\n              localCoords[1] += "+u+";\n\n              flatIndex = getFlatIndex(localCoords);\n              offset = imod(flatIndex, 4);\n    \n              flatIndex = idiv(flatIndex, 4, 1.);\n\n              r = flatIndex / "+a+";\n              c = imod(flatIndex, "+a+");\n              uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n              values = "+r.texture2D+"(A, uv);\n\n              if(offset == 0) {\n                result["+c+"] = values[0];\n              } else if(offset == 1) {\n                result["+c+"] = values[1];\n              } else if(offset == 2) {\n                result["+c+"] = values[2];\n              } else {\n                result["+c+"] = values[3];\n              }\n            }\n          }\n        "}this.userCode="\n      "+go(t)+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        vec4 result = vec4(0.);\n        int flatIndex, r, c, offset;\n        ivec3 localCoords;\n        vec2 uv;\n        vec4 values;\n        \n        "+i+"\n\n        "+r.output+" = "+s+";\n      }\n    "}}(),ya="return real * expR - imag * expI;",xa="return real * expI + imag * expR;",ba=function(){return function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n      const float exponentMultiplier = "+o+";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        "+t+"\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float("+r+");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < "+r+"; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / "+a+";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    "}}(),wa=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n      uniform float value;\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),Ca=function(){return function(t){this.variableNames=["A"];var e=vo(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n        vec4 values = "+e.texture2D+"(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    "}}(),Ea=function(){return function(t){this.variableNames=["A"];var e=vo(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n\n        vec4 result = vec4(0.);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            texC = coords[1] + row;\n            depth = coords[2] + col;\n\n            vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n            vec4 values = "+e.texture2D+"(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        "+e.output+" = result;\n      }\n    "}}(),Na=function(){return function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=So(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],a=0;a<t.length;a++)a===e?o.push("int(getIndices("+r[a]+"))"):o.push(""+r[a]);return o.join()}(t,n);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    "}}();var Ra=function(){return function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=So(e.length),o=So(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n        "+r+" strides = "+r+"("+this.strides+");\n         void main() {\n          "+o+" coords = getOutputCoords();\n          int flattenIndex = 0;\n          for (int j = 0; j < "+this.sliceDim+"; j++) {\n            int index = round(getIndices(coords[0], j));\n            flattenIndex += index * "+a+";\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      "}}();function Ia(t,e){var n=vo();return Kt(t,e,n.version+"\n    precision highp float;\n    "+n.attribute+" vec3 clipSpacePos;\n    "+n.attribute+" vec2 uv;\n    "+n.varyingVs+" vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }")}function ka(t,e){return ee(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Sa(t,e){return ne(t,e,new Uint16Array([0,1,2,2,1,3]))}function Aa(t,e,n,r,o,a,i){oe(n,r);var s=re(t,e),u=t.TEXTURE_2D;return Ut(t,e,function(){return t.bindTexture(u,s)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Ut(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Ut(t,e,function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function Ta(t,e,n,r,o){var a=Pt(n,r);return Aa(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function Da(t,e,n,r,o){var a=Pt(n,r);return Aa(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function _a(t,e,n,r,o){var a=Pt(n,r);return Aa(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Oa(t,e,n,r,o){var a=Vt(n,r);return Aa(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function Fa(t,e,n,r,o){var a=Vt(n,r);return Aa(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function Ma(t,e,n,r){return Ut(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),ie(t,e,n,"clipSpacePos",r,3,20,0)&&ie(t,e,n,"uv",r,2,20,12)}function Ba(t,e,n,r,o,a,i){var s,u,l;Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,l=i.internalFormatPackedFloat),s.set(a),Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,o,0,t.RGBA,u,s)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Pa(t,e,n,r){Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Ut(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Ut(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function La(t,e,n,r,o){var a=t.createBuffer();Ut(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var i=16*n*r;return Ut(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)}),Ut(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Ut(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function Va(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function Wa(t,e,n,r,o){var a=Pt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Ut(t,e,function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Ua(t,e,n,r,o,a,i,s){var u=t,l=new Float32Array(function(t,e){var n=Vt(t,e);return n[0]*n[1]*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function za(t,e,n,r){var o=new Float32Array(n*r*4);return Ut(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)}),o}var Ga=Object.freeze({createVertexShader:Ia,createVertexBuffer:ka,createIndexBuffer:Sa,createFloat32MatrixTexture:Ta,createFloat16MatrixTexture:Da,createUnsignedBytesMatrixTexture:_a,createPackedMatrixTexture:Oa,createFloat16PackedMatrixTexture:Fa,bindVertexProgramAttributeStreams:Ma,uploadDenseMatrixToTexture:Ba,uploadPixelDataToTexture:Pa,createBufferFromOutputTexture:La,downloadFloat32MatrixFromBuffer:Va,downloadByteEncodedFloatMatrixFromOutputTexture:Wa,downloadPackedMatrixFromBuffer:Ua,downloadMatrixFromPackedOutputTexture:za}),Ha=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var n=t.ENV.getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,Ft(n,e)):this.gl=Mt(n),1===t.ENV.getNumber("WEBGL_VERSION"))this.textureFloatExtension=$t(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=$t(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else{if(Ie(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Ie(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}}this.vertexBuffer=ka(this.gl,this.debug),this.indexBuffer=Sa(this.gl,this.debug),this.framebuffer=ae(this.gl,this.debug),this.textureConfig=Wt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return t.ENV.getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Ut(e,this.debug,function(){return e.finish()}),Ut(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Ut(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Ut(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Ut(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Ut(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Ta(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Da(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),_a(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Pa(this.gl,this.debug,t,e)},e.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ba(this.gl,this.debug,t,e,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Fa(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Oa(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(pe(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Ut(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Wa(r.gl,r.debug,e,n,r.textureConfig)})},e.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return Ua(this.gl,t,0,0,0,o,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Va(this.gl,t,e)},e.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=La(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},e.prototype.createFence=function(e){var n,r,o=this;if(t.ENV.getBool("WEBGL_FENCE_API_ENABLED")){var a=e,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=function(){var t=a.clientWaitSync(i,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},n=i}else t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(n=this.beginQuery(),this.endQuery(),r=function(){return o.isQueryAvailable(n,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:n,isFencePassed:r}},e.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return za(r.gl,r.debug,e,n)})},e.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=jt(e,this.debug,t),r=Ia(e,this.debug),o=Jt(e,this.debug);return Ut(e,this.debug,function(){return e.attachShader(o,r)}),Ut(e,this.debug,function(){return e.attachShader(o,n)}),Zt(e,this.debug,o),this.debug&&te(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Ma(e,this.debug,this.program,this.vertexBuffer)),o},e.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Ut(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},e.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&te(this.gl,this.debug,this.program),Ut(this.gl,this.debug,function(){return e.gl.useProgram(t)})},e.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ue(this.gl,this.debug,t,e):le(this.gl,t,e)},e.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Ut(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},e.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},e.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),ce(this.gl,this.debug,this.program,t,e,n)},e.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},e.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Vt(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},e.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},e.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&te(this.gl,this.debug,this.program),de(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Ut(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Ut(this.gl,this.debug,function(){return t.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=$t(this.gl,this.debug,2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(n.TIME_ELAPSED_EXT,r),r}var o=this.getQueryTimerExtensionWebGL1(),a=o.createQueryEXT();return o.beginQueryEXT(o.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var n=this.gl,r=this.getQueryTimerExtensionWebGL2();n.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return r(this,void 0,void 0,function(){var n=this;return o(this,function(r){switch(r.label){case 0:return[4,E(function(){return n.disposed||n.isQueryAvailable(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return r.sent(),[2,this.getQueryTime(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint},e.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length;++e){var n=t[e]();if(!n)break}return e-1}(this.itemsToPoll.map(function(t){return t.isDoneFn})),e=0;e<=t;++e){(0,this.itemsToPoll[e].resolveFn)()}this.itemsToPoll=this.itemsToPoll.slice(t+1)},e.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||E(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),he(this.gl,this.debug,t,this.framebuffer),this.debug&&de(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(he(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&de(this.gl)):pe(this.gl,this.debug,this.framebuffer)},e.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;he(r,this.debug,t,this.framebuffer),this.debug&&de(r),this.outputTexture=t,Ut(r,this.debug,function(){return r.viewport(0,0,e,n)}),Ut(r,this.debug,function(){return r.scissor(0,0,e,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Ut(this.gl,this.debug,function(){return o.gl.scissor(t,e,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function qa(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,o=e[n],a=o.shape;if(!y(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!y(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}})}var $a=function(){return function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,h=n.dataFormat,p=s.left,d=s.top,f=o*r,v=vo(),m="channelsLast"===h,g=m?0:1,y=m?1:2,x="",b=0;b<=1;b++)for(var w=0;w<=1;w++)x+="\n          blockIndex = rc.y + "+w+";\n          pos = rc.x + "+b+";\n\n          if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n            offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n            d0 = offsetY + "+c+" * (pos / "+f+");\n\n            if(d0 < "+e[g]+" && d0 >= 0) {\n\n              offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+p+".);\n              d1 = offsetX + "+l+" * (int(mod(float(pos), "+f+".) / "+o+".));\n\n              if(d1 < "+e[y]+" && d1 >= 0) {\n\n                ch = int(mod(float(pos), "+o+".));\n\n                if ("+m+") {\n                  innerDims = vec2(d1, ch);\n                  result["+(2*b+w)+"] = getChannel(\n                    getA(d0, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                } else {\n                  innerDims = vec2(d0, d1);\n                  result["+(2*b+w)+"] = getChannel(\n                    getA(ch, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                }\n              }\n            }\n          }\n        ";this.userCode="\n      void main() {\n        ivec2 rc = getOutputCoords();\n\n        vec4 result = vec4(0);\n\n        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n        vec2 innerDims;\n\n        "+x+"\n\n        "+v.output+" = result;\n      }\n    "}}(),Ka=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -"+i+"; j <= "+i+"; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  "+s+") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * "+a+";\n        setOutput(val);\n      }\n    "}}(),ja=function(){return function(t,e,n,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=o,this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < "+this.depth+"; ++d) {\n          int depthBegin = int(max(0.0, float(d - "+e+")));\n          int depthEnd = int(min(float("+this.depth+"),\n              float(d + "+e+" + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = "+this.depth+";\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float("+r+") * norm + float("+n+");\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float("+r+")\n                * float("+o+")\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * "+o+");\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    "}}(),Xa=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < "+this.outputShape[3]+";\n        bool hasNextRow = c < "+this.outputShape[2]+";\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - "+i+";\n        vec2 cache = vec2(0.);\n        if(firstChannel >= 0){\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n            if(hasNextRow){\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n            }\n        }\n\n        ivec2 depth = ivec2(d, d + 1);\n        for (int j = - "+i+"; j <= "+i+"; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * "+a+";\n        setOutput(result);\n      }\n    "}}(),Ya=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+o+";\n          wR += "+r+") {\n          float dyR = float(dyRCorner + wR) / "+e+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+a+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+n+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * "+a+" + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Qa=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,h=u-1-t.padInfo.top,p=l-1-t.padInfo.left,d=s*u*l-1;this.userCode="\n      const ivec3 pads = ivec3("+c+", "+h+", "+p+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < "+s+";\n           wD += "+o+") {\n          float dyD = float(dyDCorner + wD) / "+e+".0;\n\n          if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < "+u+";\n              wR += "+a+") {\n            float dyR = float(dyRCorner + wR) / "+n+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < "+l+";\n                wC += "+i+") {\n              float dyC = float(dyCCorner + wC) / "+r+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n              int maxPosValue = "+d+" -\n                  int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n              // Get the current value, check it against the value from the\n              // position matrix.\n              int curPosValue =\n                  wD * "+u+" * "+l+" +\n                  wR * "+l+" + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),Ja=function(){return function(t,e,n,r,o,a,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",f="";a&&(d=i?"vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          "+a+"\n        }":"vec4 activation(vec4 x) {\n          "+a+"\n        }",f="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+d+"\n\n      const float sharedDimension = "+u+".0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < "+u+"; i++) {\n          vec4 a = getMatrixA(rc.x, "+l+");\n          vec4 b = getMatrixB(rc.x, "+c+");\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += ("+h[0]+" * "+p[0]+");\n          result += ("+h[1]+" * "+p[1]+");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        "+v+"\n\n        "+f+"\n\n        setOutput(result);\n      }\n    "}}(),Za=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n      uniform float seed;\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < "+(e-1)+"; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float("+(e-1)+"));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),ti=function(){return function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float("+r+"), float("+n+"),\n                      float(index == coords.y)));\n      }\n    "}}(),ei=function(){return function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var n=fo("rc",e),r=So(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o<t;o++)r+=n[o]+" >= "+e[o],o<t-1&&(r+="||");return r}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var o=r.slice(-2);return"\n    int r = "+o[0]+";\n    int c = "+o[1]+";\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= "+e+";\n    bool rEdge = rp1 >= "+n+";\n  "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i<t;i++)a=e[e.length-1-i]+","+a;n.push(a)}return n}(n,e);return 1===n?"getA(rc),\n            rc + 1 >= "+t[0]+" ? 0. : getA(rc + 1),\n            0, 0":"getA("+r[0]+"),\n          cEdge ? 0. : getA("+r[1]+"),\n          rEdge ? 0. : getA("+r[2]+"),\n          rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n        void main() {\n          "+r+" rc = getOutputCoords();\n\n          if("+o+") {\n            setOutput(vec4(0));\n          } else {\n            "+a+"\n\n            setOutput(vec4("+i+"));\n          }\n        }\n      "}}}();var ni=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,o=So(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n      "+o+" start = "+o+"("+a+");\n      "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(float("+n+"));\n        } else {\n          "+o+" coords = outC - start;\n          setOutput(getX("+s+"));\n        }\n      }\n    ":"\n        int start = "+a+";\n        int end = "+i+";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(float("+n+"));\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      "}}(),ri=function(){return function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,o=So(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=fo("rc",r),u=fo("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n       if("+l+") {\n      ",1===r?"":"}\n       rc = outputLoc;\n       "+s[r-2]+" += 1;\n       if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":"  "+s[r-1]+" += 1;\n         if("+l+") {"],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",f=0,v=1===r?2:4;f<v;f++)d+="\n        "+h[f]+"\n        if ("+p+") {\n          result["+f+"] = float("+n+");\n        } else {\n          "+o+" source = rc - start;\n          result["+f+"] = getChannel(getX("+u.join()+"), "+c+");\n        }\n      ";d+=1===r?"} ":"}}",this.userCode="\n      const "+o+" start = "+o+"("+a+");\n      const "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        "+d+"\n        setOutput(result);\n      }\n    "}}(),oi=function(){return function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var p="avg"===e,d="0.0";if(p||(d="-1.0 / 1e-20"),n)this.userCode="\n        const ivec2 strides = ivec2("+o+", "+a+");\n        const ivec2 pads = ivec2("+c+", "+h+");\n\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int batch = coords[0];\n          int d = coords[3];\n\n          ivec2 xRCCorner = coords.yz * strides - pads;\n          int xRCorner = xRCCorner.x;\n          int xCCorner = xRCCorner.y;\n\n          // max/min x(?, ?, d) to get y(yR, yC, d).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n          float avgValue = 0.0;\n\n          for (int wR = 0; wR < "+u+";\n              wR += "+i+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+l+";\n                wC += "+s+") {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value >= currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = wR * "+l+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var f=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(f="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n      if ("+p+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+c+", "+h+");\n      const float initializationValue = "+d+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xR, int xC, int d) {\n        if (xC < 0 || xC >= "+t.inWidth+") {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4("+d+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+u+";\n            wR += "+i+") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+v+"; wC += 4) {\n            int xC = xCCorner + wC * "+s+";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              getValue(batch, xR, xC + 3 * "+s+", d)\n            );\n\n            "+g+"\n          }\n\n          int xC = xCCorner + "+v+";\n          if ("+(1===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(2===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(3===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              initializationValue\n            );\n\n            "+g+"\n          }\n        }\n        setOutput("+f+");\n      }\n    "}}}(),ai=function(){return function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,f=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var m="avg"===e,g="0.0";if(m||(g="-1.0 / 1e-20"),n)this.userCode="\n        const ivec3 strides =\n            ivec3("+o+", "+a+", "+i+");\n        const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n\n        void main() {\n          ivec5 coords = getOutputCoords();\n          int batch = coords.x;\n          int ch = coords.u;\n\n          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n          int xDCorner = xCorner.x;\n          int xRCorner = xCorner.y;\n          int xCCorner = xCorner.z;\n\n          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n\n          for (int wD = 0; wD < "+c+";\n              wD += "+s+") {\n            int xD = xDCorner + wD;\n\n            if (xD < 0 || xD >= "+t.inDepth+") {\n              continue;\n            }\n\n            for (int wR = 0; wR < "+h+";\n                wR += "+u+") {\n              int xR = xRCorner + wR;\n\n              if (xR < 0 || xR >= "+t.inHeight+") {\n                continue;\n              }\n\n              for (int wC = 0; wC < "+p+";\n                  wC += "+l+") {\n                int xC = xCCorner + wC;\n\n                if (xC < 0 || xC >= "+t.inWidth+") {\n                  continue;\n                }\n\n                float value = getX(batch, xD, xR, xC, ch);\n\n                // If a min / max value has already been found, use it. If not,\n                // use the current value.\n                float currMinMaxValue = mix(\n                    value, minMaxValue, minMaxValueFound);\n                if (value >= currMinMaxValue) {\n                  minMaxValue = value;\n                  minMaxValueFound = 1.0;\n                  minMaxPosition =\n                      wD * "+h+" * "+p+" +\n                      wR * "+p+" + wC;;\n                }\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var x=4*Math.floor(r/4),b=r%4,w="\n      if ("+m+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec3 strides =\n        ivec3("+o+", "+a+", "+i+");\n      const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n      const float initializationValue = "+g+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xD, int xR, int xC, int ch) {\n        if (xC < 0 || xC >= "+t.inWidth+") {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xD, xR, xC, ch);\n      }\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xDCorner = xCorner.x;\n        int xRCorner = xCorner.y;\n        int xCCorner = xCorner.z;\n\n        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n        // ? = to be determined\n        vec4 minMaxValue = vec4("+g+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wD = 0; wD < "+c+";\n            wD += "+s+") {\n          int xD = xDCorner + wD;\n\n          if (xD < 0 || xD >= "+t.inDepth+") {\n            continue;\n          }\n\n          for (int wR = 0; wR < "+h+";\n            wR += "+u+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+x+"; wC += 4) {\n              int xC = xCCorner + wC * "+l+";\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+l+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n                getValue(batch, xD, xR, xC + 3 * "+l+", ch)\n              );\n\n              "+w+"\n            }\n\n            int xC = xCCorner + "+x+";\n            if ("+(1===b)+") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                initializationValue,\n                initializationValue,\n                initializationValue\n              );\n\n              "+w+"\n            } else if ("+(2===b)+") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+l+", ch),\n                initializationValue,\n                initializationValue\n              );\n\n              "+w+"\n            } else if ("+(3===b)+") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+l+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n                initializationValue\n              );\n\n              "+w+"\n            }\n          }\n          setOutput("+y+");\n        }\n      }\n    "}}}(),ii=function(){return function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,h="\n      if ("+("sum"===e)+") {\n        sumValue += dot(values, ones);\n      } else if ("+("prod"===e)+") {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = "+s+"(values, minMaxValue);\n      }\n    ",p="vec4";"all"===e?(i="1.0",h="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",p="bvec4"):"any"===e&&(i="0.0",h="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",p="bvec4");var d="";o%n>0&&(d="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      "),this.userCode="\n      const float initializationValue = "+i+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        "+d+"\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+n+";\n\n        vec4 minMaxValue = vec4("+i+");\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < "+l+"; i += 4) {\n          int inIdx = inOffset + i;\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          "+h+"\n        }\n\n        int inIdx = inOffset + "+l+";\n        if ("+(1===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(2===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(3===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          "+h+"\n        }\n        setOutput("+u+");\n      }\n    "}}(),si=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n        "+o+"\n        "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result["+r+"] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        "+(r>0?"}":"")+"\n      "}this.userCode="\n      \n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      "+mo(["r","c","d"],e)+"\n      return ivec3(r, c, d);\n    }\n  \n      "+go(t)+"\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = "+t[1]+";\n        int cols = "+t[2]+";\n\n        "+n+"\n\n        setOutput(result);\n      }\n    "}}();var ui=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],d=1/h,f=1/p,v=2*Math.ceil(d)+2,m=2*Math.ceil(f)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+h+");\n        const float widthScale = float("+p+");\n\n        const float invHeightScale = float("+d+");\n        const float invWidthScale = float("+f+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), "+(o-1)+".0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "}}(),li=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n        ivec2 sourceCeilRC = ivec2(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n        float newValue = top + (bottom - top) * fracRC.x;\n\n        setOutput(newValue);\n      }\n    "}}(),ci=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+",\n          "+u[1]/l[1]+");\n      const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n                                     "+i+".0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n        \n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < "+(s-1)+"; \n        bool hasNextRow = coords.z < "+(n-1)+";\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    "}}(),hi=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],d=1/h,f=1/p,v=2*Math.ceil(d)+2,m=2*Math.ceil(f)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+h+");\n        const float widthScale = float("+p+");\n\n        const float invHeightScale = float("+d+");\n        const float invWidthScale = float("+f+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float("+l[0]+") *\n                (float(dyR) / float("+c[0]+"));\n\n            float sourceFracCol =\n                float("+l[1]+") *\n                  (float(dyC) / float("+c[1]+"));\n\n            int sourceNearestRow = int(min(\n                float(int("+o+") - 1),\n                "+n+" ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int("+a+") - 1),\n                "+n+" ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "}}(),pi=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    "}}(),di=function(){return function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),o=So(n);this.userCode="\n      void main() {\n        "+o+" coords = getOutputCoords();\n        setOutput(getX("+r+"));\n      }\n    "}else this.userCode="\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX("+t[0]+" - coord - 1));\n        }\n      "}}(),fi=function(){return function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=fo("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=So(n);function s(n){var r=t.map(function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX("+t[0]+" - rc - 1),\n            "+t[0]+" - rc - 1);\n          if("+o+"){\n              result.g = getChannel(getX("+t[0]+" - (rc  + 1) - 1),\n                "+t[0]+" - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      ":"\n        void main() {\n          "+i+" rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = "+function(t){return s(t)}(r.slice())+";\n          if("+o+"){\n            result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n          }\n          if("+a+") {\n            result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n            if("+o+") {\n              result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n            }\n          }\n          setOutput(result);\n        }\n    "}}(),vi=function(){return function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=So(o.length),u=So(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var p="getUpdates("+h+")",d=e>1?"strides[j]":"strides";this.userCode="\n        "+s+" strides = "+s+"("+o+");\n\n        void main() {\n          "+u+" coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < "+t+"; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < "+e+"; j++) {\n              int index = round("+c+");\n              flattenedIndex += index * "+d+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+p+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      "}}(),mi=function(){return function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,l="\n        sumValue += dot(values, segFilter);\n    ",c="";o%n>0&&(c="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      ");var h="";o%n>0&&(h="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return -1.0;\n        }\n      "),this.userCode="\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        "+c+"\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        "+h+"\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          "+a+")) * float("+n+"));\n        int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < "+s+"; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n          );\n\n          "+l+"\n        }\n\n        int inIdx = inOffset + "+s+";\n        if ("+(1===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            0,\n            0,\n            0\n          );\n\n          "+l+"\n        } else if ("+(2===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n              0,\n              0\n          );\n\n          "+l+"\n        } else if ("+(3===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            0\n          );\n\n          "+l+"\n        }\n        setOutput(sumValue);\n      }\n    "}}(),gi=function(){return function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&i.push(""+a[u]);r=i.join(),o=s.join()}var l=So(n);this.userCode="\n      void main() {\n        "+l+" resRC = getOutputCoords();\n        float cVal = getC("+r+");\n        if (cVal >= 1.0) {\n          setOutput(getA("+o+"));\n        } else {\n          setOutput(getB("+o+"));\n        }\n      }\n    "}}(),yi=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=So(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return xi.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n        "+n+" sourceLoc;\n        "+n+" coords = getOutputCoords();\n        "+t.map(function(t,e){return"sourceLoc."+xi[e]+" = start["+e+"] + coords."+xi[e]+";"}).join("\n")+"\n      ",this.userCode="\n      "+r+"\n      void main() {\n        "+e+"\n        setOutput(getSource("+o+"));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),xi=["x","y","z","w","u","v"];var bi=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=So(this.rank),n=fo("coords",this.rank),r=fo("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n      result.x = "+a+";\n      if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n        ++"+r[this.rank-1]+";\n        result.y = "+a+";\n        --"+r[this.rank-1]+";\n      }\n    ",s=1===this.rank?"":"\n      --"+n[this.rank-1]+";\n      if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n        ++"+r[this.rank-2]+";\n        result.z = "+a+";\n        if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n          ++"+r[this.rank-1]+";\n          result.w = "+a+";\n        }\n      }\n    ",u=this.rank<=4?"sourceLoc = coords +\n            "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n      uniform int start["+this.rank+"];\n      void main() {\n        "+e+" coords = getOutputCoords();\n        "+e+" sourceLoc;\n        "+u+" \n        vec4 result = vec4(0.);\n        "+i+"\n        "+s+"\n        setOutput(result);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),wi=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=So(n.length),a=So(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=n.map(function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"}).join(",")}this.userCode="\n      "+o+" begin = "+o+"("+t+");\n      "+o+" strides = "+o+"("+e+");\n\n      void main() {\n        "+a+" coords = getOutputCoords();\n        setOutput(getX("+i+"));\n      }\n    "}}(),Ci=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,o=Ei(e,n),a=Ni(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Dt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Dt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Dt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Dt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Dt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=Ni(e,Ei(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Ei(e,n){if(e===Tt.UPLOAD)return Dt.PACKED_2X2_FLOAT32;if(e===Tt.RENDER||null==e)return function(e){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Dt.PACKED_2X2_FLOAT32:Dt.UNPACKED_FLOAT32:e?Dt.PACKED_2X2_FLOAT16:Dt.UNPACKED_FLOAT16}(n);if(e===Tt.DOWNLOAD||e===Tt.PIXELS)return Dt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function Ni(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Ri=function(){return function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var o=So(this.rank),a=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],o=0;o<t.length;o++)r.push("imod("+n[o]+", "+t[o]+")");return r.join()}(t);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    "}}();var Ii=function(){return function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var o=So(this.rank),a=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),o=0;o<t.length;o++)r[t[o]]=n[o];return r.join()}(e);this.userCode="\n    void main() {\n      "+o+" resRC = getOutputCoords();\n      setOutput(getA("+a+"));\n    }\n    "}}();var ki=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=So(this.rank),a=po("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=a[r];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],l="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n    void main() {\n      "+o+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+l+";\n      if("+u+") {\n        result[1] = "+l+";\n      }\n      --"+a[this.rank-1]+";\n      if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n        result[2] = "+l+";\n        if("+u+") {\n          result[3] = "+l+";\n        }\n      }  \n      setOutput(result);\n    }\n    "}}(),Si=1.7580993408473768,Ai=1.0507009873554805,Ti=function(){return function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      float unaryOperation(float x) {\n        "+e+"\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}}(),Di="if (isnan(x)) return x;",_i="return x;",Oi="return abs(x);",Fi=Di+"\n  return (x < 0.0) ? 0.0 : x;\n",Mi="return (x >= 0.0) ? x : (exp(x) - 1.0);",Bi="\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+Si+";\n  float scale = "+Ai+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var Pi="return -x;",Li="return ceil(x);",Vi="return floor(x);",Wi="return exp(x);",Ui="return exp(x) - 1.0;",zi=Di+"\n  return sin(x);\n",Gi=Di+"\n  return cos(x);\n",Hi=Di+"\n  return atan(x);\n",qi=Di+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));",$i=Di+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\n  return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Ki="return x;",ji="return x;",Xi="\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n",Yi="\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n",Qi=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      vec4 unaryOperation(vec4 x) {\n        "+e+"\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}}(),Ji=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=fo("rc",e),r=So(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),a=n.slice(-2),i=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n      void main() {\n        "+r+" rc = getOutputCoords();\n        vec4 packedInput = getA("+o+");\n\n        setOutput(getChannel(packedInput, "+i+"));\n      }\n    "}}(),Zi={};function ts(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?ji:_i;if("relu"===t)return e?Xi:Fi;if("elu"===t)return e?Yi:Mi;if("prelu"===t)return e?Ho:zo;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var es=600;var ns=function(){function e(e){if(this.gpgpu=e,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.disposed=!1,!t.ENV.getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var n=Mt(t.ENV.getNumber("WEBGL_VERSION"));this.binaryCache=(r=t.ENV.getNumber("WEBGL_VERSION"))in Zi?Zi[r]:(Zi[r]={},Zi[r]),this.gpgpu=new Ha(n),this.canvas=n.canvas,this.gpgpuCreatedLocally=!0}else this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;var r;this.textureManager=new Ci(this.gpgpu),this.numMBBeforeWarning=null==t.ENV.global.screen?1024:t.ENV.global.screen.height*t.ENV.global.screen.width*window.devicePixelRatio*es/1024/1024,this.texData=new _r(this,St)}return e.prototype.register=function(t,e,n){if(this.texData.has(t))throw new Error("Data buffer is already registered");this.texData.set(t,{shape:e,dtype:n})},e.prototype.fromPixels=function(e,n){if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var r="undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement,o=e.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&e instanceof ImageData,i="undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,u=i?[e.videoWidth,e.videoHeight]:[e.width,e.height],l=u[0],c=u[1],h=[c,l],p=[c,l,n];if(!(r||o||a||i||s))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);(s||i)&&(null==this.fromPixels2DContext&&(this.fromPixels2DContext=Bt(t.ENV.getNumber("WEBGL_VERSION")).getContext("2d")),this.fromPixels2DContext.canvas.width=l,this.fromPixels2DContext.canvas.height=c,this.fromPixels2DContext.drawImage(e,0,0,l,c),e=this.fromPixels2DContext.canvas);var d,f,v=this.makeTensorHandle(h,"int32");if(this.texData.get(v.dataId).usage=Tt.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(v.dataId),e),t.ENV.getBool("WEBGL_PACK")){d=new Ea(p);var m=this.makePackedTensor(d.outputShape,v.dtype);f=this.compileAndRun(d,[v],m)}else d=new Ca(p),f=this.compileAndRun(d,[v]);return this.disposeData(v.dataId),f},e.prototype.makeTensorHandle=function(t,e){var n={};return this.register(n,t,e),{dataId:n,shape:t,dtype:e}},e.prototype.write=function(e,n){if(null==n)throw new Error("MathBackendWebGL.write(): values can not be null");if(t.ENV.getBool("DEBUG"))for(var r=0;r<n.length;r++){var o=n[r];if(!Ht(o)){if(t.ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+o+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.ENV.set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+o+" cannot be represented on this device.")}}var a=this.texData.get(e);if("complex64"===a.dtype)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.releaseGPUData(e),a.usage=Tt.UPLOAD,a.values=n},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,a=e.slice,i=e.shape,s=e.isPacked;if(null!=a){var u=void 0;u=s?new Qi(i,Ki):new Ti(i,Ki);var l=this.compileAndRun(u,[{dataId:t,shape:i,dtype:r}]),c=this.readSync(l.dataId);return l.dispose(),c}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var h,p,d=null!=this.activeTimers;(d&&(h=$()),"complex64"===r)?p=Zr(o.real.dataSync(),o.imag.dataSync()):p=this.getValuesFromTexture(t);return d&&(this.downloadWaitMs+=$()-h),this.convertAndCacheOnCPU(t,p)},e.prototype.read=function(e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p,d,f,v,m,y,x,b,w,C,E,N,R;return o(this,function(o){switch(o.label){case 0:if(this.pendingRead.has(e))return n=this.pendingRead.get(e),[2,new Promise(function(t){return n.push(t)})];if(r=this.texData.get(e),a=r.values,i=r.shape,s=r.slice,u=r.dtype,l=r.complexTensors,c=r.isPacked,null!=s)return h=void 0,h=c?new Qi(i,Ki):new Ti(i,Ki),p=this.compileAndRun(h,[{dataId:e,shape:i,dtype:u}]),d=this.read(p.dataId),p.dispose(),[2,d];if(null!=a)return[2,this.convertAndCacheOnCPU(e)];if(!t.ENV.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===t.ENV.getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,"complex64"!==u&&t.ENV.get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(e),m=this.texData.get(v.dataId),f=(R=this.gpgpu).createBufferFromTexture.apply(R,[m.texture].concat(Lt(i)))),this.pendingRead.set(e,[]),"complex64"===u?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:o.sent(),o.label=2;case 2:return"complex64"!==u?[3,4]:[4,Promise.all([l.real.data(),l.imag.data()])];case 3:return x=o.sent(),b=x[0],w=x[1],y=Zr(b,w),[3,5];case 4:null==f?y=this.getValuesFromTexture(e):(C=g(i),y=this.gpgpu.downloadFloat32MatrixFromBuffer(f,C)),o.label=5;case 5:return null!=v&&this.disposeData(v.dataId),E=this.convertAndCacheOnCPU(e,y),N=this.pendingRead.get(e),this.pendingRead.delete(e),N.forEach(function(t){return t(E)}),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)),[2,E]}})})},e.prototype.getValuesFromTexture=function(e){var n,r=this,o=this.texData.get(e),a=o.shape,i=o.dtype,s=o.isPacked,u=g(a);if(t.ENV.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var l=this.decode(e),c=this.texData.get(l.dataId),h=(n=this.gpgpu).downloadMatrixFromPackedTexture.apply(n,[c.texture].concat(Lt(a))).subarray(0,u);return this.disposeData(l.dataId),h}var p=t.ENV.getBool("WEBGL_PACK")&&!0===s,d=p?xe(a):a,f=this.makeTensorHandle(d,"float32");f.size=g(a),this.texData.get(f.dataId).usage=Tt.DOWNLOAD;var v=Fe(function(){var t=p?new va(d):new fa(d);return r.compileAndRun(t,[{shape:d,dtype:i,dataId:e}],f,null)}),m=this.texData.get(v.dataId),y=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,u);return this.disposeData(f.dataId),y},e.prototype.time=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return e=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=m(this.activeTimers.map(function(t){return t.query})).filter(function(t){return null!=t}),i=m(this.activeTimers.map(function(t){return t.name})).filter(function(t){return null!=t}),this.activeTimers=e,r&&(this.programTimersStack=null),[4,Promise.all(a)];case 1:return s=o.sent(),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:p(s),getExtraProfileInfo:function(){return s.map(function(t,e){return{name:i[e],ms:t}}).map(function(t){return t.name+": "+t.ms}).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:$(),endMs:null}},e.prototype.endTimer=function(e){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=$(),e)},e.prototype.getQueryTime=function(e){return r(this,void 0,void 0,function(){var n;return o(this,function(r){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]})})},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return t.ENV.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=St.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size<e})},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.complex=function(t,e){var n=this.makeOutputArray(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:St.keep(t.clone()),imag:St.keep(e.clone())},n},e.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(e,n,r){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,n,r);if(0===g(r))return nn([],r,e.dtype);var o=this.texData.get(e.dataId).isPacked,a=Rr(e.shape,n,r);if(o||!a){var i=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new bi(r):new yi(r),s=i.getCustomSetupFunc(n);return this.compileAndRun(i,[e],null,s)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,n,r)},e.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=ct.make(n,{},t.dtype,this),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=Ir(e,t.strides);r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),o},e.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var o=Cr(e,n,r);if(o.some(function(t){return 0===t}))return nn([],o);var a=new wi(e,r,o);return this.compileAndRun(a,[t])},e.prototype.reverse=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fi(e.shape,n):new di(e.shape,n);return this.compileAndRun(r,[e])},e.prototype.concat=function(e,n){if("complex64"===e[0].dtype){var r=e.map(function(t){return tn(t)}),o=e.map(function(t){return en(t)});return Ze(this.concat(r,n),this.concat(o,n))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,n);if(1===e.length)return e[0];if(e.length>t.ENV.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(e.length/2),i=this.concat(e.slice(0,a),n),s=this.concat(e.slice(a),n);return this.concat([i,s],n)}if(t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var u=new Yo(e.map(function(t){return t.shape}),n);return this.compileAndRun(u,e)}var l=Qe(e.map(function(t){return t.shape}),n),c=e.map(function(t){return t.as2D(-1,g(t.shape.slice(n)))}),h=new Xo(c.map(function(t){return t.shape}));return this.compileAndRun(h,c).reshape(l)},e.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Pi,e.dtype);var n=new Ti(e.shape,Pi);return this.compileAndRun(n,[e])},e.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),l=1===a?2:1,c=1===a?e.as3D(s,1,i):e;return this.multiply(u,c).sum(l,!0)}var h=xt(t.dtype,e.dtype),p=new Ja(t.shape,[s,o,a],n,r),d=this.makePackedTensor(p.outputShape,h);return this.compileAndRun(p,[t,e],d)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=o?n.shape[1]:n.shape[2],c=e.shape[0],h=xt(e.dtype,n.dtype),p=null!=a,d=null!=s,f=i?ts(i,!0):null,v=new Ja(e.shape,[c,u,l],r,o,p,f,d),m=this.makePackedTensor(v.outputShape,h),g=[e,n];return a&&g.push(a),s&&g.push(s),this.compileAndRun(v,g,m)},e.prototype.multiply=function(e,n){if("complex64"===e.dtype){var r=this.texData.get(e.dataId),o=this.texData.get(n.dataId),a=new Lo(Bo,e.shape,n.shape),i=new Lo(Po,e.shape,n.shape),s=[this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag),this.makeComplexComponentTensorHandle(n,o.complexTensors.real),this.makeComplexComponentTensorHandle(n,o.complexTensors.imag)],u=this.compileAndRun(a,s),l=this.compileAndRun(i,s),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Uo,e.dtype);var h=new Go(Uo,e.shape,n.shape),p=this.makeOutputArray(h.outputShape,e.dtype);return this.compileAndRun(h,[e,n],p)},e.prototype.batchNormalization=function(e,n,r,o,a,i){var s=[e,n,r],u=null;null!=i&&(u=i.shape,s.push(i));var l=null;if(null!=a&&(l=a.shape,s.push(a)),t.ENV.getBool("WEBGL_PACK_NORMALIZATION")){var c=new Mo(e.shape,n.shape,r.shape,u,l,o);return this.compileAndRun(c,s)}var h=new Fo(e.shape,n.shape,r.shape,u,l,o);return this.compileAndRun(h,s)},e.prototype.localResponseNormalization4D=function(e,n,r,o,a){var i=t.ENV.getBool("WEBGL_PACK_NORMALIZATION")?new Xa(e.shape,n,r,o,a):new Ka(e.shape,n,r,o,a);return this.compileAndRun(i,[e])},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new ja(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return X(t)});return io(Pn(t.shape,t.dtype,n),e)}var r=new Ri(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(e,n,r){var o=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ri(e.shape,n,r):new ni(e.shape,n,r);return this.compileAndRun(o,[e])},e.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var r=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ki(e.shape,n):new Ii(e.shape,n);return this.compileAndRun(r,[e])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new Na(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){d(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=hr(t.shape,e,r),a=pr(o.length,e.length),i=dr(t.shape,e,r),s=fr(n,e.length),u=vr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){d(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=hr(i.shape,e,r,!1),u=pr(s.length,e.length,!1),l=dr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(l)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=yr(o),i=new ii({windowSize:a,inSize:o,batchSize:r},e),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],n);return this.compileAndRun(i,[t],c),1===c.shape[1]?c:this.reduce(c,e,n)},e.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],o=t.shape[1];null!=n&&(r=n.shape[0],o=n.shape[1]);var a=yr(o),i=new ho({windowSize:a,inSize:o,batchSize:r},e,null==n),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],"int32"),h=[t];return null!=n&&h.push(n),this.compileAndRun(i,h,c),1===c.shape[1]?c:this.argReduce(t,e,c)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=yr(r[r.length-1]),a=new Do(r,o,e,null==n),i=this.makePackedTensor(a.outputShape,"int32"),s=null==n?[t]:[t,n];return this.compileAndRun(a,s,i),i.rank===t.rank?this.argReducePacked(t,e,i):i},e.prototype.sum=function(t,e){$e("sum",e,t.rank);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o),i=bt(t.dtype);return this.reduce(a,"sum",i).reshape(r)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o),i=bt(t.dtype);return this.reduce(a,"prod",i).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=Ke([r],t.rank),a=t;null!=o&&(a=t.transpose(o),r=Xe(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],o=t.length,a=0;a<o;a++)a!==e?r.push(t[a]):r.push(n);return r}(a.shape,r,n),s=g([a.shape[r]]),u=a.as2D(-1,s),l=bt(t.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",e,l,n).reshape(i);return null!=o&&(c=c.transpose(je(o))),c},e.prototype.segOpCompute=function(t,e,n,r,o){var a=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=gr?(n=t,r=!0):n=W(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=W(t,n+1);return n}(i,o),u=new mi({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),l=u.outputShape,c=l[0],h=l[1],p=this.makeOutputArray([c,h],r);return this.compileAndRun(u,[t,n],p),p.shape[1]===o?p:(n=mn(0,o).tile([i/s]),this.segOpCompute(p,e,n,r,o))},e.prototype.argMinMaxReduce=function(e,n,r){var o=[n];if($e("arg"+r.charAt(0).toUpperCase()+r.slice(1),o,e.rank),!t.ENV.getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var a=He(e.shape,o),i=a[0],s=g(a[1]),u=e.as2D(-1,s);return this.argReduce(u,r).reshape(i)}return this.argReducePacked(e,r)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var o=new ua(t.shape,n,r);return this.compileAndRun(o,[t])},e.prototype.equal=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(equal(a, b));\n","bool");var r=new Go("return float(a == b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.notEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(notEqual(a, b));\n","bool");var r=new Go("return float(a != b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(lessThan(a, b));\n","bool");var r=new Go("return float(a < b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.lessEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(lessThanEqual(a, b));\n","bool");var r=new Go("return float(a <= b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(greaterThan(a, b));\n","bool");var r=new Go("return float(a > b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.greaterEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var r=new Go("return float(a >= b);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.logicalNot=function(t){var e=new Ti(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var r=new Go("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.logicalOr=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n","bool");var r=new Go("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],o)},e.prototype.select=function(t,e,n){var r=new gi(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,xt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o)},e.prototype.where=function(t){Pe("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return uo(t.shape,e)},e.prototype.topk=function(t,e,n){return so(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){$e("min",e,t.rank);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},e.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("\n  vec4 result = vec4(min(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",e.shape,n.shape):new Go("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.mod=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("\n  vec4 result = mod(a, b);\n  vec4 isNaN = vec4(equal(b, vec4(0.0)));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",e.shape,n.shape):new Go("if (b == 0.0) return NAN;\n  return mod(a, b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);$e("max",e,t.rank);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},e.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("\n  vec4 result = vec4(max(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",e.shape,n.shape):new Go("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.all=function(t,e){$e("all",e,t.rank);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},e.prototype.any=function(t,e){$e("any",e,t.rank);var n=He(t.shape,e),r=n[0],o=g(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},e.prototype.squaredDifference=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("return (a - b) * (a - b);",e.shape,n.shape):new Go("return (a - b) * (a - b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.realDivide=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")){return this.packedBinaryOp(e,n,"\n  // vec4 one = vec4(equal(a, b));\n  // return one + (vec4(1.0) - one) * a / b;\n  vec4 result = a / b;\n  if(b.x == 0.0) {\n    result.x = NAN;\n  } else if(a.x == b.x) {\n    result.x = 1.;\n  }\n  if(b.y == 0.0) {\n    result.y = NAN;\n  } else if(a.y == b.y) {\n    result.y = 1.;\n  }\n  if(b.z == 0.0) {\n    result.z = NAN;\n  } else if(a.z == b.z) {\n    result.z = 1.;\n  }\n  if(b.w == 0.0) {\n    result.w = NAN;\n  } else if(a.w == b.w) {\n    result.w = 1.;\n  }\n\n  return result;\n","float32",!0)}var r=new Go("\nif (b == 0.0) {\n  return NAN;\n}\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"float32");return this.compileAndRun(r,[e,n],o)},e.prototype.floorDiv=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n  ivec4 ia = round(a);\n  ivec4 ib = round(b);\n  bvec4 cond = notEqual(ib, ivec4(0));\n  ivec4 result = ivec4(0);\n  vec4 s = sign(a) * sign(b);\n\n  // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n  if (cond[0]) {\n    result[0] = idiv(ia[0], ib[0], s[0]);\n  }\n  if (cond[1]) {\n    result[1] = idiv(ia[1], ib[1], s[1]);\n  }\n  if (cond[2]) {\n    result[2] = idiv(ia[2], ib[2], s[2]);\n  }\n  if (cond[3]) {\n    result[3] = idiv(ia[3], ib[3], s[3]);\n  }\n  return vec4(result);\n","int32");var r=new Go("\n  float s = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  if (ib != 0) {\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n    return float(idiv(ia, ib, s));\n  } else {\n    return NAN;\n  }\n",e.shape,n.shape),o=this.makeOutputArray(r.outputShape,"int32");return this.compileAndRun(r,[e,n],o)},e.prototype.add=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,Vo);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var r=xt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Vo,r);var o=new Go(Vo,e.shape,n.shape),a=this.makeOutputArray(o.outputShape,r);return this.compileAndRun(o,[e,n],a)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Qi(t.shape,e),o=this.makePackedTensor(r.outputShape,n);return this.compileAndRun(r,[t],o)},e.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new qo(n,t.shape,e.shape,o),i=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],i)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map(function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,i),l=new Go(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,xt(a.dtype,i.dtype));return r.compileAndRun(l,[s,u],c)}),s=i[0],u=i[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(e){if(1===e.length)return e[0];if(e.length>t.ENV.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),r=this.addN(e.slice(0,n)),o=this.addN(e.slice(n));return this.addN([r,o])}var a=e.map(function(t){return t.dtype}).reduce(function(t,e){return xt(t,e)}),i=e.map(function(t){return t.shape}),s=t.ENV.getBool("WEBGL_PACK"),u=s?new co(e[0].shape,i):new lo(e[0].shape,i),l=s?this.makePackedTensor(u.outputShape,a):this.makeOutputArray(u.outputShape,a);return this.compileAndRun(u,e,l)},e.prototype.subtract=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,Wo);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var r=xt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Wo,e.dtype);var o=new Go(Wo,e.shape,n.shape),a=this.makeOutputArray(o.outputShape,r);return this.compileAndRun(o,[e,n],a)},e.prototype.pow=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"),o=r?new qo("\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n  vec4 result = multiplier * pow(abs(a), b);\n\n  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n  bvec4 isExpZero = equal(b, vec4(0.0));\n  result.r = isExpZero.r ? 1.0 : result.r;\n  result.g = isExpZero.g ? 1.0 : result.g;\n  result.b = isExpZero.b ? 1.0 : result.b;\n  result.a = isExpZero.a ? 1.0 : result.a;\n\n  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",e.shape,n.shape):new Go("\nif(a < 0.0 && floor(b) < b){\n  return NAN;\n}\nif (b == 0.0) {\n  return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n    pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,n.shape),a=xt(e.dtype,n.dtype),i=r?this.makePackedTensor(o.outputShape,a):this.makeOutputArray(o.outputShape,a);return this.compileAndRun(o,[e,n],i)},e.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Li,e.dtype);var n=new Ti(e.shape,Li);return this.compileAndRun(n,[e])},e.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Vi,e.dtype);var n=new Ti(e.shape,Vi);return this.compileAndRun(n,[e])},e.prototype.sign=function(t){var e=new Ti(t.shape,"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new Ti(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isInf=function(t){var e=new Ti(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isFinite=function(t){var e=new Ti(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.round=function(t){var e=new Ti(t.shape,"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Wi,e.dtype);var n=new Ti(e.shape,Wi);return this.compileAndRun(n,[e])},e.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ui,e.dtype);var n=new Ti(e.shape,Ui);return this.compileAndRun(n,[e])},e.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,"\n  vec4 result = log(x);\n  vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n  result.r = isNaN.r == 1.0 ? NAN : result.r;\n  result.g = isNaN.g == 1.0 ? NAN : result.g;\n  result.b = isNaN.b == 1.0 ? NAN : result.b;\n  result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n  return result;\n",e.dtype);var n=new Ti(e.shape,"if (x < 0.0) return NAN;\n  return log(x);");return this.compileAndRun(n,[e])},e.prototype.log1p=function(t){var e=new Ti(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Ti(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Ti(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.square=function(t){var e=new Ti(t.shape,"return x * x;");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Ti(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(e){var n;return n=t.ENV.getBool("WEBGL_PACK")?new Qi(e.shape,Xi):new Ti(e.shape,Fi),this.compileAndRun(n,[e])},e.prototype.prelu=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo(Ho,e.shape,n.shape):new Go(zo,e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.elu=function(e){if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Yi,e.dtype);var n=new Ti(e.shape,Mi);return this.compileAndRun(n,[e])},e.prototype.eluDer=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",e.shape,n.shape):new Go("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.selu=function(t){var e=new Ti(t.shape,Bi);return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Ti(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},e.prototype.clip=function(e,n,r){var o,a=(o=t.ENV.getBool("WEBGL_PACK_CLIP")?new Ko(e.shape):new $o(e.shape)).getCustomSetupFunc(n,r);return this.compileAndRun(o,[e],null,a)},e.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Oi,e.dtype);var n=new Ti(e.shape,Oi);return this.compileAndRun(n,[e])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new jo(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Ti(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Ti(t.shape,"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new Ti(t.shape,zi);return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Ti(t.shape,Gi);return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Ti(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Ti(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Ti(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Ti(t.shape,Hi);return this.compileAndRun(e,[t])},e.prototype.atan2=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new qo("\n  vec4 result = atan(a, b);\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",e.shape,n.shape):new Go("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.sinh=function(t){var e=new Ti(t.shape,"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new Ti(t.shape,"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new Ti(t.shape,"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new Ti(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Ti(t.shape,qi);return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Ti(t.shape,$i);return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Ti(t.shape,'\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float t = 1.0 / (1.0 + p * x);\n  return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new Ti(t.shape,function(t){return void 0===t&&(t=0),Di+"\n    return x > 0.0 ? 1.0 : float("+t+");\n  "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(e,n,r,o,a,i){var s=e.shape,u=this.texData.get(e.dataId),l=r.inChannels,c=s[0]*s[1]*s[2],h=r.outChannels,p="channelsLast"===r.dataFormat,f=(1===c||1===h)&&l>1e3,v=s[2]%2!=0&&!!u.isPacked;if(f||!t.ENV.getBool("WEBGL_LAZILY_UNPACK")||!t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){var m=p?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],g=this.reshape(e,[1,m,r.inChannels]),y=this.reshape(n,[1,r.inChannels,r.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:y,transposeA:!1,transposeB:!1,bias:o,activation:a,preluActivationWeights:i}),r.outShape)}var x=p?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),b=ct.make([1,x,r.inChannels],{dataId:e.dataId},e.dtype,this),w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,d(Ce(u.shape,b.shape),function(){return"packed reshape "+u.shape+" to "+b.shape+" isn't free"});var C=this.reshape(n,[1,r.inChannels,r.outChannels]),E=this.fusedBatchMatMul({a:b,b:C,transposeA:!1,transposeB:!1,bias:o,activation:a,preluActivationWeights:i}),N=this.texData.get(E.dataId);return d(N.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=w,N.shape=r.outShape,ct.make(r.outShape,{dataId:E.dataId},E.dtype,this)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,h="channelsLast"===n.dataFormat,p=i*s*u,d=c*l,f=[p,d],v=t.squeeze([0]),m=e.reshape([1,p,-1]),g=new $a(f,v.shape,n),y=this.compileAndRun(g,[v]).reshape([1,f[0],f[1]]),x=null!=r,b=null!=a,w=o?ts(o,!0):null,C=new Ja(y.shape,[1,d,n.outChannels],!0,!1,x,w,b),E=[y,m];r&&E.push(r),b&&E.push(a);var N=this.compileAndRun(C,E);return h?N.reshape([1,c,l,n.outChannels]):N.reshape([1,n.outChannels,c,l])},e.prototype.fusedConv2d=function(e,n,r,o,a,i){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,o,a,i);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,a,i);var s=null!=o,u=null!=i,l=a?ts(a,!1):null,c=new ra(r,s,l,u),h=[e,n];return o&&h.push(o),i&&h.push(i),this.compileAndRun(c,h)},e.prototype.conv2d=function(e,n,r){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r);var o=new ra(r);return this.compileAndRun(o,[e,n])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Jo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Qo(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2D=function(e,n,r){var o;return t.ENV.getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels==1?(o=new ia(r),this.compileAndRun(o,[e,n],this.makePackedTensor(r.outShape,e.dtype))):(o=new aa(r),this.compileAndRun(o,[e,n]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new na(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new ea(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new oa(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new ta(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new Zo(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new oi(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},e.prototype.avgPool=function(t,e){var n=new oi(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},e.prototype.maxPoolBackprop=function(t,e,n,r){var o=new oi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Ya(r),s=this.makeOutputArray(i.outputShape,e.dtype),u=this.compileAndRun(i,[t,a],s);return a.dispose(),u},e.prototype.avgPoolBackprop=function(t,e,n){var r=new _o(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},e.prototype.cast=function(t,e){return Xr(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},e.prototype.avgPool3d=function(t,e){var n=new ai(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new Oo(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},e.prototype.maxPool3d=function(t,e){var n=new ai(e,"max",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},e.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new ai(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Qa(r),s=this.makeOutputArray(i.outputShape,e.dtype),u=this.compileAndRun(i,[t,a],s);return a.dispose(),u},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);return!n.isPacked||Ce(t.shape,e)||null!==n.texture&&Ce(n.shape,e)?Yr(t,e):this.packedReshape(t,e)},e.prototype.resizeBilinear=function(e,n,r,o){var a=t.ENV.getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ci(e.shape,n,r,o):new li(e.shape,n,r,o);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new ui(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new pi(t.shape,e,n,r);return this.compileAndRun(o,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new hi(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var o=e?t:Tr(t),a=o.shape[0],i=o.shape[1],s=new Za(a,i,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],u,l)},e.prototype.oneHot=function(t,e,n,r){var o=new ti(t.size,e,n,r);return this.compileAndRun(o,[t])},e.prototype.diag=function(t){var e=new da(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return Pe("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),ro(t.dataSync(),e.dataSync(),n,r,o)},e.prototype.cropAndResize=function(t,e,n,r,o,a){var i=new sa(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n])},e.prototype.depthToSpace=function(t,e,n){d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,l=i/(e*e),c=new pa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return ao(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=br(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/i,i],c=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return Yr(nn([]),n);var p=on(0),d=new vi(a,o,c.rank,h.rank,s,l);return this.compileAndRun(d,[h,c,p]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var o=br(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,l=new vi(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ba(ya,t.shape,e),o=new ba(xa,t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=mr(t,e),a=o[0],i=o[1],s=o[2],u=o[3],l=e.reshape([i,r]),c=t.reshape([t.size/s,s]),h=new Ra(r,u,[i,s]);return this.compileAndRun(h,[c,l]).reshape(a)},e.prototype.fill=function(t,e,n){if("string"===(n=n||L(e))){var r=S(n,g(t));return r.fill(e),ct.make(t,{values:r},n)}var o=new wa(t,e),a=o.getCustomSetupFunc(e),i=this.makeOutputArray(t,n);return this.compileAndRun(o,[],i,a)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Qr(t,e,n)},e.prototype.makeOutputArray=function(t,e){return ct.make(t,{},e,this)},e.prototype.makePackedTensor=function(t,e){var n=ct.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},e.prototype.unpackTensor=function(t){var e=new Ji(t.shape);return this.compileAndRun(e,[t],ct.make(e.outputShape,{},t.dtype,this))},e.prototype.packTensor=function(t){var e=new ei(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},e.prototype.packedReshape=function(t,e){var n=t.reshape([ge(t.shape)].concat(ye(t.shape))),r=[ge(e)].concat(ye(e)),o=new si(r,n.shape);return this.compileAndRun(o,[n]).reshape(e)},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=xe(o),s=Lt(o),u=this.makeTensorHandle(o,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new ha(i,s):new ca(i,s),this.compileAndRun(e,[{shape:i,dtype:a,dataId:t}],u,null,!0),u},e.prototype.compileAndRun=function(e,n,r,o,a){var i=this;if(void 0===a&&(a=!1),null==r&&(r=e.usesPackedTextures?this.makePackedTensor(e.outputShape,n[0].dtype):this.makeOutputArray(e.outputShape,n[0].dtype)),0===r.size)return this.texData.get(r.dataId).values=k(r.dtype,0),r;var s=n.map(function(n){if("complex64"===n.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var r=i.texData.get(n.dataId);if(null==r.texture){if(!e.usesPackedTextures&&g(n.shape)<=t.ENV.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:n.shape,texData:null,isUniform:!0,uniformValues:r.values};e.usesPackedTextures&&(r.isPacked=!0,r.shape=n.shape)}else if(!!r.isPacked!=!!e.usesPackedTextures)n=r.isPacked?i.unpackTensor(n):i.packTensor(n),r=i.texData.get(n.dataId);else if(r.isPacked&&!Ce(r.shape,n.shape)){var o=n,a=n.shape;n.shape=r.shape,n=i.packedReshape(n,a),r=i.texData.get(n.dataId),o.shape=a}return i.uploadToGPU(n.dataId),{shape:n.shape,texData:r,isUniform:!1}});this.uploadToGPU(r.dataId);var u,l={shape:r.shape,texData:this.texData.get(r.dataId),isUniform:!1},c=function(t,e,n){var r="";e.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var o=t.userCode,a=t.constructor.name;return a+="_"+r+"_"+o}(e,s,l),h=this.getAndSaveBinary(c,function(){return function(e,n,r,o){var a=n.userCode,i=r.map(function(t,e){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:n.variableNames[e],shapeInfo:r}}),s=i.map(function(t){return t.shapeInfo}),u={logicalShape:o.shape,texShape:o.texData.texShape,isUniform:!1,isPacked:o.texData.isPacked,flatOffset:null},l=xo(i,u,a,n.usesPackedTextures),c=e.createProgram(l),h=null,p=e.getUniformLocation(c,"NAN",!1);1===t.ENV.getNumber("WEBGL_VERSION")&&(h=e.getUniformLocation(c,"INFINITY",!1));for(var d={},f=0;f<n.variableNames.length;f++){var v=n.variableNames[f];d[v]=e.getUniformLocation(c,v,!1),d["offset"+v]=e.getUniformLocation(c,"offset"+v,!1)}return{program:n,source:l,webGLProgram:c,uniformLocations:d,inShapeInfos:s,outShapeInfo:u,infLoc:h,nanLoc:p}}(i.gpgpu,e,s,l)}),p=null!=this.activeTimers;return p&&(u=this.startTimer()),function(e,n,r,o,a){qa(n.inShapeInfos,r),qa([n.outShapeInfo],[o]);var i=o.texData.texture,s=o.texData.texShape;o.texData.isPacked?e.setOutputPackedMatrixTexture(i,s[0],s[1]):e.setOutputMatrixTexture(i,s[0],s[1]),e.setProgram(n.webGLProgram),1===t.ENV.getNumber("WEBGL_VERSION")&&null!==n.infLoc&&e.gl.uniform1f(n.infLoc,1/0),null!==n.nanLoc&&e.gl.uniform1f(n.nanLoc,NaN),r.forEach(function(t,r){var o=n.program.variableNames[r],a=n.uniformLocations[o],i=n.uniformLocations["offset"+o];if(null!=a)if(t.isUniform)if(g(t.shape)<2)e.gl.uniform1f(a,t.uniformValues[0]);else{var s=t.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),e.gl.uniform1fv(a,s)}else null!=t.texData.slice&&null!=i&&e.gl.uniform1i(i,t.texData.slice.flatOffset),e.setInputMatrixTexture(t.texData.texture,a,r)}),null!=a&&a(e,n.webGLProgram),e.executeProgram()}(this.gpgpu,h,s,l,o),p&&(u=this.endTimer(u),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(u)})),!t.ENV.getBool("WEBGL_LAZILY_UNPACK")&&this.texData.get(r.dataId).isPacked&&!1===a?this.unpackTensor(r):r},e.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){this.disposed||(this.textureManager.dispose(),null!=this.canvas&&null!=this.canvas.remove?this.canvas.remove():this.canvas=null,null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},e.prototype.floatPrecision=function(){var e=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Fe(function(){if(!t.ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")){var n=t.ENV.getBool("DEBUG");t.ENV.set("DEBUG",!1);var r=e.abs(on(1e-8)).dataSync()[0];if(t.ENV.set("DEBUG",n),r>0)return 32}return 16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var l,c=null!=this.activeTimers;c&&(l=$());var h=n.texShape;if(null==h&&(h=be(r,u),n.texShape=h),null!=a){var p=xe(r),d=void 0,f=h[1],v=h[0],m=a instanceof Uint8Array;u?(f=(e=Vt(h[0],h[1]))[0],v=e[1],d=new ga(p,[v,f],m)):d=new ma(p,[v,f],m);var y=this.makeTensorHandle([v,f],o);this.texData.get(y.dataId).usage=m?Tt.PIXELS:Tt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),f,v,a);var x=this.makeTensorHandle(d.outputShape,y.dtype);x.size=g(d.outputShape),this.texData.get(x.dataId).isPacked=u,this.compileAndRun(d,[y],x);var b=this.texData.get(x.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(y.dataId),this.texData.delete(x.dataId),n.values=null,c&&(this.uploadWaitMs+=$()-l)}else{var w=this.acquireTexture(h,s,o,u);n.texture=w}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},e.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*O(e)},e}();At()&&St.registerBackend("webgl",function(){return new ns},2);var rs=Je({abs_:function(t){var e=We(t,"x","abs");return"complex64"===e.dtype?St.runKernel(function(t){return t.complexAbs(e)},{$x:e}):St.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),os=Je({acos_:function(t){var e=We(t,"x","acos");return St.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(on(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),as=Je({acosh_:function(t){var e=We(t,"x","acosh");return St.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),is=Je({asin_:function(t){var e=We(t,"x","asin");return St.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(on(1).sub(n.toFloat().square()).sqrt())}}})}}),ss=Je({asinh_:function(t){var e=We(t,"x","asinh");return St.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(on(1).add(n.toFloat().square()).sqrt())}}})}}),us=Je({atan_:function(t){var e=We(t,"x","atan");return St.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),ls=Je({atanh_:function(t){var e=We(t,"x","atanh");return St.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(on(1).sub(n.toFloat().square()))}}})}}),cs=Je({ceil_:function(t){var e=We(t,"x","ceil");return St.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),hs=Je({clipByValue_:function(t,e,n){var r=We(t,"x","clipByValue");return d(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),St.runKernel(function(t,o){var a=t.clip(r,e,n);return o([r]),a},{$x:r},function(t,r){var o=r[0];return{$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),yn(t))}}})}}),ps=Je({cos_:function(t){var e=We(t,"x","cos");return St.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),ds=Je({cosh_:function(t){var e=We(t,"x","cosh");return St.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),fs=Je({erf_:function(t){var e=We(t,"x","erf");return d("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),St.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),vs=Je({exp_:function(t){var e=We(t,"x","exp");return St.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),ms=Je({expm1_:function(t){var e=We(t,"x","expm1");return St.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),gs=Je({floor_:function(t){var e=We(t,"x","floor");return St.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ys=Je({log_:function(t){var e=We(t,"x","log");return St.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),xs=Je({log1p_:function(t){var e=We(t,"x","log1p");return St.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),bs=Je({logSigmoid_:function(t){var e=We(t,"x","logSigmoid");return St.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),ws=Je({neg_:function(t){var e=We(t,"x","neg");return St.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),Cs=Je({reciprocal_:function(t){var e=We(t,"x","reciprocal");return St.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),Es=Je({round_:function(t){var e=We(t,"x","round");return St.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),Ns=Je({rsqrt_:function(t){var e=We(t,"x","rsqrt");return St.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),Rs=Je({sigmoid_:function(t){var e=We(t,"x","sigmoid");return St.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(on(1).sub(n)))}}})}}),Is=Je({sign_:function(t){var e=We(t,"x","sign");return St.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ks=Je({isNaN_:function(t){var e=We(t,"x","isNaN");return St.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),Ss=Je({isInf_:function(t){var e=We(t,"x","isInf");return St.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),As=Je({isFinite_:function(t){var e=We(t,"x","isFinite");return St.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),Ts=Je({sin_:function(t){var e=We(t,"x","sin");return St.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),Ds=Je({sinh_:function(t){var e=We(t,"x","sinh");return St.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),_s=Je({softplus_:function(t){var e=We(t,"x","softplus");return St.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),Os=Je({sqrt_:function(t){var e=We(t,"x","sqrt");return St.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),Fs=Je({square_:function(t){var e=We(t,"x","square");return St.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),Ms=Je({step_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","step");return St.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return yn(t)}}})}}),Bs=Je({tan_:function(t){var e=We(t,"x","tan");return St.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),Ps=Je({tanh_:function(t){var e=We(t,"x","tanh");return St.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return on(1).sub(n.square()).mulStrict(t)}}})}});function Ls(t,e,n,r,o,a){var i,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=o&&(i=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),d(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),d(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(2===i.rank||1===i.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),Us(u,l,c,s,i,a)}function Vs(t,e,n,r,o,a){var i,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=o&&(i=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),d(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),d(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(3===i.rank||1===i.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),Us(u,l,c,s,i,a)}function Ws(t,e,n,r,o,a){var i,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=o&&(i=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),d(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),d(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(4===i.rank||1===i.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),Us(u,l,c,s,i,a)}function Us(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,l=We(t,"x","batchNorm"),c=We(e,"mean","batchNorm"),h=We(n,"variance","batchNorm");null!=o&&(i=We(o,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),d(c.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),d(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),d(null==i||c.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;return St.runKernel(function(t,e){var n=t.batchNormalization(u,zs(c),zs(h),a,zs(i),zs(s));return e([l,c,h,i]),n},{$x:l,$mean:c,$variance:h,$scale:i,$offset:s},function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],l=null==s?on(1):s,c=Mr(o.shape,u.shape),h=[];if(1===o.rank){for(var p=0;p<u.shape.length-1;++p)h.push(u.shape[p]);h.push(1)}var d=r.sub(o),f=t.mul(l),v=Ns(i.add(on(a))),m=v.mul(v).mul(v).mul(on(-.5));return{$x:function(){return 1===o.rank?t.mul(sr(v.as4D(1,1,1,o.shape[0]),h)).mul(l).reshape(r.shape):t.mul(v).mul(l).reshape(r.shape)},$mean:function(){var t=v.mul(on(-1)).mul(f);return 1===o.rank&&(t=t.sum(c)),t.reshape(o.shape)},$variance:function(){var t=m.mul(d).mul(f);return 1===o.rank&&(t=t.sum(c)),t.reshape(o.shape)},$scale:function(){var e=d.mul(v),n=t.mul(e);return 1===o.rank&&(n=n.sum(c)),n.reshape(o.shape)},$offset:function(){var e=t;return 1===o.rank&&(e=e.sum(c)),e.reshape(o.shape)}}}).reshape(l.shape)}function zs(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function Gs(){Oe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Hs=Je({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Gs(),Ls(t,e,n,a,o,r)}}),qs=Je({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Gs(),Vs(t,e,n,a,o,r)}}),$s=Je({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Gs(),Ws(t,e,n,a,o,r)}}),Ks=Je({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Gs(),Us(t,e,n,a,o,r)}}),js=Je({batchNorm_:Us}),Xs=Je({batchNorm2d_:Ls}),Ys=Je({batchNorm3d_:Vs}),Qs=Je({batchNorm4d_:Ws});var Js=Je({logicalAnd_:function(t,e){var n=We(t,"a","logicalAnd","bool"),r=We(e,"b","logicalAnd","bool");return Br(n.shape,r.shape),St.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),Zs=Je({logicalNot_:function(t){var e=We(t,"x","logicalNot","bool");return St.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),tu=Je({logicalOr_:function(t,e){var n=We(t,"a","logicalOr","bool"),r=We(e,"b","logicalOr","bool");return Br(n.shape,r.shape),St.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),eu=Je({logicalXor_:function(t,e){var n=We(t,"a","logicalXor","bool"),r=We(e,"b","logicalXor","bool");return Br(n.shape,r.shape),tu(t,e).logicalAnd(Js(t,e).logicalNot())}}),nu=Je({where_:function(t,e,n){var r=We(e,"a","where"),o=We(n,"b","where"),a=We(t,"condition","where","bool");return f(r.shape,o.shape,"Error in where: "),1===a.rank?d(a.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):f(a.shape,o.shape,"Error in where: "),St.runKernel(function(t,e){var n=t.select(a,r,o);return e([a]),n},{$condition:a,$a:r,$b:o},function(t,e){var n=e[0];return{$condition:function(){return yn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),ru=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){switch(o.label){case 0:return[4,(e=We(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=uo(e.shape,n),t!==e&&e.dispose(),[2,r]}})})};var ou=Je({add_:function(t,e){var n,r=We(t,"a","add"),o=We(e,"b","add");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t){return t.add(r,o)},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=Mr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Mr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}})}}),au=Je({addN_:function(t){d(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return We(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!y(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return St.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),iu=Je({addStrict_:function(t,e){var n=We(t,"a","addStrict"),r=We(e,"b","addStrict");return f(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),su=Je({atan2_:function(t,e){var n,r=We(t,"a","atan2"),o=We(e,"b","atan2");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t,e){var n=t.atan2(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=ou(n.square(),r.square()),o=t.mul(r.div(e)),i=Mr(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=ou(n.square(),r.square()),o=ws(t.mul(n.div(e))),i=Mr(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}})}}),uu=Je({div_:function(t,e){var n,r=We(t,"a","div"),o=We(e,"b","div");if(n=wt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return cu(r,o);var a=Br(r.shape,o.shape);return St.runKernel(function(t,e){var n=t.realDivide(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Mr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Mr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),lu=Je({divStrict_:function(t,e){var n=We(t,"a","div"),r=We(e,"b","div");return f(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),cu=Je({floorDiv_:function(t,e){var n,r=We(t,"a","floorDiv"),o=We(e,"b","floorDiv");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Mr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Mr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),hu=Je({maximum_:function(t,e){var n,r=We(t,"a","maximum"),o=We(e,"b","maximum");return n=wt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Br(r.shape,o.shape),St.runKernel(function(t,e){var n=t.maximum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),pu=Je({maximumStrict_:function(t,e){var n=We(t,"a","maximumStrict"),r=We(e,"b","maximumStrict");return f(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),du=Je({minimum_:function(t,e){var n,r=We(t,"a","minimum"),o=We(e,"b","minimum");return n=wt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Br(r.shape,o.shape),St.runKernel(function(t,e){var n=t.minimum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),fu=Je({minimumStrict_:function(t,e){var n=We(t,"a","minimumStrict"),r=We(e,"b","minimumStrict");return f(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),vu=Je({mod_:function(t,e){var n,r=We(t,"a","mod"),o=We(e,"b","mod");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t,e){var n=t.mod(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Mr(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Mr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),mu=Je({modStrict_:function(t,e){var n=We(t,"a","modStrict"),r=We(e,"b","modStrict");return f(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),gu=Je({mul_:function(t,e){var n,r=We(t,"a","mul"),o=We(e,"b","mul");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t,e){var n=t.multiply(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),o=Mr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Mr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),yu=Je({mulStrict_:function(t,e){var n=We(t,"a","mul"),r=We(e,"b","mul");return f(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),xu=Je({pow_:function(t,e){var n=We(t,"base","pow"),r=We(e,"exp","pow"),o=Br(n.shape,r.shape);return t=n.cast(xt(n.dtype,r.dtype)),e=r.cast(xt(n.dtype,r.dtype)),St.runKernel(function(t,e){var o=t.pow(n,r);return e([n,r,o]),o},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(on(1))))),i=Mr(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),i=n.log().where(e,yn(n)),s=t.mul(a.mul(i)),u=Mr(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),bu=Je({powStrict_:function(t,e){return f(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),wu=Je({squaredDifference_:function(t,e){var n,r=We(t,"a","squaredDifference"),o=We(e,"b","squaredDifference");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1],o=on(2);return{$a:function(){return t.mul(n.sub(r).mul(o))},$b:function(){return t.mul(r.sub(n).mul(o))}}})}}),Cu=Je({squaredDifferenceStrict_:function(t,e){var n=We(t,"a","squaredDifferenceStrict"),r=We(e,"b","squaredDifferenceStrict");return f(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Eu=Je({sub_:function(t,e){var n,r=We(t,"a","sub"),o=We(e,"b","sub");n=wt(r,o),r=n[0],o=n[1];var a=Br(r.shape,o.shape);return St.runKernel(function(t){return t.subtract(r,o)},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=Mr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Mr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}})}}),Nu=Je({subStrict_:function(t,e){var n=We(t,"a","subStrict"),r=We(e,"b","subStrict");return f(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var Ru=Je({equal_:function(t,e){var n,r=We(t,"a","equal"),o=We(e,"b","equal");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t){return t.equal(r,o)},{$a:r,$b:o})}}),Iu=Je({equalStrict_:function(t,e){var n=We(t,"a","equalStrict"),r=We(e,"b","equalStrict");return f(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),ku=Je({greater_:function(t,e){var n,r=We(t,"a","greater"),o=We(e,"b","greater");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t){return t.greater(r,o)},{$a:r,$b:o})}}),Su=Je({greaterEqual_:function(t,e){var n,r=We(t,"a","greaterEqual"),o=We(e,"b","greaterEqual");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t,e){var n=t.greaterEqual(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return yn(n)},$b:function(){return yn(r)}}})}}),Au=Je({greaterEqualStrict_:function(t,e){var n=We(t,"a","greaterEqualStrict"),r=We(e,"b","greaterEqualStrict");return f(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),Tu=Je({greaterStrict_:function(t,e){var n=We(t,"a","greaterStrict"),r=We(e,"b","greaterStrict");return f(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),Du=Je({less_:function(t,e){var n,r=We(t,"a","less"),o=We(e,"b","less");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t){return t.less(r,o)},{$a:r,$b:o})}}),_u=Je({lessEqual_:function(t,e){var n,r=We(t,"a","lessEqual"),o=We(e,"b","lessEqual");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t){return t.lessEqual(r,o)},{$a:r,$b:o})}}),Ou=Je({lessEqualStrict_:function(t,e){var n=We(t,"a","lessEqualStrict"),r=We(e,"b","lessEqualStrict");return f(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),Fu=Je({lessStrict_:function(t,e){var n=We(t,"a","lessStrict"),r=We(e,"b","lessStrict");return f(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Mu=Je({notEqual_:function(t,e){var n,r=We(t,"a","notEqual"),o=We(e,"b","notEqual");return n=wt(r,o),r=n[0],o=n[1],Br(r.shape,o.shape),St.runKernel(function(t){return t.notEqual(r,o)},{$a:r,$b:o})}}),Bu=Je({notEqualStrict_:function(t,e){var n=We(t,"a","notEqualStrict"),r=We(e,"b","notEqualStrict");return f(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Pu(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Lu(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var Vu=Je({gather_:function(t,e,n){void 0===n&&(n=0);var r=We(t,"x","gather"),o=We(e,"indices","gather","int32");n=R(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],o=[],a=1,i=1,s=0;s<n;s++)o.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)o.push(e.shape[s]);for(s=n+1;s<t.rank;s++)o.push(t.shape[s]),i*=t.shape[s];return{batchSize:a,sliceSize:i,dimSize:r,outputShape:o}}(r,o,n);return St.runKernel(function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a},{$x:r},function(t,e){var o=e[0];return{$x:function(){var e=r.shape,a=o.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),l=u.length,c=Pu(0,s),h=Pu(s+1,s+1+l),p=Lu([i,[a],u]),d=t.reshape(p),f=o.reshape([a]),v=Lu([[s],c,h]),m=d.transpose(v),g=Wu(m,f,r.shape[n]),y=je(v);return g=g.transpose(y)}}}).reshape(a.outputShape)}}),Wu=Je({unsortedSegmentSum_:function(t,e,n){var r=We(t,"x","unsortedSegmentSum"),o=We(e,"segmentIds","unsortedSegmentSum","int32");return d(x(n),function(){return"numSegments must be of dtype int"}),St.runKernel(function(t,e){var a=t.unsortedSegmentSum(r,o,n);return e([o]),a},{$x:r},function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=hu(e,yn(e)),r=Vu(t,n),o=Su(e,on(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=Hn(o,i+1);o=Js(o,pn(r.shape,"bool"));var s=yn(r);return nu(o,r,s)}(t,n)}}})}});var Uu=function(t,e,n){return r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p,v,m,g,y;return o(this,function(o){switch(o.label){case 0:for(r=We(t,"tensor","boolMask"),a=We(e,"mask","boolMask","bool"),i=null==n?0:n,s=a.rank,u=r.shape,d(s>0,function(){return"mask cannot be scalar"}),f(u.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=i;c<i+s;c++)l*=u[c];return h=u.slice(0,i).concat([l],u.slice(i+s)),p=r.reshape(h),v=a.reshape([-1]),[4,ru(v)];case 1:return m=o.sent(),g=m.squeeze([1]),y=Vu(p,g,i),t!==r&&r.dispose(),e!==a&&a.dispose(),g.dispose(),p.dispose(),v.dispose(),m.dispose(),[2,y]}})})};function zu(t,e,n,r,o,a,i){void 0===a&&(a="NHWC"),d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var s=t,u=e,l=!1;3===e.rank&&(l=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),d(4===s.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."}),d(4===u.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank}),d(4===n.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank});var c="NHWC"===a?s[3]:s[1],h="NHWC"===a?u.shape[3]:u.shape[1];d(c===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+c+") must match input depth for filter "+n.shape[2]+"."}),d(h===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."}),null!=i&&d(x(o),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var p=jr(a),f=Vr(s,n.shape,r,1,o,i,!1,p),v=St.runKernel(function(t,e){var r=t.conv2dDerInput(u,n,f);return e([n,u]),r},{dy4D:u,filter:n},function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return Ku(t,n,r,o,a,1,i)},filter:function(){return Xu(t,s,n.shape,r,o,a,i)}}});return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}function Gu(t,e,n,r,o,a,i){void 0===a&&(a="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),d(4===s.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."}),d(4===u.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."}),d(4===n.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."});var l="NHWC"===a?s.shape[3]:s.shape[1],c="NHWC"===a?u.shape[3]:u.shape[1];d(l===n[2],function(){return"Error in conv2dDerFilter: depth of input "+l+") must match input depth in filter ("+n[2]+"."}),d(c===n[3],function(){return"Error in conv2dDerFilter: depth of dy ("+c+") must match output depth for filter ("+n[3]+")."}),null!=i&&d(x(o),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var h=jr(a),p=Vr(s.shape,n,r,1,o,i,!1,h);return St.runKernel(function(t){return t.conv2dDerFilter(s,u,p)},{x4D:s,dy4D:u})}function Hu(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function qu(t,e,n,r,o){d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var a=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],l=i.shape[4];d(5===a.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."}),d(5===i.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank}),d(5===n.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank}),d(u===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."}),d(l===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[4]+"."});var c=Wr(a,n.shape,r,1,o),h=St.runKernel(function(t){return t.conv3dDerInput(i,n,c)},{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var $u=Je({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=We(t,"x","conv1d"),u=We(e,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),d(3===l.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."}),d(3===u.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),null!=i&&d(x(r),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}),d(l.shape[2]===u.shape[1],function(){return"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."}),d(Kr(n,a),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"}),d("NWC"===o,function(){return"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported."});var h=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),p=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),f=Ku(p,h,[1,n],r,"NHWC",[1,a],i);return c?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),Ku=Je({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=We(t,"x","conv2d"),u=We(e,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),null!=i&&d(x(r),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var h="NHWC"===o?l.shape[3]:l.shape[1];d(h===u.shape[2],function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."}),d(Kr(n,a),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"});var p=jr(o),f=Vr(l.shape,u.shape,n,a,r,i,!1,p),v=St.runKernel(function(t,e){var n=t.conv2d(l,u,f);return e([u,l]),n},{x:l,$filter:u},function(t,e){var i=e,s=i[0],u=i[1];return d($r(a),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"}),{x:function(){return zu(u.shape,t,s,n,r,o)},$filter:function(){return Gu(u,t,s.shape,n,r,o)}}});return c?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),ju=Je({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=We(t,"x","conv3d"),s=We(e,"filter","conv3d"),u=i,l=!1;4===i.rank&&(l=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),d(5===u.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),d(5===s.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),d(u.shape[4]===s.shape[3],function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."}),d(function(t,e){return Hu(t)||Hu(e)}(n,a),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),d("NDHWC"===o,function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."});var c=Wr(u.shape,s.shape,n,a,r),h=St.runKernel(function(t,e){var n=t.conv3d(u,s,c);return e([u,s]),n},{x:u,$filter:s},function(t,e){d(Hu(a),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"});var o=e[0],i=e[1];return{x:function(){return qu(o.shape,t,i,n,r)},$filter:function(){return function(t,e,n,r,o){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),d(5===a.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."}),d(5===i.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."}),d(5===n.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."}),d(a.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."}),d(i.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+")."});var s=Wr(a.shape,n,r,1,o);return St.runKernel(function(t){return t.conv3dDerFilter(a,i,s)},{x5D:a,dy5D:i})}(o,t,i.shape,n,r)}}});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Xu=Je({conv2dDerFilter_:Gu}),Yu=Je({conv2dDerInput_:zu}),Qu=Je({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=We(t,"x","depthwiseConv2d"),u=We(e,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),d(l.shape[3]===u.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."}),null==a&&(a=[1,1]),d(Kr(n,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),null!=i&&d(x(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var h=Vr(l.shape,u.shape,n,a,r,i,!0),p=St.runKernel(function(t,e){var n=t.depthwiseConv2D(l,u,h);return e([l,u]),n},{x:l,$filter:u},function(t,e){d($r(a),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+a+"'"});var n=e[0],r=e[1];return{x:function(){return function(t,e,n,r){var o=e,a=!1;3===e.rank&&(a=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=St.runKernel(function(t){return t.depthwiseConv2DDerInput(o,n,r)},{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}(n.shape,t,r,h)},$filter:function(){return function(t,e,n,r){var o=t;3===t.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=e;return 3===a.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),St.runKernel(function(t){return t.depthwiseConv2DDerFilter(o,a,r)},{x4D:o,dy4D:a})}(n,t,r.shape,h)}}});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),Ju=Je({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=We(t,"x","separableConv2d"),u=We(e,"depthwiseFilter","separableConv2d"),l=We(n,"pointwiseFilter","separableConv2d"),c=s,h=!1;if(3===s.rank&&(h=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");d(4===c.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."}),d(4===u.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),d(4===l.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),d(1===l.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+l.shape[0]+"."}),d(1===l.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+"."});var p=u.shape[2],f=u.shape[3];d(l.shape[2]===p*f,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+p*f+", but got "+l.shape[2]+"."});var v=Qu(c,u,r,o,i,a),m=Ku(v,l,1,"valid",i);return h?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Zu=Je({conv2dTranspose_:function(t,e,n,r,o,a){return zu(n,We(t,"x","conv2dTranspose"),We(e,"filter","conv2dTranspose"),r,o,"NHWC",a)}}),tl=Je({conv3dTranspose_:function(t,e,n,r,o){return qu(n,We(t,"x","conv3dTranspose"),We(e,"filter","conv3dTranspose"),r,o)}});var el=Je({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=We(t,"a","matMul"),i=We(e,"b","matMul");o=wt(a,i),a=o[0],i=o[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],l=n?a.shape[a.rank-1]:a.shape[a.rank-2],c=r?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),p=i.shape.slice(0,-2),f=g(h),v=g(p);d(a.rank>=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),d(y(h,p),function(){return"Error in matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),d(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var m=a.shape.slice(0,-2).concat([l,c]),x=n?a.as3D(f,s,l):a.as3D(f,l,s),b=r?i.as3D(v,c,u):i.as3D(v,u,c);return St.runKernel(function(t,e){var o=t.batchMatMul(x,b,n,r);return e([x,b]),o},{$a:x,$b:b},function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{$a:function(){return t.matMul(i,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return i.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return i.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(i,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(m)}}),nl=Je({dot_:function(t,e){var n=We(t,"t1","dot"),r=We(e,"t2","dot");d(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return d(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),rl=Je({outerProduct_:function(t,e){var n=We(t,"v1","outerProduct"),r=We(e,"v2","outerProduct");return d(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}});var ol=Je({reverse_:function(t,e){var n=We(t,"x","reverse");if(0===n.rank)return n.clone();var r=R(e,n.shape);return St.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),al=Je({reverse1d_:function(t){var e=We(t,"x","reverse");return d(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),ol(e,0)}}),il=Je({reverse2d_:function(t,e){var n=We(t,"x","reverse");return d(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),ol(n,e)}}),sl=Je({reverse3d_:function(t,e){var n=We(t,"x","reverse");return d(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),ol(n,e)}}),ul=Je({reverse4d_:function(t,e){var n=We(t,"x","reverse");return d(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),ol(n,e)}});function ll(t,e,n,r,o,a){var i=We(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),d(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),d(Kr(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&d(x(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=Pr(s.shape,e,n,r,o,a),c=St.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=We(t,"dy","maxPoolBackprop"),l=We(e,"input","maxPoolBackprop"),c=We(n,"output","maxPoolBackprop");d(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),d(Kr(o,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),d(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}),null!=s&&d(x(i),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var h=Pr(l.shape,r,o,a,i,s);return St.runKernel(function(t){return t.maxPoolBackprop(u,l,c,h)},{$dy:u,$input:l})}(t,i,s,e,n,r,o)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function cl(t,e,n,r,o,a){var i=We(t,"x","avgPool","float32");null==r&&(r=[1,1]),d(Kr(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&d(x(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=Pr(s.shape,e,n,r,o,a),c=St.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,o,a){var i=We(t,"dy","avgPoolBackprop"),s=We(e,"input","avgPoolBackprop");d(s.rank===i.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"}),null==o&&(o=[1,1]),d(Kr(r,o),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"});var u=s,l=i,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var h=Pr(u.shape,n,r,o,a),p=St.runKernel(function(t){return t.avgPoolBackprop(l,u,h)},{dy4D:l,input4D:u});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(t,s,e,n,r,o)}}});return c=c.cast(i.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var hl=Je({maxPool_:function(t,e,n,r,o){return ll(t,e,n,1,r,o)}}),pl=Je({avgPool_:function(t,e,n,r,o){return cl(t,e,n,1,r,o)}}),dl=Je({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=We(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(Kr(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var l,c=Pr(s.shape,e,a,o,r),h=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),o=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],o[e]]})}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];var p=1===h[0]&&1===h[1],f=function(t,e,n){var r=n.map(function(t){return t[0]}),o=n.map(function(t){return t[1]}),a=t.concat(r,o),i=e.map(function(t,e){return(t-a[e]%t)%t}),s=o.map(function(t,e){return t+i[e]}),u=e.map(function(t,e){return[r[e],s[e]]}),l=e.map(function(t,e){return[0,i[e]]});return[u,l]}([c.inHeight,c.inWidth],h,l),v=f[0],m=f[1],g=p?r:"valid",y=p?s:or(s,h,v),x=("avg"===n?function(){return cl(y,e,a,1,g)}:function(){return ll(y,e,a,1,g)})(),b=p?x:Vn(x,h,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),fl=Je({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=We(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),d(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),d("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),d(Kr(n,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&d(x(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var c=Lr(u.shape,e,n,i,r,o,a),h=St.runKernel(function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n},{x:u},function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=We(t,"dy","maxPool3dBackprop"),l=We(e,"input","maxPool3dBackprop"),c=We(n,"output","maxPool3dBackprop"),h=u,p=l,f=c,v=!1;4===l.rank&&(v=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),p=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),d(5===h.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."}),d(5===p.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+p.rank+"."}),d(5===f.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+f.rank+"."}),null==a&&(a=[1,1,1]),d(Kr(o,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),null!=s&&d(x(i),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var m=Lr(p.shape,r,o,a,i,s),g=St.runKernel(function(t){return t.maxPool3dBackprop(h,p,f,m)},{dy5D:h,input5D:p});return v?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(t,s,u,e,n,i,r,o)}}});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),vl=Je({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=We(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),d(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),d("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),d(Kr(n,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&d(x(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var c=Lr(u.shape,e,n,i,r,o,a),h=St.runKernel(function(t){return t.avgPool3d(u,c)},{x:u},function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=We(t,"dy","avgPool3dBackprop"),u=We(e,"input","avgPool3dBackprop"),l=s,c=u,h=!1;4===u.rank&&(h=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),d(5===l.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."}),d(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==o&&(o=[1,1,1]),d(Kr(r,o),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),null!=i&&d(x(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."});var p=Lr(c.shape,n,r,o,a,i),f=St.runKernel(function(t){return t.avgPool3dBackprop(l,c,p)},{dy5D:l,input5D:c});return h?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}(t,u,e,n,i,r,o)}}});return h=h.cast(u.dtype),l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}});var ml=Je({slice_:function(t,e,n){var r,o,a=We(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length<a.rank?e.concat(new Array(a.rank-e.length).fill(0)):e.slice()).forEach(function(t){d(-1!==t,function(){return"slice() does not support negative begin indexing."})}),o=(o=null==n?new Array(a.rank).fill(-1):"number"==typeof n?[n].concat(new Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(new Array(a.rank-n.length).fill(-1)):n).map(function(t,e){return t>=0?t:(d(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),a.shape[e]-r[e])}),function(t,e,n){d(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),d(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){d(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},o=0;o<t.rank;++o)r(o)}(a,r,o);var i=a.shape;return St.runKernel(function(t){return t.slice(a,r,o)},{$x:a},function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-o[n]]);return{$x:function(){return t.pad(e)}}})}}),gl=Je({slice1d_:function(t,e,n){var r=We(t,"x","slice1d");return d(1===r.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"}),ml(r,[e],[n])}}),yl=Je({slice2d_:function(t,e,n){var r=We(t,"x","slice2d");return d(2===r.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"}),ml(r,e,n)}}),xl=Je({slice3d_:function(t,e,n){var r=We(t,"x","slice3d");return d(3===r.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"}),ml(r,e,n)}}),bl=Je({slice4d_:function(t,e,n){var r=We(t,"x","slice4d");return d(4===r.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"}),ml(r,e,n)}});function wl(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(qe(e.shape,r))),t.rank<n.rank&&(t=t.reshape(qe(t.shape,r))),{$x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}var Cl=Je({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","all","bool"),o=R(e,r.shape),a=o,i=Ke(a,r.rank);null!=i&&(r=r.transpose(i),a=Xe(a.length,r.rank));var s=St.runKernel(function(t){return t.all(r,a)},{$x:r});if(n){var u=qe(s.shape,o);return s.reshape(u)}return s}}),El=Je({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","any","bool"),o=R(e,r.shape),a=o,i=Ke(a,r.rank);null!=i&&(r=r.transpose(i),a=Xe(a.length,r.rank));var s=St.runKernel(function(t){return t.any(r,a)},{$x:r});if(n){var u=qe(s.shape,o);return s.reshape(u)}return s}}),Nl=Je({argMax_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","argMax");null==e&&(e=0);var r=R(e,n.shape),o=Ke(r,n.rank);return null!=o&&(n=n.transpose(o),r=Xe(r.length,n.rank)),St.runKernel(function(t,e){var o=t.argMax(n,r[0]);return e([n]),o},{$x:n},function(t,e){var n=e[0];return{$x:function(){return yn(n)}}})}}),Rl=Je({argMin_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","argMin");null==e&&(e=0);var r=R(e,n.shape),o=Ke(r,n.rank);return null!=o&&(n=n.transpose(o),r=Xe(r.length,n.rank)),St.runKernel(function(t,e){var o=t.argMin(n,r[0]);return e([n]),o},{$x:n},function(t,e){var n=e[0];return{$x:function(){return yn(n)}}})}}),Il=Je({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","logSumExp"),o=R(e,r.shape),a=r.max(o,!0),i=r.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(n){var u=qe(s.shape,o);return s.reshape(u)}return s}}),kl=Je({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","max"),o=r,a=R(e,r.shape),i=a,s=Ke(i,r.rank);null!=s&&(r=r.transpose(s),i=Xe(i.length,r.rank));var u=St.runKernel(function(t,e){var n=t.max(r,i);return e([o,n]),n},{$x:r},function(t,e){return wl(t,e[1],e[0],a,s)});if(n){var l=qe(u.shape,a);u=u.reshape(l)}return u}}),Sl=Je({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","mean"),o=R(e,r.shape),a=g(He(r.shape,o)[1]);return Sr(function(t){var r=on(a);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1}),e.reshape(n).mul(pn(t.shape,"float32")).div(a)}}})(r)}}),Al=Je({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","min"),o=r,a=R(e,r.shape),i=a,s=Ke(i,r.rank);null!=s&&(r=r.transpose(s),i=Xe(i.length,r.rank));var u=St.runKernel(function(t,e){var n=t.min(r,i);return e([o,n]),n},{$x:r},function(t,e){return wl(t,e[1],e[0],a,s)});if(n){var l=qe(u.shape,a);u=u.reshape(l)}return u}}),Tl=Je({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=R(e,(t=We(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=qe(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)}}}),Dl=Je({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=R(e,r.shape);return Sr(function(t){var e=Ke(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=Xe(r.length,t.rank));var i=St.runKernel(function(t){return t.sum(a,r)},{permutedX:a});if(n){var s=qe(i.shape,o);i=i.reshape(s)}return{value:i,gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1}),e.reshape(n).mul(pn(t.shape,"float32"))}}})(r)}}),_l=Je({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=R(e,r.shape),a=Ke(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=Xe(i.length,r.rank));var u=St.runKernel(function(t){return t.prod(s,i)},{permutedX:s});if(n){var l=qe(u.shape,o);u=u.reshape(l)}return u}});var Ol=Je({elu_:function(t){var e=We(t,"x","elu");return St.runKernel(function(t,n){var r=t.elu(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return St.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Fl=Je({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=We(t,"x","leakyRelu");return hu(on(e).mul(n),n)}}),Ml=Je({prelu_:function(t,e){var n=We(t,"x","prelu"),r=We(e,"alpha","prelu");return St.runKernel(function(t,e){var o=t.prelu(n,r);return e([n,r]),o},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{$x:function(){return nu(o,t,t.mul(r))},$alpha:function(){var e=nu(o,yn(t),t.mul(n)),a=Mr(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}})}}),Bl=Je({relu_:function(t){var e=We(t,"x","relu");return"bool"===e.dtype?e.toInt():St.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),Pl=Je({selu_:function(t){var e=We(t,"x","selu");return St.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(on(0)),r=on(Si),o=on(Ai),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return nu(e,a,i)}}})}});var Ll=Je({transpose_:function(t,e){var n=We(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){d(t>=0&&t<n.rank,function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e})}),n.rank<=1?n.clone():St.runKernel(function(t){return t.transpose(n,e)},{$x:n},function(t){var n=je(e);return{$x:function(){return t.transpose(n)}}})}});var Vl=Je({localResponseNormalization_:function(t,e,n,r,o){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===o&&(o=.5);var a=We(t,"x","localResponseNormalization");d(4===a.rank||3===a.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+a.rank+"."}),d(x(e),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."});var i=a,s=!1;3===a.rank&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=St.runKernel(function(t,a){var s=t.localResponseNormalization4D(i,e,n,r,o);return a([i,s]),s},{x4D:i},function(t,a){var i=a[0],s=a[1];return{x4D:function(){return St.runKernel(function(a){return a.LRNGrad(t,i,s,e,n,r,o)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}});var Wl=Je({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(on(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=We(t,"x","norm"),e,n),a=o.shape;if(r){var i=R(n,t.shape);a=qe(o.shape,i)}return o.reshape(a)}});var Ul=Je({basicLSTMCell_:function(t,e,n,r,o,a){var i=We(t,"forgetBias","basicLSTMCell"),s=We(e,"lstmKernel","basicLSTMCell"),u=We(n,"lstmBias","basicLSTMCell"),l=We(r,"data","basicLSTMCell"),c=We(o,"c","basicLSTMCell"),h=We(a,"h","basicLSTMCell"),p=l.concat(h,1).matMul(s).add(u),d=p.shape[0],f=p.shape[1]/4,v=[d,f],m=p.slice([0,0],v),g=p.slice([0,f],v),y=p.slice([0,2*f],v),x=p.slice([0,3*f],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(c.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),zl=Je({multiRNNCell_:function(t,e,n,r){for(var o=We(e,"data","multiRNNCell"),a=Ue(n,"c","multiRNNCell"),i=Ue(r,"h","multiRNNCell"),s=o,u=[],l=0;l<t.length;l++){var c=t[l](s,a[l],i[l]);u.push(c[0]),u.push(c[1]),s=c[1]}var h=[],p=[];for(l=0;l<u.length;l+=2)h.push(u[l]),p.push(u[l+1]);return[h,p]}});var Gl=Je({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=We(t,"v","movingAverage"),i=We(e,"x","movingAverage"),s=We(n,"decay","movingAverage");Ct(a,i),d(y(a.shape,i.shape),function(){return"Shape mismatch in v and x"});var u=on(1),l=u.sub(s),c=i.sub(a).mul(l);if(o){d(null!=r,function(){return"When using zeroDebias: true, step is required."});var h=We(r,"step","movingAverage");c=c.div(u.sub(xu(s,h)))}return a.add(c)}});var Hl=Je({stridedSlice_:function(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==i)throw new Error("ellipsis mask is not yet supported");var l=We(t,"x","stridedSlice"),c=wr(s),h=l.shape.slice();c.forEach(function(t){e[t]=0,n[t]=1,h.splice(t,0,1)}),l=l.reshape(h);for(var p=0;p<l.rank;p++)e[p]=Er(o,e,r,l.shape,p),n[p]=Nr(a,n,r,l.shape,p),r[p]=r[p]||1;var d=wr(u);d.forEach(function(t){n[t]=e[t]+1,r[t]=1});var f=Cr(e,n,r),v=f.filter(function(t,e){return-1===d.indexOf(e)});return r.every(function(t){return 1===t})?ml(l,e,f).reshape(v):St.runKernel(function(t){return t.stridedSlice(l,e,n,r)},{$x:l}).reshape(v)}});var ql=Je({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=We(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var o=r.shape[r.shape.length-1];if(e>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=St.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}});var $l=Je({scatterND_:function(t,e,n){var r=We(t,"indices","scatterND","int32"),o=We(e,"updates","scatterND");return xr(o,r,n),St.runKernel(function(t){return t.scatterND(r,o,n)},{$indices:r,$updates:o})}});var Kl=Je({fft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return St.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),jl=Je({ifft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return St.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),Xl=Je({rfft_:function(t,e){d("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&e<r){var a=t.shape.map(function(t){return 0}),i=t.shape.map(function(t){return t});i[t.shape.length-1]=e,n=t.slice(a,i),r=e}else if(null!=e&&e>r){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(dn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=Ze(n,u).as2D(o,r),c=Kl(l),h=Math.floor(r/2)+1,p=tn(c),f=en(c),v=p.split([h,r-h],p.shape.length-1),m=f.split([h,r-h],f.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=h,Ze(v[0],m[0]).reshape(g)}}),Yl=Je({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=jl(r);return tn(o)}var a=[n,2*(e-1)],i=tn(t).as2D(n,e),s=en(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(on(-1)),c=i.concat(u,1),h=s.concat(l,1);return r=Ze(c,h).as2D(a[0],a[1]),o=jl(r),tn(o)}}),Ql=Object.freeze({fft:Kl,ifft:jl,rfft:Xl,irfft:Yl});var Jl=Je({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=We(t,"sparseIndices","sparseToDense","int32"),a=We(e,"sparseValues","sparseToDense"),i=We(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,n,i),St.runKernel(function(t){return t.sparseToDense(o,a,n,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var Zl=Je({gatherND_:function(t,e){var n=We(e,"indices","gatherND","int32"),r=We(t,"x","gatherND");return St.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});var tc=Je({diag_:function(t){var e=We(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return St.runKernel(function(t){return t.diag(e)},{$x:e}).reshape(n)}});var ec=Je({dropout_:function(t,e,n,r){var o=We(t,"x","dropout");if(d("float32"===o.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),d(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof ct?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(y(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(o,n),i=1-e,s=nr(a,0,1,"float32",r).add(i).floor().div(i);return o.mul(s)}});function nc(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a<t;++a){var i=2*Math.PI*a/(t+r-1);o[a]=e-n*Math.cos(i)}return an(o,"float32")}var rc=Je({hannWindow_:function(t){return nc(t,.5,.5)}}),oc=Je({hammingWindow_:function(t){return nc(t,.54,.46)}}),ac=Je({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var a=0,i=[];a+e<=t.size;)i.push(ml(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=xn([ml(t,a,e-s),fn([s],o)]);i.push(u),a+=n}return 0===i.length?sn([],[0,e]):xn(i).as2D(i.length,e)}}),ic=Je({stft_:function(t,e,n,r,o){var a;void 0===o&&(o=rc),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=ac(t,e,n),s=gu(i,o(e)),u=[],l=0;l<i.shape[0];l++)u.push(Xl(s.slice([l,0],[1,e]),r));return xn(u)}}),sc=Object.freeze({hannWindow:rc,hammingWindow:oc,frame:ac,stft:ic});var uc,lc=function(t,e,n){return void 0===n&&(n=1),r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p,v,m,g,y,x;return o(this,function(o){switch(o.label){case 0:return r=We(t,"predictions","inTopK"),a=We(e,"targets","inTopK"),d(r.rank>1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank}),d(r.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank}),f(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=r.shape[r.shape.length-1],d(n>0&&n<=i,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+n}),[4,r.data()];case 1:return s=o.sent(),[4,a.data()];case 2:for(u=o.sent(),l=[s.length/i,i],h=l[1],p=k("bool",c=l[0]),v=0;v<c;v++){for(m=v*h,g=s.subarray(m,m+h),y=[],x=0;x<g.length;x++)y.push({value:g[x],index:x});for(y.sort(function(t,e){return e.value-t.value}),p[v]=0,x=0;x<n;x++)if(y[x].index===u[v]){p[v]=1;break}}return t!==r&&r.dispose(),e!==a&&a.dispose(),[2,nn(p,a.shape,"bool")]}})})};(uc=t.Reduction||(t.Reduction={}))[uc.NONE=0]="NONE",uc[uc.MEAN=1]="MEAN",uc[uc.SUM=2]="SUM",uc[uc.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";var cc=Je({absoluteDifference_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","absoluteDifference"),i=We(n,"predictions","absoluteDifference"),s=null;null!=r&&(s=We(r,"weights","absoluteDifference")),f(a.shape,i.shape,"Error in absoluteDifference: ");var u=a.sub(i).abs();return hc(u,s,o)}}),hc=Je({computeWeightedLoss_:function(e,n,r){void 0===r&&(r=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"losses","computeWeightedLoss"),a=null;null!=n&&(a=We(n,"weights","computeWeightedLoss"));var i=null==a?o:o.mul(a);if(r===t.Reduction.NONE)return i;if(r===t.Reduction.SUM)return i.sum();if(r===t.Reduction.MEAN){if(null==a)return i.mean();var s=o.size/a.size,u=i.sum().div(a.sum());return s>1?u.div(on(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(on(o.size));var l=a.mul(pn(o.shape)).notEqual(on(0)).sum().toFloat();return i.sum().div(l)}throw Error("Unknown reduction: "+r)}}),pc=Je({cosineDistance_:function(e,n,r,o,a){void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"labels","cosineDistance"),s=We(n,"predictions","cosineDistance"),u=null;null!=o&&(u=We(o,"weights","cosineDistance")),f(i.shape,s.shape,"Error in cosineDistance: ");var l=on(1).sub(i.mul(s).sum(r,!0));return hc(l,u,a)}}),dc=Je({hingeLoss_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","hingeLoss"),i=We(n,"predictions","hingeLoss"),s=null;null!=r&&(s=We(r,"weights","hingeLoss")),f(a.shape,i.shape,"Error in hingeLoss: ");var u=on(1);a=on(2).mul(a).sub(u);var l=u.sub(a.mul(i)).relu();return hc(l,s,o)}}),fc=Je({huberLoss_:function(e,n,r,o,a){void 0===o&&(o=1),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"labels","huberLoss"),s=We(n,"predictions","huberLoss"),u=null;null!=r&&(u=We(r,"weights","huberLoss")),f(i.shape,s.shape,"Error in huberLoss: ");var l=on(o),c=s.sub(i).abs(),h=du(c,l),p=c.sub(h),d=on(.5).mul(h.square()).add(l.mul(p));return hc(d,u,a)}}),vc=Je({logLoss_:function(e,n,r,o,a){void 0===o&&(o=1e-7),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"labels","logLoss"),s=We(n,"predictions","logLoss"),u=null;null!=r&&(u=We(r,"weights","logLoss")),f(i.shape,s.shape,"Error in logLoss: ");var l=on(1),c=on(o),h=i.mul(s.add(c).log()).neg().sub(l.sub(i).mul(l.sub(s).add(c).log()));return hc(h,u,a)}}),mc=Je({meanSquaredError_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","meanSquaredError"),i=We(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=We(r,"weights","meanSquaredError")),f(a.shape,i.shape,"Error in meanSquaredError: ");var u=a.squaredDifference(i);return hc(u,s,o)}}),gc=Je({sigmoidCrossEntropy_:function(e,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"multiClassLabels","sigmoidCrossEntropy"),s=We(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=We(r,"weights","sigmoidCrossEntropy")),f(i.shape,s.shape,"Error in sigmoidCrossEntropy: "),o>0){var l=on(o),c=on(1),h=on(.5);i=i.mul(c.sub(l)).add(h.mul(l))}var p=function(t,e){var n=We(t,"labels","sigmoidCrossEntropyWithLogits"),r=We(e,"logits","sigmoidCrossEntropyWithLogits");f(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(i,s);return hc(p,u,a)}}),yc=Je({softmaxCrossEntropy_:function(e,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"onehotLabels","softmaxCrossEntropy"),s=We(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=We(r,"weights","softmaxCrossEntropy")),f(i.shape,s.shape,"Error in softmaxCrossEntropy: "),o>0){var l=on(o),c=on(1),h=on(i.shape[1]);i=i.mul(c.sub(l)).add(l.div(h))}var p=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Sr(function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=qe(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}})(t,e)}(i,s);return hc(p,u,a)}}),xc=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:cc,computeWeightedLoss:hc,cosineDistance:pc,hingeLoss:dc,huberLoss:fc,logLoss:vc,meanSquaredError:mc,sigmoidCrossEntropy:gc,softmaxCrossEntropy:yc});function bc(t,e){return void 0===e&&(e=!1),St.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],o=qn(n),a=t.clone(),i=sn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=o;e=St.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=sn([[-1]]).where(l.greater(0),sn([[1]])),h=l.sub(c.mul(u)),p=e.div(h);s=1===p.shape[0]?i.clone():i.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var d=c.matMul(h).div(u).neg(),f=a.slice([t,0],[n-t,r]),v=d.mul(s);if(0===t)a=f.sub(v.matMul(s.transpose().matMul(f)));else{var m=f.sub(v.matMul(s.transpose().matMul(f)));a=a.slice([0,0],[t,r]).concat(m,0)}var g=o.slice([0,t],[n,o.shape[1]-t]);if(0===t)o=g.sub(g.matMul(s).matMul(v.transpose()));else{var y=g.sub(g.matMul(s).matMul(v.transpose()));o=o.slice([0,0],[n,t]).concat(y,1)}return[s,a,o]}),s=e[0],a=e[1],o=e[2],Me([u,l,c])},c=0;c<u;++c)l(c);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]})}var wc=Je({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,d(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){d(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},o=1;o<t.length;++o)r(o)}else e=!0,t=Nn(t,t.shape[0],0).map(function(t){return ar(t,[0])});d(t.length<=t[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."});var a=[],i=t,s=function(t){a.push(St.tidy(function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=Dl(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(Wl(e,"euclidean"))}))};for(o=0;o<t.length;++o)s(o);return e?ir(a,0):a}}),Cc=Je({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return bc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=lr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach(function(t){var n=bc(t,e),r=n[0],i=n[1];o.push(r),a.push(i)}),[ir(o,0).reshape(t.shape),ir(a,0).reshape(t.shape)]}}),Ec=Object.freeze({gramSchmidt:wc,qr:Cc});function Nc(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),d(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),d(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),d(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),d(1===e.rank,function(){return"scores must be a 1D tensor"}),d(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}var Rc=Je({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeBilinear");d(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=St.runKernel(function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return St.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ic=Je({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),d("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=St.runKernel(function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return St.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),kc=Je({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=We(t,"boxes","nonMaxSuppression"),i=We(e,"scores","nonMaxSuppression"),s=Nc(a,i,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,St.runKernel(function(t){return t.nonMaxSuppression(a,i,n,r,o)},{$boxes:a})}}),Sc=function(t,e,n,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return r=We(t,"boxes","nonMaxSuppressionAsync"),s=We(e,"scores","nonMaxSuppressionAsync"),u=Nc(r,s,n,a,i),n=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,Promise.all([r.data(),s.data()])];case 1:return l=o.sent(),c=l[0],h=l[1],p=ro(c,h,n,a,i),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,p]}})})},Ac=Je({cropAndResize_:function(t,e,n,r,o,a){var i=We(t,"image","cropAndResize","float32"),s=We(e,"boxes","cropAndResize","float32"),u=We(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var l=s.shape[0];return d(4===i.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),d(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),d(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),d(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),d(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),d("bilinear"===o||"nearest"===o,function(){return"method must be bilinear or nearest, but was "+o}),St.runKernel(function(t,e){return t.cropAndResize(i,s,u,r,o,a)},{$image:i,$boxes:s})}}),Tc=Object.freeze({resizeBilinear:Rc,resizeNearestNeighbor:Ic,nonMaxSuppression:kc,nonMaxSuppressionAsync:Sc,cropAndResize:Ac});var Dc=Je({matMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,a=void 0!==o&&o,i=t.transposeB,s=void 0!==i&&i,u=t.bias,l=t.activation,c=void 0===l?"linear":l,h=t.preluActivationWeights,p=We(n,"a","fused matMul"),f=We(r,"b","fused matMul");e=wt(p,f),p=e[0],f=e[1];var v=a?p.shape[p.rank-2]:p.shape[p.rank-1],m=s?f.shape[f.rank-1]:f.shape[f.rank-2],x=a?p.shape[p.rank-1]:p.shape[p.rank-2],b=s?f.shape[f.rank-2]:f.shape[f.rank-1],w=p.shape.slice(0,-2),C=f.shape.slice(0,-2),E=g(w),N=g(C);d(p.rank>=2&&f.rank>=2&&p.rank===f.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+p.rank+" and "+f.rank+"."}),d(y(w,C),function(){return"Error in fused matMul: outer dimensions ("+w+") and ("+C+") of Tensors with shapes "+p.shape+" and "+f.shape+" must match."}),d(v===m,function(){return"Error in fused matMul: inner shapes ("+v+") and ("+m+") of Tensors with shapes "+p.shape+" and "+f.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var R,I,k=p.shape.slice(0,-2).concat([x,b]),S=a?p.as3D(E,v,x):p.as3D(E,x,v),A=s?f.as3D(N,b,m):f.as3D(N,m,b);null!=u&&Br(k,(R=wt(R=We(u,"bias","fused matMul"),p)[0]).shape),null!=h&&(I=We(h,"prelu weights","fused matMul"));var T={$a:S,$b:A};return null!=u&&(T.$bias=R),null!=h&&(T.$preluActivationWeights=I),St.runKernel(function(t,e){var n=t.fusedBatchMatMul({a:S,b:A,transposeA:a,transposeB:s,bias:R,activation:c,preluActivationWeights:I});return e([S,A,n]),n},T,function(t,e){var n,r=e[0],o=e[1],i=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(i.step())}var l={};return null!=u&&(l={$bias:function(){var t=n,e=Mr(R.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(R.shape)}}),a||s?!a&&s?Object.assign({$a:function(){return n.matMul(o,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}},l):a&&!s?Object.assign({$a:function(){return o.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}},l):Object.assign({$a:function(){return o.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}},l):Object.assign({$a:function(){return n.matMul(o,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}},l)}).reshape(k)}}),_c=Je({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,h=t.activation,p=void 0===h?"linear":h,f=t.preluActivationWeights,v=We(e,"x","conv2d"),m=We(n,"filter","conv2d"),g=v,y=!1;3===v.rank&&(y=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),d(4===g.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."}),d(4===m.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."}),null!=l&&d(x(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+o+"."}),d(g.shape[3]===m.shape[2],function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+m.shape[2]+"."}),d(Kr(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),d("NHWC"===i,function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var b,w,C=Vr(g.shape,m.shape,r,u,o,l);null!=c&&(b=wt(b=We(c,"bias","fused conv2d"),v)[0],Br(C.outShape,b.shape)),null!=f&&(w=We(f,"prelu weights","fused conv2d"));var E={x:g,$filter:m};null!=c&&(E.$bias=b),null!=f&&(E.$preluActivationWeights=w);var N=St.runKernel(function(t,e){var n=t.fusedConv2d(g,m,C,b,p,w);return e([m,g,n]),n},E,function(t,e){var n,a=e,i=a[0],s=a[1],l=a[2];if(null==p||"linear"===p)n=t;else{if("relu"!==p)throw new Error("Gradient for activation "+p+" has not been implemented yet.");n=t.mul(l.step())}d($r(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var h={};return null!=c&&(h={$bias:function(){var t=n,e=Mr(b.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(b.shape)}}),Object.assign({x:function(){return Yu(s.shape,n,i,r,o)},$filter:function(){return Xu(s,n,i.shape,r,o)}},h)});return y?N.as3D(N.shape[1],N.shape[2],N.shape[3]):N}}),Oc=Object.freeze({matMul:Dc,conv2d:_c}),Fc=Object.freeze({image:Tc,linalg:Ec,losses:xc,spectral:Ql,fused:Oc,signal:sc,op:Je,batchNormalization2d:Hs,batchNormalization3d:qs,batchNormalization4d:$s,batchNormalization:Ks,batchNorm:js,batchNorm2d:Xs,batchNorm3d:Ys,batchNorm4d:Qs,booleanMaskAsync:Uu,complex:Ze,real:tn,imag:en,concat:xn,concat1d:bn,concat2d:wn,concat3d:Cn,concat4d:En,split:Nn,conv1d:$u,conv2d:Ku,conv3d:ju,conv2dDerFilter:Xu,conv2dDerInput:Yu,depthwiseConv2d:Qu,separableConv2d:Ju,conv2dTranspose:Zu,conv3dTranspose:tl,matMul:el,dot:nl,outerProduct:rl,reverse:ol,reverse1d:al,reverse2d:il,reverse3d:sl,reverse4d:ul,maxPool:hl,avgPool:pl,pool:dl,maxPool3d:fl,avgPool3d:vl,slice:ml,slice1d:gl,slice2d:yl,slice3d:xl,slice4d:bl,abs:rs,acos:os,acosh:as,asin:is,asinh:ss,atan:us,atanh:ls,ceil:cs,clipByValue:hs,cos:ps,cosh:ds,erf:fs,exp:vs,expm1:ms,floor:gs,log:ys,log1p:xs,logSigmoid:bs,neg:ws,reciprocal:Cs,round:Es,rsqrt:Ns,sigmoid:Rs,sign:Is,isNaN:ks,isInf:Ss,isFinite:As,sin:Ts,sinh:Ds,softplus:_s,sqrt:Os,square:Fs,step:Ms,tan:Bs,tanh:Ps,all:Cl,any:El,argMax:Nl,argMin:Rl,logSumExp:Il,max:kl,mean:Sl,min:Al,moments:Tl,sum:Dl,prod:_l,equal:Ru,equalStrict:Iu,greater:ku,greaterEqual:Su,greaterEqualStrict:Au,greaterStrict:Tu,less:Du,lessEqual:_u,lessEqualStrict:Ou,lessStrict:Fu,notEqual:Mu,notEqualStrict:Bu,add:ou,addN:au,addStrict:iu,atan2:su,div:uu,divStrict:lu,floorDiv:cu,maximum:hu,maximumStrict:pu,minimum:du,minimumStrict:fu,mod:vu,modStrict:mu,mul:gu,mulStrict:yu,pow:xu,powStrict:bu,squaredDifference:wu,squaredDifferenceStrict:Cu,sub:Eu,subStrict:Nu,elu:Ol,leakyRelu:Fl,prelu:Ml,relu:Bl,selu:Pl,logicalAnd:Js,logicalNot:Zs,logicalOr:tu,logicalXor:eu,where:nu,whereAsync:ru,buffer:Pn,print:Ln,batchToSpaceND:Vn,cast:Wn,clone:Un,cumsum:zn,depthToSpace:Gn,expandDims:Hn,eye:qn,multinomial:$n,oneHot:Kn,pad:jn,pad1d:Xn,pad2d:Yn,pad3d:Qn,pad4d:Jn,rand:Zn,randomNormal:tr,randomGamma:er,randomUniform:nr,reshape:rr,spaceToBatchND:or,squeeze:ar,stack:ir,tile:sr,truncatedNormal:ur,unstack:lr,setdiff1dAsync:cr,fill:fn,linspace:vn,ones:pn,range:mn,scalar:on,tensor:nn,tensor1d:an,tensor2d:sn,tensor3d:un,tensor4d:ln,tensor5d:cn,tensor6d:hn,zeros:dn,onesLike:gn,zerosLike:yn,transpose:Ll,softmax:Tr,logSoftmax:Dr,localResponseNormalization:Vl,norm:Wl,gather:Vu,unsortedSegmentSum:Wu,basicLSTMCell:Ul,multiRNNCell:zl,movingAverage:Gl,stridedSlice:Hl,topk:ql,scatterND:$l,fft:Kl,ifft:jl,rfft:Xl,irfft:Yl,sparseToDense:Jl,gatherND:Zl,diag:tc,dropout:ec,hannWindow:rc,hammingWindow:oc,frame:ac,stft:ic,inTopKAsync:lc});function Mc(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var Bc=function(){function e(){if(this.blockSize=48,this.firstUse=!0,t.ENV.get("IS_BROWSER")){var e="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==e&&(this.fromPixels2DContext=e.getContext("2d"))}this.data=new _r(this,St)}return e.prototype.register=function(e,n,r){if(this.firstUse&&(this.firstUse=!1,t.ENV.get("IS_NODE")&&Pe("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:r})},e.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},e.prototype.fromPixels=function(e,n){if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var r,o,a=e.data instanceof Uint8Array,i="undefined"!=typeof ImageData&&e instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,l=s?[e.videoWidth,e.videoHeight]:[e.width,e.height],c=l[0],h=l[1];if(t.ENV.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)r=e.getContext("2d").getImageData(0,0,c,h).data;else if(i||a)r=e.data;else{if(!u&&!s)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=c,this.fromPixels2DContext.canvas.height=h,this.fromPixels2DContext.drawImage(e,0,0,c,h),r=this.fromPixels2DContext.getImageData(0,0,c,h).data}if(4===n)o=new Int32Array(r);else{var p=c*h;o=new Int32Array(p*n);for(var d=0;d<p;d++)for(var f=0;f<n;++f)o[d*n+f]=r[4*d+f]}return un(o,[h,c,n],"int32")},e.prototype.read=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){return[2,this.readSync(t)]})})},e.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Zr(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},e.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map(function(t){return X(t)})}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return Pn(t.shape,t.dtype,n)},e.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},e.prototype.time=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return e=$(),t(),[2,{kernelMs:$()-e}]})})},e.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},e.prototype.complex=function(t,e){var n=ct.make(t.shape,{},"complex64");return this.data.get(n.dataId).complexTensors={real:St.keep(t.clone()),imag:St.keep(e.clone())},n},e.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},e.prototype.assertNotComplex=function(t,e){Array.isArray(t)||(t=[t]),t.forEach(function(t){null!=t&&d("complex64"!==t.dtype,function(){return e+" does not support complex64 tensors."})})},e.prototype.slice=function(t,e,n){if(this.assertNotComplex(t,"slice"),Rr(t.shape,e,n)){var r=Ir(e,t.strides),o=g(n);return nn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var a=Pn(n,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s).map(function(t,n){return t+e[n]});a.values[s]=i.get.apply(i,u)}return a.toTensor()},e.prototype.stridedSlice=function(t,e,n,r){this.assertNotComplex(t,"stridedSlice");var o=Cr(e,n,r);if(o.some(function(t){return 0===t}))return nn([],o);for(var a=Pn(o,t.dtype),i=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),l=new Array(u.length),c=0;c<l.length;c++)l[c]=u[c]*r[c]+e[c];a.set.apply(a,[i.get.apply(i,l)].concat(u))}return a.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=Pn([t.size,t.size],t.dtype),r=n.values,o=0;o<e.length;o++)r[o*t.size+o]=e[o];return n.toTensor()},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},e.prototype.reverse=function(t,e){this.assertNotComplex(t,"reverse");for(var n=Pn(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var a=n.indexToLoc(o),i=a.slice();e.forEach(function(e){return i[e]=t.shape[e]-1-i[e]}),n.set.apply(n,[r.get.apply(r,i)].concat(a))},a=0;a<n.size;a++)o(a);return n.toTensor()},e.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map(function(t){return tn(t)}),o=t.map(function(t){return en(t)});return Ze(this.concat(r,e),this.concat(o,e))}var a=t.map(function(t){var n=g(t.shape.slice(e));return t.as2D(-1,n)}),i=Qe(a.map(function(t){return t.shape}),1),s=Pn(i,t[0].dtype).values;if(1===a[0].shape[0]){var u=0;a.forEach(function(t){s.set(n.readSync(t.dataId),u),u+=t.size})}else{var l=0;a.forEach(function(t){for(var e=n.readSync(t.dataId),r=0,o=0;o<t.shape[0];++o)for(var a=o*i[1]+l,u=0;u<t.shape[1];++u)s[a+u]=e[r++];l+=t.shape[1]})}var c=Qe(t.map(function(t){return t.shape}),e);return nn(s,c,t[0].dtype)},e.prototype.neg=function(t){return this.assertNotComplex(t,"neg"),this.multiply(on(-1),t)},e.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t+n,imag:e+r}}):this.broadcastedBinaryOp(t,e,xt(t.dtype,e.dtype),function(t,e){return t+e})},e.prototype.addN=function(t){var e=this;this.assertNotComplex(t,"addN");for(var n=t.map(function(t){return e.readSync(t.dataId)}),r=Pn(t[0].shape,t[0].dtype),o=r.values,a=0;a<t.length;a++)for(var i=n[a],s=0;s<o.length;s++)o[s]+=i[s];return r.toTensor()},e.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t-n,imag:e-r}}):this.broadcastedBinaryOp(t,e,xt(t.dtype,e.dtype),function(t,e){return t-e})},e.prototype.pow=function(t,e){return this.assertNotComplex([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.pow(t,e)})},e.prototype.batchMatMul=function(t,e,n,r){this.assertNotComplex([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],h=c[0],p=c[1],d=c[2],f=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=f[0],m=f[1],g=f[2],y=a*i,x=Pn([s,a,i],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<a;E+=w)for(var N=0;N<i;N+=w)for(var R=0;R<o;R+=w)for(var I=Math.min(E+w,a),k=Math.min(N+w,i),S=Math.min(R+w,o),A=E;A<I;A++)for(var T=N;T<k;T++){for(var D=0,_=R;_<S;_++)D+=u[C*h+A*p+_*d]*l[_*v+T*m+C*g];b[C*y+(A*i+T)]+=D}return x.toTensor()},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,o);return a&&(u=this.add(u,a)),i&&(u=Mc(this,u,i,s)),u},e.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}}):this.broadcastedBinaryOp(t,e,xt(t.dtype,e.dtype),function(t,e){return t*e})},e.prototype.realDivide=function(t,e){this.assertNotComplex([t,e],"realDivide");return this.broadcastedBinaryOp(t,e,"float32",function(t,e){return t/e})},e.prototype.floorDiv=function(t,e){this.assertNotComplex([t,e],"floorDiv");return this.broadcastedBinaryOp(t,e,"int32",function(t,e){return Math.floor(t/e)})},e.prototype.sum=function(t,e){this.assertNotComplex(t,"sum"),$e("sum",e,t.rank);for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,xt(t.dtype,"int32")),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=0,p=0;p<i;++p)h+=u[c+p];s[l]=h}return a},e.prototype.prod=function(t,e){this.assertNotComplex(t,"sum");for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,xt(t.dtype,"int32")),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=1,p=0;p<i;++p)h*=u[c+p];s[l]=h}return a},e.prototype.unsortedSegmentSum=function(t,e,n){this.assertNotComplex(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,a=0;a<o;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var i=on(a,"int32"),s=Ru(i,e).asType("float32").mul(t).sum(0);r.push(s)}return ir(r)},e.prototype.argMin=function(t,e){this.assertNotComplex(t,"argMin");var n=[e];$e("argMin",n,t.rank);for(var r=He(t.shape,n),o=r[0],a=r[1],i=dn(o,"int32"),s=g(a),u=this.readSync(i.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var h=c*s,p=l[h],d=0,f=0;f<s;++f){var v=l[h+f];v<p&&(p=v,d=f)}u[c]=d}return i},e.prototype.argMax=function(t,e){this.assertNotComplex(t,"argMax");var n=[e];$e("argMax",n,t.rank);for(var r=He(t.shape,n),o=r[0],a=r[1],i=dn(o,"int32"),s=g(a),u=this.readSync(i.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var h=c*s,p=l[h],d=0,f=0;f<s;++f){var v=l[h+f];v>p&&(p=v,d=f)}u[c]=d}return i},e.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var o=xt(t.dtype,"int32"),a=dn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;c<s.length;c+=u)for(var h=0;h<u;h++){var p=l(c,h);if(0===h)i[p]=n?0:s[p];else{var d=l(c,h-1);i[p]=n?s[d]+i[d]:s[p]+i[d]}}return a},e.prototype.equal=function(t,e){return this.assertNotComplex([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t===e?1:0})},e.prototype.notEqual=function(t,e){return this.assertNotComplex([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t!==e?1:0})},e.prototype.less=function(t,e){return this.assertNotComplex([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<e?1:0})},e.prototype.lessEqual=function(t,e){return this.assertNotComplex([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<=e?1:0})},e.prototype.greater=function(t,e){return this.assertNotComplex([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>e?1:0})},e.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},e.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return ct.make(t.shape,{values:n},"bool")},e.prototype.logicalAnd=function(t,e){return this.assertNotComplex([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t&&e})},e.prototype.logicalOr=function(t,e){return this.assertNotComplex([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t||e})},e.prototype.select=function(t,e,n){this.assertNotComplex([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=dn(e.shape,xt(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,l=0===t.rank||t.rank>1||1===e.rank?1:e.shape[1],c=0;c<r.length;c++)for(var h=0;h<l;h++)1===r[c]?s[u++]=o[c]:s[u++]=a[c];return i},e.prototype.where=function(t){this.assertNotComplex([t],"where");var e=this.readSync(t.dataId);return uo(t.shape,e)},e.prototype.topk=function(t,e,n){return this.assertNotComplex(t,"topk"),so(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){this.assertNotComplex(t,"min"),$e("min",e,t.rank);for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,t.dtype),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var d=u[c+p];d<h&&(h=d)}s[l]=h}return a},e.prototype.minimum=function(t,e){return this.assertNotComplex([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.min(t,e)})},e.prototype.mod=function(t,e){return this.assertNotComplex([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e})},e.prototype.max=function(t,e){this.assertNotComplex(t,"max"),$e("max",e,t.rank);for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,t.dtype),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var d=u[c+p];d>h&&(h=d)}s[l]=h}return a},e.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},e.prototype.all=function(t,e){this.assertNotComplex(t,"all"),$e("all",e,t.rank);for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,t.dtype),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var d=u[c+p];h=h&&d}s[l]=h}return a},e.prototype.any=function(t,e){this.assertNotComplex(t,"any"),$e("any",e,t.rank);for(var n=He(t.shape,e),r=n[0],o=n[1],a=dn(r,t.dtype),i=g(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var d=u[c+p];h=h||d}s[l]=h}return a},e.prototype.squaredDifference=function(t,e){return this.assertNotComplex([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t-e;return n*n})},e.prototype.ceil=function(t){this.assertNotComplex(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return ct.make(t.shape,{values:n})},e.prototype.floor=function(t){this.assertNotComplex(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return ct.make(t.shape,{values:n})},e.prototype.sign=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return ct.make(t.shape,{values:n})},e.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return ct.make(t.shape,{values:n},"bool")},e.prototype.isInf=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return ct.make(t.shape,{values:n},"bool")},e.prototype.isFinite=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return ct.make(t.shape,{values:n},"bool")},e.prototype.round=function(t){this.assertNotComplex(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=Math.floor(e[r]);e[r]-o<.5?n[r]=Math.floor(e[r]):e[r]-o>.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1}return ct.make(t.shape,{values:n})},e.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return ct.make(t.shape,{values:n})},e.prototype.expm1=function(t){this.assertNotComplex(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return ct.make(t.shape,{values:n})},e.prototype.log=function(t){this.assertNotComplex(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log(o)}return ct.make(t.shape,{values:n})},e.prototype.log1p=function(t){this.assertNotComplex(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log1p(o)}return ct.make(t.shape,{values:n})},e.prototype.sqrt=function(t){this.assertNotComplex(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.sqrt(o)}return ct.make(t.shape,{values:n})},e.prototype.rsqrt=function(t){this.assertNotComplex(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=1/Math.sqrt(o)}return ct.make(t.shape,{values:n})},e.prototype.square=function(t){this.assertNotComplex(t,"square");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=o*o}return ct.make(t.shape,{values:n})},e.prototype.reciprocal=function(t){this.assertNotComplex(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return ct.make(t.shape,{values:n})},e.prototype.linear=function(t){return t},e.prototype.relu=function(t){this.assertNotComplex(t,"relu");for(var e=dn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.max(0,r[o]);return e},e.prototype.prelu=function(t,e){return this.assertNotComplex([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return t<0?e*t:t})},e.prototype.elu=function(t){this.assertNotComplex(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r];e[r]=o>=0?o:Math.exp(o)-1}return ct.make(t.shape,{values:e})},e.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];n[a]=i>=1?o[a]:o[a]*(i+1)}return ct.make(e.shape,{values:n})},e.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=Si,n=Ai,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>=0?n*i:e*(Math.exp(i)-1)}return ct.make(t.shape,{values:r})},e.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>n?n:i<e?e:i}return ct.make(t.shape,{values:r})},e.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return ct.make(t.shape,{values:e})},e.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var o=n[2*r],a=n[2*r+1];e[r]=Math.hypot(o,a)}return ct.make(t.shape,{values:e})},e.prototype.int=function(t){this.assertNotComplex(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return ct.make(t.shape,{values:e},"int32")},e.prototype.sigmoid=function(t){this.assertNotComplex(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return ct.make(t.shape,{values:e})},e.prototype.softplus=function(t){this.assertNotComplex(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o]>-e,i=r[o]<e,s=Math.exp(r[o]),u=void 0;u=i?s:a?r[o]:Math.log(1+s),n[o]=u}return ct.make(t.shape,{values:n})},e.prototype.sin=function(t){this.assertNotComplex(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return ct.make(t.shape,{values:e})},e.prototype.cos=function(t){this.assertNotComplex(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return ct.make(t.shape,{values:e})},e.prototype.tan=function(t){this.assertNotComplex(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return ct.make(t.shape,{values:e})},e.prototype.asin=function(t){this.assertNotComplex(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return ct.make(t.shape,{values:e})},e.prototype.acos=function(t){this.assertNotComplex(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return ct.make(t.shape,{values:e})},e.prototype.atan=function(t){this.assertNotComplex(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return ct.make(t.shape,{values:e})},e.prototype.atan2=function(t,e){return this.assertNotComplex([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.atan2(t,e)})},e.prototype.sinh=function(t){this.assertNotComplex(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return ct.make(t.shape,{values:e})},e.prototype.cosh=function(t){this.assertNotComplex(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return ct.make(t.shape,{values:e})},e.prototype.tanh=function(t){this.assertNotComplex(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=b(n[r]);return ct.make(t.shape,{values:e})},e.prototype.asinh=function(t){this.assertNotComplex(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return ct.make(t.shape,{values:e})},e.prototype.acosh=function(t){this.assertNotComplex(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return ct.make(t.shape,{values:e})},e.prototype.atanh=function(t){this.assertNotComplex(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return ct.make(t.shape,{values:e})},e.prototype.erf=function(t){this.assertNotComplex(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r],a=1/(1+.3275911*o);e[r]=1-((((1.061405429*a-1.453152027)*a+1.421413741)*a-.284496736)*a+.254829592)*a*Math.exp(-o*o)}return ct.make(t.shape,{values:e})},e.prototype.step=function(t,e){void 0===e&&(e=0),this.assertNotComplex(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o];isNaN(a)?n[o]=NaN:n[o]=a>0?1:e}return ct.make(t.shape,{values:n})},e.prototype.fusedConv2d=function(t,e,n,r,o,a){var i=this.conv2d(t,e,n);return r&&(i=this.add(i,r)),o&&(i=Mc(this,i,o,a)),i},e.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Pn(n.outShape,t.dtype),h=t.strides[0],p=l?t.strides[1]:t.strides[2],d=l?t.strides[2]:1,f=l?1:t.strides[1],v=c.strides[0],m=l?c.strides[1]:c.strides[2],g=l?c.strides[2]:1,y=l?1:c.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=c.values,C=0;C<n.batchSize;++C)for(var E=C*h,N=C*v,R=0;R<n.outHeight;++R)for(var I=N+R*m,k=R*n.strideHeight-u,S=0;S<r;S++){var A=k+S*a;if(!(A<0||A>=n.inHeight))for(var T=S*e.strides[0],D=E+A*p,_=0;_<n.outWidth;++_)for(var O=I+_*g,F=_*n.strideWidth-s,M=0;M<o;M++){var B=F+M*i;if(!(B<0||B>=n.inWidth))for(var P=D+B*d,L=T+M*e.strides[1],V=0;V<n.inChannels;++V){for(var W=x[P+V*f],U=0;U<n.outChannels;++U)w[O+U*y]+=W*b[L+U];L+=n.outChannels}}}return c.toTensor()},e.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,a=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,l=n.padInfo.front,c=n.padInfo.left,h=n.padInfo.top,p=Pn(n.outShape,t.dtype),d=this.readSync(t.dataId),f=this.readSync(e.dataId),v=p.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],y=m*p.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*p.strides[1],w=x*n.strideDepth-l,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var N=C*e.strides[0],R=g+E*t.strides[1],I=0;I<n.outHeight;++I)for(var k=b+I*p.strides[2],S=I*n.strideHeight-h,A=0;A<o;A++){var T=S+A*s;if(!(T<0||T>=n.inHeight))for(var D=N+A*e.strides[1],_=R+T*t.strides[2],O=0;O<n.outWidth;++O)for(var F=k+O*n.outChannels,M=O*n.strideWidth-c,B=0;B<a;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=D+B*e.strides[2],V=_+P*n.inChannels,W=L,U=0;U<n.inChannels;++U){for(var z=d[V+U],G=0;G<n.outChannels;++G)v[F+G]+=z*f[W+G];W+=n.outChannels}}}}return p.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerInput");for(var r=Pn(n.inShape,"float32"),o=r.values,a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],l=s[1],c=s[2],h=n.batchSize,p=n.filterHeight,d=n.filterWidth,f=n.inChannels,v=n.inHeight,m=n.inWidth,g=n.outChannels,y=n.outHeight,x=n.outWidth,b=n.strideHeight,w=n.strideWidth,C=n.dataFormat,E=p-1-n.padInfo.top,N=d-1-n.padInfo.left,R="channelsLast"===C,I=r.strides[0],k=R?r.strides[1]:r.strides[2],S=R?r.strides[2]:1,A=R?1:r.strides[1],T=t.strides[0],D=R?t.strides[1]:t.strides[2],_=R?t.strides[2]:1,O=R?1:t.strides[1],F=0;F<h;++F)for(var M=0;M<f;++M)for(var B=0;B<v;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),V=Math.min(y,(p+P)/b),W=0;W<m;++W){for(var U=W-N,z=Math.max(0,Math.ceil(U/w)),G=Math.min(x,(d+U)/w),H=0,q=L;q<V;++q)for(var $=q*b-P,K=z;K<G;++K)for(var j=T*F+D*q+_*K,X=u*(p-1-$)+l*(d-1-(K*w-U))+c*M,Y=0;Y<g;++Y){H+=a[j+O*Y]*i[X+Y]}o[I*F+k*B+S*W+A*M]=H}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=Pn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],l=a[3],c=this.readSync(t.dataId),h=t.strides,p=h[0],d=h[1],f=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,N=n.filterHeight,R=n.filterWidth,I=n.inChannels,k=n.inDepth,S=n.inHeight,A=n.inWidth,T=n.outChannels,D=n.outDepth,_=n.outHeight,O=n.outWidth,F=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=N-1-n.padInfo.top,V=R-1-n.padInfo.left,W=0;W<C;++W)for(var U=0;U<I;++U)for(var z=0;z<k;++z)for(var G=z-P,H=Math.max(0,Math.ceil(G/F)),q=Math.min(D,(E+G)/F),$=0;$<S;++$)for(var K=$-L,j=Math.max(0,Math.ceil(K/M)),X=Math.min(_,(N+K)/M),Y=0;Y<A;++Y){for(var Q=Y-V,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(O,(R+Q)/B),tt=0,et=H;et<q;++et)for(var nt=et*F-G,rt=j;rt<X;++rt)for(var ot=rt*M-K,at=J;at<Z;++at)for(var it=p*W+d*et+f*rt+v*at,st=y*(E-1-nt)+x*(N-1-ot)+b*(R-1-(at*B-Q))+w*U,ut=0;ut<T;++ut){tt+=c[it+ut]*m[st+ut]}o[i*W+s*z+u*$+l*Y+U]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=Pn(n.filterShape,"float32"),l=n.padInfo.left,c=n.padInfo.top,h=this.bufferSync(t),p=this.bufferSync(e),d=0;d<a;++d)for(var f=Math.max(0,Math.ceil((c-d)/r)),v=Math.min(n.outHeight,(n.inHeight+c-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((l-m)/o)),y=Math.min(n.outWidth,(n.inWidth+l-m)/o),x=0;x<n.inChannels;++x)for(var b=0;b<n.outChannels;++b){for(var w=0,C=0;C<n.batchSize;++C)for(var E=f;E<v;++E)for(var N=d+E*r-c,R=g;R<y;++R){var I=m+R*o-l;w+=s?h.get(C,N,I,x)*p.get(C,E,R,b):h.get(C,x,N,I)*p.get(C,b,E,R)}u.set(w,d,m,x,b)}return u.toTensor()},e.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=Pn(n.filterShape,"float32"),c=l.values,h=l.strides,p=h[0],d=h[1],f=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=this.readSync(t.dataId),E=t.strides,N=E[0],R=E[1],I=E[2],k=E[3],S=n.padInfo.front,A=n.padInfo.left,T=n.padInfo.top,D=0;D<i;++D)for(var _=Math.max(0,Math.ceil((S-D)/r)),O=Math.min(n.outDepth,(n.inDepth+S-D)/r),F=D*p,M=0;M<s;++M)for(var B=Math.max(0,Math.ceil((T-M)/o)),P=Math.min(n.outHeight,(n.inHeight+T-M)/o),L=M*d+F,V=0;V<u;++V)for(var W=Math.max(0,Math.ceil((A-V)/a)),U=Math.min(n.outWidth,(n.inWidth+A-V)/a),z=V*f+L,G=0;G<n.inChannels;++G)for(var H=G*v+z,q=0;q<n.outChannels;++q){for(var $=0,K=0;K<n.batchSize;++K)for(var j=K*N,X=K*y,Y=_;Y<O;++Y)for(var Q=(D+Y*r-S)*R+j,J=Y*x+X,Z=B;Z<P;++Z)for(var tt=(M+Z*o-T)*I+Q,et=Z*b+J,nt=W;nt<U;++nt){var rt=nt*w+et;$+=C[(V+nt*a-A)*k+tt+G]*m[rt+q]}c[H+q]=$}return l.toTensor()},e.prototype.depthwiseConv2D=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=n.outChannels/n.inChannels,c=Pn(n.outShape,t.dtype),h=this.readSync(t.dataId),p=this.readSync(e.dataId),d=c.values,f=0;f<n.batchSize;++f)for(var v=f*t.strides[0],m=f*c.strides[0],g=0;g<n.outHeight;++g)for(var y=m+g*c.strides[1],x=g*n.strideHeight-s,b=0;b<r;++b){var w=x+b*a;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],N=0;N<n.outWidth;++N)for(var R=y+N*c.strides[2],I=N*n.strideWidth-u,k=0;k<o;++k){var S=I+k*i;if(!(S<0||S>=n.inWidth))for(var A=C+k*e.strides[1],T=E+S*n.inChannels,D=R,_=A,O=0;O<n.inChannels;++O){for(var F=h[T+O],M=0;M<l;++M)d[D+M]+=F*p[_+M];D+=l,_+=l}}}return c.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerInput");for(var r=Pn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],l=this.readSync(t.dataId),c=t.strides,h=c[0],p=c[1],d=c[2],f=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,N=n.inWidth,R=n.outChannels,I=n.outHeight,k=n.outWidth,S=n.strideHeight,A=n.strideWidth,T=b-1-n.padInfo.top,D=w-1-n.padInfo.left,_=R/C,O=0;O<x;++O)for(var F=0;F<C;++F)for(var M=0;M<E;++M)for(var B=M-T,P=Math.max(0,Math.ceil(B/S)),L=Math.min(I,(b+B)/S),V=0;V<N;++V){for(var W=V-D,U=Math.max(0,Math.ceil(W/A)),z=Math.min(k,(w+W)/A),G=0,H=P;H<L;++H)for(var q=H*S-B,$=U;$<z;++$)for(var K=h*O+p*H+d*$,j=m*(b-1-q)+g*(w-1-($*A-W))+y*F,X=0;X<_;++X){G+=l[K+(F*_+X)]*f[j+X]}o[i*O+s*M+u*V+F]=G}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=Pn(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=n.outChannels/n.inChannels,h=this.bufferSync(t),p=this.bufferSync(e),d=0;d<a;++d)for(var f=Math.max(0,Math.ceil((l-d)/r)),v=Math.min(n.outHeight,(n.inHeight+l-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((u-m)/o)),y=Math.min(n.outWidth,(n.inWidth+u-m)/o),x=0;x<n.outChannels;++x){for(var b=Math.trunc(x/c),w=x%c,C=0,E=0;E<n.batchSize;++E)for(var N=f;N<v;++N)for(var R=d+N*r-l,I=g;I<y;++I){var k=m+I*o-u;C+=h.get(E,R,k,b)*p.get(E,N,I,x)}s.set(C,d,m,b,w)}return s.toTensor()},e.prototype.tile=function(t,e){return this.assertNotComplex(t,"tile"),io(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){this.assertNotComplex(t,"pad");var r=e.map(function(e,n){return e[0]+t.shape[n]+e[1]}),o=e.map(function(t){return t[0]}),a=this.bufferSync(t),i=Pn(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),l=u.map(function(t,e){return t+o[e]});i.set.apply(i,[a.get.apply(a,u)].concat(l))}return i.toTensor()},e.prototype.transpose=function(t,e){this.assertNotComplex(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var o=this.readSync(t.dataId),a=Pn(n,t.dtype),i=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=i.indexToLoc(r),u=new Array(s.length),l=0;l<u.length;l++)u[l]=s[e[l]];var c=a.locToIndex(u);a.values[c]=o[r]}return a.toTensor()},e.prototype.gather=function(t,e,n){this.assertNotComplex([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=Pn(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),l=u.slice();l[n]=o[u[n]];var c=i.locToIndex(l);a.values[s]=i.values[c]}return a.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){this.assertNotComplex([t],"batchToSpaceND");var r=e.reduce(function(t,e){return t*e}),o=hr(t.shape,e,r),a=pr(o.length,e.length),i=dr(t.shape,e,r),s=fr(n,e.length),u=vr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){this.assertNotComplex([t],"spaceToBatchND");var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=hr(i.shape,e,r,!1),u=pr(s.length,e.length,!1),l=dr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(l)},e.prototype.pool=function(t,e,n){this.assertNotComplex(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,p=this.readSync(t.dataId),d=Pn(e.outShape,t.dtype),f=d.values,v=e.outShape[1]*e.outShape[2]*e.outShape[3],m=e.outShape[2]*e.outShape[3],g=e.outShape[3],y=0;y<e.batchSize;++y)for(var x=y*v,b=y*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var E=C*r-l,N=Math.max(0,E),R=Math.min(e.inHeight,s+E),I=x+C*m,k=0;k<e.outWidth;++k){for(var S=k*o-c,A=Math.max(0,S),T=Math.min(e.inWidth,u+S),D=h,_=0,O=0,F=N;F<R;F+=a){for(var M=b+F*t.strides[1],B=A;B<T;B+=i){var P=p[M+B*t.strides[2]+w];"max"===n&&P>D?D=P:"avg"===n&&(_+=P,O++)}if(isNaN(D))break}f[I+k*g+w]="avg"===n?_/O:D}return d.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=Pn(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h=this.bufferSync(t),p=0;p<e.batchSize;++p)for(var d=0;d<e.inChannels;++d)for(var f=0;f<e.outHeight;++f){for(var v=f*r-l,m=v;m<0;)m+=a;for(var g=Math.min(e.inHeight,s+v),y=0;y<e.outWidth;++y){for(var x=y*o-c,b=x;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,N=m;N<g;N+=a)for(var R=N-v,I=b;I<w;I+=i){var k=I-x,S=h.get(p,N,I,d);S>C&&(C=S,E=R*u+k)}n.set(E,p,f,y,d)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,h=c-1-r.padInfo.left,p=l-1-r.padInfo.top,d=Pn(e.shape,"float32"),f=this.bufferSync(o),v=this.bufferSync(t),m=0;m<r.batchSize;++m)for(var g=0;g<r.inChannels;++g)for(var y=0;y<r.inHeight;++y)for(var x=0;x<r.inWidth;++x){for(var b=y-p,w=x-h,C=0,E=0;E<l;E+=s){var N=(b+E)/a;if(!(N<0||N>=r.outHeight||Math.floor(N)!==N))for(var R=0;R<c;R+=u){var I=(w+R)/i;if(!(I<0||I>=r.outWidth||Math.floor(I)!==I)){var k=l*c-1-f.get(m,N,I,g)===E*c+R?1:0;if(0!==k)C+=v.get(m,N,I,g)*k}}}d.set(C,m,y,x,g)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,h=c-1-n.padInfo.left,p=l-1-n.padInfo.top,d=Pn(e.shape,"float32"),f=1/(a*i),v=this.bufferSync(t),m=0;m<n.batchSize;++m)for(var g=0;g<n.inChannels;++g)for(var y=0;y<n.inHeight;++y)for(var x=0;x<n.inWidth;++x){for(var b=y-p,w=x-h,C=0,E=0;E<l;E+=s){var N=(b+E)/r;if(!(N<0||N>=n.outHeight||Math.floor(N)!==N))for(var R=0;R<c;R+=u){var I=(w+R)/o;if(!(I<0||I>=n.outWidth||Math.floor(I)!==I))C+=v.get(m,N,I,g)}}d.set(C*f,m,y,x,g)}return d.toTensor()},e.prototype.pool3d=function(t,e,n){this.assertNotComplex(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=Pn(e.outShape,t.dtype),y=g.values,x=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;E<e.batchSize;++E)for(var N=E*x,R=E*t.strides[0],I=0;I<e.inChannels;++I)for(var k=0;k<e.outDepth;++k){for(var S=k*r-p,A=S;A<0;)A+=i;for(var T=Math.min(e.inDepth,l+S),D=N+k*b,_=0;_<e.outHeight;++_){for(var O=_*o-d,F=O;F<0;)F+=s;for(var M=Math.min(e.inHeight,c+O),B=D+_*w,P=0;P<e.outWidth;++P){for(var L=P*a-f,V=L;V<0;)V+=u;for(var W=Math.min(e.inWidth,h+L),U=B+P*C,z=v,G=0,H=0,q=A;q<T;q+=i){for(var $=R+q*t.strides[1],K=F;K<M;K+=s){for(var j=$+K*t.strides[2],X=V;X<W;X+=u){var Y=m[j+X*t.strides[3]+I];if("max"===n&&Y>z?z=Y:"avg"===n&&(G+=Y,H++),isNaN(z))break}if(isNaN(z))break}if(isNaN(z))break}y[U+I]="avg"===n?G/H:z}}}return g.toTensor()},e.prototype.avgPool3d=function(t,e){return this.assertNotComplex(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,h=n.dilationWidth,p=n.effectiveFilterDepth,d=n.effectiveFilterHeight,f=n.effectiveFilterWidth,v=p-1-n.padInfo.front,m=f-1-n.padInfo.left,g=d-1-n.padInfo.top,y=Pn(e.shape,"float32"),x=1/(i*s*u),b=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var E=0;E<n.inDepth;++E)for(var N=0;N<n.inHeight;++N)for(var R=0;R<n.inWidth;++R){for(var I=E-v,k=N-g,S=R-m,A=0,T=0;T<p;T+=l){var D=(I+T)/r;if(!(D<0||D>=n.outDepth||Math.floor(D)!==D))for(var _=0;_<d;_+=c){var O=(k+_)/o;if(!(O<0||O>=n.outHeight||Math.floor(O)!==O))for(var F=0;F<f;F+=h){var M=(S+F)/a;if(!(M<0||M>=n.outWidth||Math.floor(M)!==M))A+=b.get(w,D,O,M,C)}}}y.set(A*x,w,E,N,R,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return this.assertNotComplex(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Pn(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,v=this.bufferSync(t),m=0;m<e.batchSize;++m)for(var g=0;g<e.inChannels;++g)for(var y=0;y<e.outDepth;++y){for(var x=y*r-p,b=x;b<0;)b+=i;for(var w=Math.min(e.inDepth,l+x),C=0;C<e.outHeight;++C){for(var E=C*o-d,N=E;N<0;)N+=s;for(var R=Math.min(e.inHeight,c+E),I=0;I<e.outWidth;++I){for(var k=I*a-f,S=k;S<0;)S+=u;for(var A=Math.min(e.inWidth,h+k),T=Number.NEGATIVE_INFINITY,D=-1,_=b;_<w;_+=i)for(var O=_-x,F=N;F<R;F+=s)for(var M=F-E,B=S;B<A;B+=u){var P=B-k,L=v.get(m,_,F,B,g);L>=T&&(T=L,D=O*c*h+M*c+P)}n.set(D,m,y,C,I,g)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterDepth,p=r.effectiveFilterHeight,d=r.effectiveFilterWidth,f=h-1-r.padInfo.front,v=d-1-r.padInfo.left,m=p-1-r.padInfo.top,g=Pn(e.shape,"float32"),y=this.bufferSync(o),x=this.bufferSync(t),b=0;b<r.batchSize;++b)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var E=0;E<r.inHeight;++E)for(var N=0;N<r.inWidth;++N){for(var R=C-f,I=E-m,k=N-v,S=0,A=0;A<h;A+=u){var T=(R+A)/a;if(!(T<0||T>=r.outDepth||Math.floor(T)!==T))for(var D=0;D<p;D+=l){var _=(I+D)/i;if(!(_<0||_>=r.outHeight||Math.floor(_)!==_))for(var O=0;O<d;O+=c){var F=(k+O)/s;if(!(F<0||F>=r.outWidth||Math.floor(F)!==F)){var M=h*p*d-1-y.get(b,T,_,F,w)===A*p*d+D*d+O?1:0;if(0!==M)S+=x.get(b,T,_,F,w)*M}}}}g.set(S,b,C,E,N,w)}return g.toTensor()},e.prototype.cast=function(t,e){return Xr(t,e,this)},e.prototype.reshape=function(t,e){return Yr(t,e)},e.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(g([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,f=h[0]/p[0],v=h[1]/p[1],m=0;m<a;m++)for(var y=0;y<e;y++)for(var x=f*y,b=Math.floor(x),w=x-b,C=Math.min(i-1,Math.ceil(x)),E=m*t.strides[0]+b*t.strides[1],N=m*t.strides[0]+C*t.strides[1],R=0;R<n;R++)for(var I=v*R,k=Math.floor(I),S=I-k,A=Math.min(s-1,Math.ceil(I)),T=E+k*t.strides[2],D=N+k*t.strides[2],_=E+ +A*t.strides[2],O=N+A*t.strides[2],F=0;F<u;F++){var M=l[T+F],B=l[D+F],P=M+(l[_+F]-M)*S,L=P+(B+(l[O+F]-B)*S-P)*w;c[d++]=L}return nn(c,[a,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],h=new Float32Array(o*a*i*s),p=[n&&l>1?a-1:a,n&&c>1?i-1:i],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],f=p[0]/d[0],v=p[1]/d[1],m=this.readSync(t.dataId),g=0,y=0;y<o;y++)for(var x=y*e.strides[0],b=0;b<l;b++)for(var w=b*f,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),N=x+C*e.strides[1],R=x+E*e.strides[1],I=w-C,k=1-I,S=0;S<c;S++)for(var A=S*v,T=Math.floor(A),D=Math.min(Math.ceil(A),i-1),_=A-T,O=1-_,F=N+T*e.strides[2],M=N+D*e.strides[2],B=R+T*e.strides[2],P=R+D*e.strides[2],L=k*O,V=k*_,W=I*O,U=I*_,z=0;z<s;z++){var G=m[g++];h[F+z]+=G*L,h[M+z]+=G*V,h[B+z]+=G*W,h[P+z]+=G*U}return ln(h,[o,i,a,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){this.assertNotComplex(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(a*e*n*u),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=h[0]/p[0],f=h[1]/p[1],v=0,m=0;m<a;m++)for(var g=m*t.strides[0],y=0;y<e;y++)for(var x=d*y,b=g+Math.min(i-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=f*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],N=0;N<u;N++){var R=l[E+N];c[v++]=R}return nn(c,[a,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],h=new Float32Array(o*a*i*s),p=this.readSync(t.dataId),d=[n&&l>1?a-1:a,n&&c>1?i-1:i],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],v=d[0]/f[0],m=d[1]/f[1],g=1/v,y=1/m,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w<o;w++)for(var C=w*e.strides[0],E=0;E<a;E++)for(var N=C+E*e.strides[1],R=Math.floor(E*g),I=Math.floor(R-x/2),k=0;k<i;k++)for(var S=N+k*e.strides[2],A=Math.floor(k*y),T=Math.floor(A-b/2),D=0;D<s;D++){for(var _=0,O=0;O<x;O++){var F=O+I;if(!(F<0||F>=l)){var M=C+F*t.strides[1],B=F*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+T;if(!(L<0||L>=c)){var V=M+L*t.strides[2],W=L*m;k===Math.min(i-1,n?Math.round(W):Math.floor(W))&&(_+=p[V+D])}}}}h[S+D]=_}return ln(h,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,a){this.assertNotComplex([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=o?this.readSync(o.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),p=c.length,d=l.length,f=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b<i.length;++b)h[b]=c[m++]+(i[b]-s[g++])*l[y++]/Math.sqrt(u[x++]+r),m>=p&&(m=0),g>=v&&(g=0),y>=d&&(y=0),x>=f&&(x=0);return ln(h,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var l=s[r];u+=l*l}return u}for(var h=0;h<u;h++){var p=c(h),d=s[h]*Math.pow(n+r*p,-o);l[h]=d}return ln(l,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){this.assertNotComplex(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=this.readSync(n.dataId),h=new Float32Array(t.size),p=t.size,d=0;d<p;d++){for(var f=d%s,v=d-f+Math.max(0,f-r),m=d-f+Math.min(s,f+r+1),g=0,y=v;y<m;y++)g+=Math.pow(l[y],2);g=a*g+o;for(y=v;y<m;y++){var x=-2*a*i*l[y]*c[d]/g;d===y&&(x+=Math.pow(g,-i)),x*=u[d],h[y]+=x}}return ln(h,t.shape)},e.prototype.multinomial=function(t,e,n,r){this.assertNotComplex(t,"multinomial");for(var o=e?t:Tr(t),a=o.shape[0],i=o.shape[1],s=dn([a,n],"int32"),u=this.readSync(s.dataId),l=this.readSync(o.dataId),c=0;c<a;++c){var h=c*i,p=new Float32Array(i-1);p[0]=l[h];for(var d=1;d<p.length;++d)p[d]=p[d-1]+l[h+d];for(var f=On(r.toString()),v=c*n,m=0;m<n;++m){var g=f();u[v+m]=p.length;for(var y=0;y<p.length;y++)if(g<p[y]){u[v+m]=y;break}}}return s},e.prototype.oneHot=function(t,e,n,r){this.assertNotComplex(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var a=this.readSync(t.dataId),i=0;i<t.size;++i)a[i]>=0&&a[i]<e&&(o[i*e+a[i]]=n);return sn(o,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return this.assertNotComplex(t,"nonMaxSuppression"),ro(this.readSync(t.dataId),this.readSync(e.dataId),n,r,o)},e.prototype.fft=function(t){return this.fftBatch(t,!1)},e.prototype.ifft=function(t){return this.fftBatch(t,!0)},e.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],o=Pn(t.shape,"float32"),a=Pn(t.shape,"float32"),i=tn(t).as2D(n,r),s=en(t).as2D(n,r),u=0;u<n;u++)for(var l=i.slice([u,0],[1,r]),c=s.slice([u,0],[1,r]),h=Ze(l,c),p=this.readSync(this.fftImpl(h,e).dataId),d=0;d<r;d++){var f=to(p,d);o.values[u*r+d]=f.real,a.values[u*r+d]=f.imag}return Ze(o.toTensor(),a.toTensor()).as2D(n,r)},e.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var o=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(o=Ze(tn(o).div(on(r)),en(o).div(on(r)))),o}var a=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(a,r,e));return Ze(i.real,i.imag).as2D(t.shape[0],t.shape[1])},e.prototype.isExponentOf2=function(t){return 0==(t&t-1)},e.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),o=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=0;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),i=Ze(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=2;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),u=Ze(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var l=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),o=0;o<Math.ceil(t/2);o++){var a=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(a),r[o]=Math.sin(a)}return{real:n,imag:r}}(e,n),c=Ze(l.real,l.imag).mul(u),h=i.add(c),p=i.sub(c),d=tn(h).concat(tn(p)),f=en(h).concat(en(p));return Ze(d,f).as1D()},e.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var a=0,i=0,s=0;s<e;s++){var u=no(o*s,e,n),l=to(t,s);a+=l.real*u.real-l.imag*u.imag,i+=l.real*u.imag+l.imag*u.real}n&&(a/=e,i/=e),eo(r,a,i,o)}return r},e.prototype.depthToSpace=function(t,e,n){d("NHWC"===n,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n}),d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,l=i/(e*e),c=this.readSync(t.dataId),h=new Float32Array(r*s*u*l),p=0,f=0;f<r;++f)for(var v=0;v<s;++v)for(var m=Math.floor(v/e),g=v%e,y=0;y<u;++y)for(var x=Math.floor(y/e),b=(g*e+y%e)*l,w=0;w<l;++w){var C=w+b+i*(x+a*(m+o*f));h[p++]=c[C]}return ln(h,[r,s,u,l])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=Br(t.shape,e.shape),a=Pn(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Fr(t.shape,o),l=Fr(e.shape,o),c=a.values;if(u.length+l.length===0)for(var h=0;h<c.length;++h)c[h]=r(i[h%i.length],s[h%s.length]);else{var p=this.bufferSync(t),d=this.bufferSync(e),f=function(n){var o=a.indexToLoc(n),h=o.slice(-t.rank);u.forEach(function(t){return h[t]=0});var f=p.locToIndex(h),v=o.slice(-e.rank);l.forEach(function(t){return v[t]=0});var m=d.locToIndex(v);c[n]=r(i[f],s[m])};for(h=0;h<c.length;++h)f(h)}return a.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Br(t.shape,e.shape),o=Pn(r,"float32"),a=Pn(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Fr(t.shape,r),l=Fr(e.shape,r),c=o.values,h=a.values;if(u.length+l.length===0)for(var p=0;p<c.length;p++){var d=p%i.length,f=p%s.length,v=n(i[2*d],i[2*d+1],s[2*f],s[2*f+1]);c[p]=v.real,h[p]=v.imag}else{var m=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var a=o.indexToLoc(r),p=a.slice(-t.rank);u.forEach(function(t){return p[t]=0});var d=m.locToIndex(p),f=a.slice(-e.rank);l.forEach(function(t){return f[t]=0});var v=g.locToIndex(f),y=n(i[2*d],i[2*d+1],s[2*v],s[2*v+1]);c[r]=y.real,h[r]=y.imag};for(p=0;p<c.length;p++)y(p)}return this.complex(o.toTensor(),a.toTensor())},e.prototype.split=function(t,e,n){return ao(t,e,n)},e.prototype.dispose=function(){},e.prototype.floatPrecision=function(){return 32},e.prototype.epsilon=function(){return 1e-7},e.prototype.cropAndResize=function(t,e,n,r,o,a){for(var i=t.shape,s=i[0],u=i[1],l=i[2],c=i[3],h=e.shape[0],p=r[0],d=r[1],f=Pn([h,p,d,c],t.dtype),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=f.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],N=v[w+2],R=v[w+3],I=m[b];if(!(I>=s))for(var k=p>1?(N-C)*(u-1)/(p-1):0,S=d>1?(R-E)*(l-1)/(d-1):0,A=0;A<p;A++){var T=p>1?C*(u-1)+A*k:.5*(C+N)*(u-1);if(T<0||T>u-1)for(var D=0;D<d;D++)for(var _=0;_<c;_++){var O=_+D*x[2]+A*x[1]+b*x[0];f.values[O]=a}else if("bilinear"===o){var F=Math.floor(T),M=Math.ceil(T),B=T-F;for(D=0;D<d;D++){if((q=d>1?E*(l-1)+D*S:.5*(E+R)*(l-1))<0||q>l-1)for(_=0;_<c;_++){O=_+D*x[2]+A*x[1]+b*x[0];f.values[O]=a}else{var P=Math.floor(q),L=Math.ceil(q),V=q-P;for(_=0;_<c;_++){var W=g[O=_+P*y[2]+F*y[1]+I*y[0]],U=g[O=_+L*y[2]+F*y[1]+I*y[0]],z=g[O=_+P*y[2]+M*y[1]+I*y[0]],G=W+(U-W)*V,H=z+(g[O=_+L*y[2]+M*y[1]+I*y[0]]-z)*V;O=_+D*x[2]+A*x[1]+b*x[0],f.values[O]=G+(H-G)*B}}}}else for(D=0;D<d;++D){var q;if((q=d>1?E*(l-1)+D*S:.5*(E+R)*(l-1))<0||q>l-1)for(_=0;_<c;_++){O=_+D*x[2]+A*x[1]+b*x[0];f.values[O]=a}else{var $=Math.round(q),K=Math.round(T);for(_=0;_<c;_++){var j=_+$*y[2]+K*y[1]+I*y[0],X=_+D*x[2]+A*x[1]+b*x[0];f.values[X]=g[j]}}}}}return f.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var o=br(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,l=o.outputSize;return this.scatter(t,e,n,l,s,i,a,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=mr(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return nn([],a,t.dtype);for(var l=new it([i,s],t.dtype),c=this.readSync(e.dataId),h=this.readSync(t.dataId),p=0;p<i;p++){for(var d=[],f=0,v=0;v<r;v++){var m=c[p*r+v];f+=m*u[v],d.push(m)}if(f<0||f>=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var g=0;g<s;g++)l.values[p*s+g]=h[f*s+g]}return l.toTensor().reshape(a)},e.prototype.scatterND=function(t,e,n){var r=br(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=on(0);return this.scatter(t,e,n,u,i,a,o,s,l,!0)},e.prototype.fill=function(t,e,n){var r=S(n=n||L(e),g(t));return r.fill(e),ct.make(t,{values:r},n)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){var e=S(t.dtype,g(t.shape));return ct.make(t.shape,{values:e},t.dtype)},e.prototype.linspace=function(t,e,n){return Qr(t,e,n)},e.prototype.scatter=function(t,e,n,r,o,a,i,s,u,l){var c=[r/o,o],h=this.readSync(t.dataId),p=this.readSync(e.dataId);if(0===r)return nn([],n,e.dtype);var d=new it(c,e.dtype);d.values.fill(this.readSync(u.dataId)[0]);for(var f=0;f<a;f++){for(var v=[],m=0,g=0;g<i;g++){var y=h[f*i+g];v.push(y),m+=y*s[g]}if(m<0||m>=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x<o;x++)l?d.values[m*o+x]+=p[f*o+x]:d.values[m*o+x]=0===e.rank?p[0]:p[f*o+x]}return d.toTensor().reshape(n)},e}();St.registerBackend("cpu",function(){return new Bc},1);var Pc=function(){function t(){this.textEncoder=new TextEncoder}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();t.ENV.get("IS_BROWSER")&&t.ENV.setPlatform("browser",new Pc);var Lc,Vc=function(){return require("node-fetch")},Wc=function(){function e(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return e.prototype.fetch=function(e,n){return null!=t.ENV.global.fetch?t.ENV.global.fetch(e,n):(null==Lc&&(Lc=Vc()),Lc(e,n))},e.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},e.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},e.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},e}();t.ENV.get("IS_NODE")&&t.ENV.setPlatform("node",new Wc);var Uc={float32:4,int32:4,uint16:2,uint8:1,bool:1},zc=4;function Gc(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=g(i),u=void 0;if("quantization"in e){var l=e.quantization;if("uint8"!==l.dtype&&"uint16"!==l.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+l.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var c=Uc[l.dtype],h=t.slice(r,r+s*c),p="uint8"===l.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===a)u=Float32Array.from(p,function(t){return t*l.scale+l.min});else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(p,function(t){return Math.round(t*l.scale+l.min)})}r+=s*c}else if("string"===a){var d=g(e.shape);u=[];for(var f=0;f<d;f++){var v=new Uint32Array(t.slice(r,r+zc))[0];r+=zc;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v}}else{var y=Uc[a];h=t.slice(r,r+s*y);if("float32"===a)u=new Float32Array(h);else if("int32"===a)u=new Int32Array(h);else{if("bool"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=new Uint8Array(h)}r+=s*y}n[o]=nn(u,i,a)},a=0,i=e;a<i.length;a++){o(i[a])}return n}function Hc(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach(function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)});var r=new Uint8Array(e),o=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),o),o+=t.byteLength}),r.buffer}var qc="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function $c(t){return qc?Buffer.byteLength(t):new Blob([t]).size}function Kc(t){var e=0;t.forEach(function(t){e+=t.byteLength});var n=new Uint8Array(e),r=0;return t.forEach(function(t){n.set(new Uint8Array(t),r),r+=t.byteLength}),n.buffer}function jc(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function Xc(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:$c(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:$c(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var Yc=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var o=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach(function(t){var n=t(e,r);null!==n&&o.push(n)}),o},t}(),Qc="://",Jc=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){d(null!=e,function(){return"scheme must not be undefined or null."}),e.endsWith(Qc)&&(e=e.slice(0,e.indexOf(Qc))),d(e.length>0,function(){return"scheme must not be an empty string."});var r=t.getInstance();d(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Zc(t){if(-1===t.indexOf(Qc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Jc.getSchemes().join(","));return{scheme:t.split(Qc)[0],path:t.split(Qc)[1]}}function th(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return d(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),d((r=Yc.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),d(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),a=r[0],d((i=Yc.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),d(i.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=i[0],u=Zc(t).scheme,l=Zc(t).path,c=u===Zc(t).scheme,[4,a.load()];case 1:return h=o.sent(),n&&c?[4,Jc.getManager(u).removeModel(l)]:[3,3];case 2:o.sent(),o.label=3;case 3:return[4,s.save(h)];case 4:return p=o.sent(),!n||c?[3,6]:[4,Jc.getManager(u).removeModel(l)];case 5:o.sent(),o.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var eh="models_store",nh="model_info_store";function rh(){if(!t.ENV.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window,n=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==n)throw new Error("The current browser does not appear to support IndexedDB.");return n}function oh(t){var e=t.result;e.createObjectStore(eh,{keyPath:"modelPath"}),e.createObjectStore(nh,{keyPath:"modelPath"})}var ah=function(){function t(t){if(this.indexedDB=rh(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return oh(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(eh,"readonly"),s=i.objectStore(eh).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()}}else{var u,l=Xc(e),c=a.transaction(nh,"readwrite"),h=c.objectStore(nh),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var o=(u=a.transaction(eh,"readwrite")).objectStore(eh).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});o.onsuccess=function(){return t({modelArtifactsInfo:l})},o.onerror=function(t){var e=(h=c.objectStore(nh)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},p.onerror=function(t){return a.close(),r(p.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},o.onerror=function(t){return r(o.error)}})},t.URL_SCHEME="indexeddb://",t}(),ih=function(e){return t.ENV.getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ah.URL_SCHEME)?(n=e.slice(ah.URL_SCHEME.length),new ah(n)):null;var n};Yc.registerSaveRouter(ih),Yc.registerLoadRouter(ih);var sh=function(){function t(){this.indexedDB=rh()}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return o(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return oh(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(nh,"readonly"),a=o.objectStore(nh).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo}e(t)},a.onerror=function(e){return t.close(),n(a.error)},o.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}})]})})},t.prototype.removeModel=function(t){return r(this,void 0,void 0,function(){var e=this;return o(this,function(n){var r;return t=(r=t).startsWith(ah.URL_SCHEME)?r.slice(ah.URL_SCHEME.length):r,[2,new Promise(function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return oh(o)},o.onsuccess=function(){var e,a=o.result,i=a.transaction(nh,"readwrite"),s=i.objectStore(nh),u=s.get(t);u.onsuccess=function(){if(null==u.result)return a.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),i=function(){var o=(e=a.transaction(eh,"readwrite")).objectStore(eh).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo)},o.onerror=function(t){return r(u.error)}};o.onsuccess=i,o.onerror=function(t){return i(),a.close(),r(u.error)}},u.onerror=function(t){return a.close(),r(u.error)},i.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close()}}},o.onerror=function(t){return r(o.error)}})]})})},t}();if(t.ENV.getBool("IS_BROWSER"))try{Jc.registerManager(ah.URL_SCHEME,new sh)}catch(t){}var uh="/",lh="tensorflowjs_models",ch="info",hh="model_topology",ph="weight_specs",dh="weight_data",fh="model_metadata";function vh(t){return{info:[lh,t,ch].join(uh),topology:[lh,t,hh].join(uh),weightSpecs:[lh,t,ph].join(uh),weightData:[lh,t,dh].join(uh),modelMetadata:[lh,t,fh].join(uh)}}function mh(t){var e=t.split(uh);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(uh)}var gh=function(){function e(e){if(!t.ENV.getBool("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=vh(this.modelPath)}return e.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=Xc(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,(a=t.weightData,qc?Buffer.from(a).toString("base64"):btoa(String.fromCharCode.apply(null,new Uint8Array(a))))),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy})),[2,{modelArtifactsInfo:r}]}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".")}var a;return[2]})})},e.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s;return o(this,function(o){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=r,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(qc){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),o=0;o<n.length;++o)r.set([n.charCodeAt(o)],o);return r.buffer}(s),[2,e]})})},e.URL_SCHEME="localstorage://",e}(),yh=function(e){return t.ENV.getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(gh.URL_SCHEME)?(n=e.slice(gh.URL_SCHEME.length),new gh(n)):null;var n};Yc.registerSaveRouter(yh),Yc.registerLoadRouter(yh);var xh=function(){function e(){d(t.ENV.getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),d(void 0!==window.localStorage,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return e.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i;return o(this,function(o){for(t={},e=lh+uh,n=uh+ch,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(i=mh(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]})})},e.prototype.removeModel=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){var o;if(t=(o=t).startsWith(gh.URL_SCHEME)?o.slice(gh.URL_SCHEME.length):o,e=vh(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]})})},e}();if(t.ENV.getBool("IS_BROWSER"))try{Jc.registerManager(gh.URL_SCHEME,new xh)}catch(t){}var bh="model",wh=".json",Ch=".weights.bin";function Eh(t){return new Promise(function(t){return setTimeout(t)}).then(t)}var Nh=function(){function e(n){if(!t.ENV.getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");n.startsWith(e.URL_SCHEME)&&(n=n.slice(e.URL_SCHEME.length)),null!=n&&0!==n.length||(n=bh),this.modelTopologyFileName=n+wh,this.weightDataFileName=n+Ch}return e.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s;return o(this,function(o){switch(o.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,Eh(function(){return i.dispatchEvent(new MouseEvent("click"))})];case 2:return o.sent(),null==t.weightData?[3,4]:((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,Eh(function(){return s.dispatchEvent(new MouseEvent("click"))})]);case 3:o.sent(),o.label=4;case 4:return[2,{modelArtifactsInfo:Xc(t)}]}})})},e.URL_SCHEME="downloads://",e}(),Rh=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n=this;return o(this,function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise(function(r,o){var a=new FileReader;a.onload=function(a){var i=JSON.parse(a.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var l;try{l=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var c=[],h=[],p=[];u.forEach(function(t){t.paths.forEach(function(t){h.push(t),p.push(null)}),c.push.apply(c,t.weights)}),u.forEach(function(t){t.paths.forEach(function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,o=h.indexOf(t);p[o]=n,-1===p.indexOf(null)&&r({modelTopology:s,weightSpecs:c,weightData:Kc(p)})},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(l[t])})})}else o(new Error("weightManifest field is missing from file "+t.name))}else o(new Error("modelTopology field is missing from file "+t.name))},a.onerror=function(e){return o("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},a.readAsText(t)})]})})},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map(function(t){return jc(t.name)}),o={},a=0,i=t;a<i.length;a++){i[a].paths.forEach(function(t){var a=jc(t);if(-1!==n.indexOf(a))throw new Error("Duplicate file basename found in weights manifest: '"+a+"'");if(n.push(a),-1===r.indexOf(a))throw new Error("Weight file with basename '"+a+"' is not provided.");o[t]=e[r.indexOf(a)]})}if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return o},t}();function Ih(t,e,n,r){!function(t){d(null!=t&&Array.isArray(t)&&t.length>0,function(){return"promises must be a none empty array"})}(t),function(t,e){d(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),d(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),d(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var o=0;return Promise.all(t.map(function(a){return a.then(function(a){var i=n+ ++o/t.length*(r-n);return e(i),a}),a}))}function kh(e,n){return r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return null==n&&(n={}),r=null==n.fetchFunc?t.ENV.platform.fetch:n.fetchFunc,a=e.map(function(t){return r(t,n.requestInit,{isBinary:!0})}),i=0,s=.5,null!=n.onProgress?[3,2]:[4,Promise.all(a)];case 1:return u=o.sent(),[3,4];case 2:return[4,Ih(a,n.onProgress,i,s)];case 3:u=o.sent(),o.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer()}),c=.5,h=1,null!=n.onProgress?[3,6]:[4,Promise.all(l)];case 5:return p=o.sent(),[3,8];case 6:return[4,Ih(l,n.onProgress,c,h)];case 7:p=o.sent(),o.label=8;case 8:return[2,p]}})})}function Sh(t){var e=this;return function(n,a,i){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,h,p,d,f;return o(this,function(o){switch(o.label){case 0:if(e=n.map(function(){return!1}),r={},s=null!=i?i.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var o=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Uc[a]*g(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:o,sizeBytes:l})};null!=i?i.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),o+=l})}),!s.every(function(t){return t}))throw l=i.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),h=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e)})}),[4,t(h)];case 1:return p=o.sent(),d={},f=0,c.forEach(function(t){for(var e=n[t].paths.length,o=0,a=0;a<e;a++)o+=p[f+a].byteLength;for(var i=new ArrayBuffer(o),s=new Uint8Array(i),u=0,l=0;l<e;l++){var c=new Uint8Array(p[f+l]);s.set(c,u),u+=c.byteLength}r[t].forEach(function(t){var e=Gc(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)d[n]=e[n]}),f+=e}),[2,d]}})})}}Yc.registerSaveRouter(function(e){return t.ENV.getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Nh.URL_SCHEME)?(n=e.slice(Nh.URL_SCHEME.length),void 0===n&&(n="model"),new Nh(n)):null;var n});var Ah=function(){function e(e,n){if(this.DEFAULT_METHOD="POST",null==n&&(n={}),this.weightPathPrefix=n.weightPathPrefix,this.onProgress=n.onProgress,null!=n.fetchFunc?(d("function"==typeof n.fetchFunc,function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"}),this.fetch=n.fetchFunc):this.fetch=t.ENV.platform.fetch,d(null!=e&&e.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(e)&&d(2===e.length,function(){return"URL paths for http must have a length of 2, (actual length is "+e.length+")."}),this.path=e,null!=n.requestInit&&null!=n.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=n.requestInit||{}}return e.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a;return o(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=o.sent()).ok)return[2,{modelArtifactsInfo:Xc(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=o.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");o.label=2;case 2:return o.trys.push([2,4,,5]),[4,t.json()];case 3:return e=o.sent(),[3,5];case 4:throw o.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=o.sent(),i=u[0],s=u[1],o.label=7;case 7:return[2,{modelTopology:r,weightSpecs:i,weightData:s}]}})})},e.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o]}(e),r=n[0],a=n[1],i=this.weightPathPrefix||r,s=[],u=0,l=t;u<l.length;u++)c=l[u],s.push.apply(s,c.weights);return h=[],t.forEach(function(t){t.paths.forEach(function(t){h.push(i+t+a)})}),[4,kh(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return p=o.sent(),[2,[s,Kc(p)]]}})})},e.URL_SCHEME_REGEX=/^https?:\/\//,e}();function Th(t){return null!=t.match(Ah.URL_SCHEME_REGEX)}var Dh=function(t,e){if("undefined"==typeof fetch)return null;return(Array.isArray(t)?t.every(function(t){return Th(t)}):Th(t))?_h(t,{onProgress:e}):null};function _h(t,e){return new Ah(t,e)}Yc.registerSaveRouter(Dh),Yc.registerLoadRouter(Dh);var Oh=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return[2,this.modelArtifacts]})})},t}(),Fh=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){return[2,this.saveHandler(t)]})})},t}();var Mh=Object.freeze({browserFiles:function(t){return new Rh(t)},browserHTTPRequest:function(t,e){return _h(t,e)},concatenateArrayBuffers:Kc,decodeWeights:Gc,encodeWeights:function(t,e){return r(this,void 0,void 0,function(){var n,a,i,s,u,l=this;return o(this,function(c){switch(c.label){case 0:for(n=[],a=[],i=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),s=function(s){var u=i[s],c=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==c.dtype&&"int32"!==c.dtype&&"bool"!==c.dtype&&"string"!==c.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+c.dtype);var h={name:u,shape:c.shape,dtype:c.dtype};if("string"===c.dtype){var p=new Promise(function(t){return r(l,void 0,void 0,function(){var e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return[4,c.bytes()];case 1:for(e=o.sent(),n=e.reduce(function(t,e){return t+e.length},0)+zc*e.length,r=new Uint8Array(n),a=0,i=0;i<e.length;i++)s=e[i],u=new Uint8Array(new Uint32Array([s.length]).buffer),r.set(u,a),a+=zc,r.set(s,a),a+=s.length;return t(r),[2]}})})});a.push(p)}else a.push(c.data());null!=e&&(h.group=e),n.push(h)},u=0;u<i.length;++u)s(u);return[4,Promise.all(a)];case 1:return[2,{data:Hc(c.sent()),specs:n}]}})})},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Oh(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Oh({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Oh({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return Yc.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:Xc,getSaveHandlers:function(t){return Yc.getSaveHandlers(t)},http:_h,isHTTPScheme:Th,loadWeights:function(t,e,n,a){return void 0===e&&(e=""),r(this,void 0,void 0,function(){return o(this,function(r){return[2,Sh(function(t){return kh(t,{requestInit:a})})(t,e,n)]})})},registerLoadRouter:function(t){return Yc.registerLoadRouter(t)},registerSaveRouter:function(t){return Yc.registerSaveRouter(t)},weightsLoaderFactory:Sh,withSaveHandler:function(t){return new Fh(t)},copyModel:function(t,e){return r(this,void 0,void 0,function(){return o(this,function(n){return[2,th(t,e,!1)]})})},listModels:function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s;return o(this,function(o){switch(o.label){case 0:t=Jc.getSchemes(),e={},n=0,r=t,o.label=1;case 1:return n<r.length?(a=r[n],[4,Jc.getManager(a).listModels()]):[3,4];case 2:for(s in i=o.sent())e[a+Qc+s]=i[s];o.label=3;case 3:return n++,[3,1];case 4:return[2,e]}})})},moveModel:function(t,e){return r(this,void 0,void 0,function(){return o(this,function(n){return[2,th(t,e,!0)]})})},removeModel:function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return e=Zc(t),[2,Jc.getManager(e.scheme).removeModel(e.path)]})})}});var Bh=Je({confusionMatrix_:function(t,e,n){var r=We(t,"labels","confusionMatrix"),o=We(e,"predictions","confusionMatrix");d(null==n||n>0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),d(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),d(1===o.rank,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),d(r.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),d(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=Kn(r.asType("int32"),n),i=Kn(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),Ph=Object.freeze({confusionMatrix:Bh});var Lh=Je({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");var n="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement;if(n&&n&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");return St.fromPixels(t,e)}}),Vh=Object.freeze({toPixels:function(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p,d,f,v,m,g,y,x,b,w,C,E,N,R;return o(this,function(o){switch(o.label){case 0:if(n=We(t,"img","toPixels"),t instanceof ct||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return[4,n.data()];case 1:return u=o.sent(),l=n.min(),c=n.max(),[4,Promise.all([l.data(),c.data()])];case 2:if(h=o.sent(),p=h[0],d=h[1],f=p[0],v=d[0],l.dispose(),c.dispose(),"float32"===n.dtype){if(f<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+f+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(f<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+f+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*a*4),y=0;y<a*i;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===s?(x=u[y]*m,b=u[y]*m,w=u[y]*m,C=255):3===s?(x=u[3*y]*m,b=u[3*y+1]*m,w=u[3*y+2]*m,C=255):4===s&&(x=u[4*y]*m,b=u[4*y+1]*m,w=u[4*y+2]*m,C=u[4*y+3]*m),g[0+(E=4*y)]=Math.round(x),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=i,e.height=a,N=e.getContext("2d"),R=new ImageData(g,i,a),N.putImageData(R,0,0)),n!==t&&n.dispose(),[2,g]}})})},fromPixels:Lh}),Wh=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Uh=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function zh(t){d(null!=t.className,function(){return"Class being registered does not have the static className property defined."}),d("string"==typeof t.className,function(){return"className is required to be a string, but got type "+typeof t.className}),d(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Uh.register(t)}var Gh=Object.freeze({Serializable:Wh,SerializationMap:Uh,registerClass:zh}),Hh=.001,qh=.1;function $h(){return 32===St.backend.floatPrecision()?Hh:qh}function Kh(t,e,n){var r=!0;if((_(t)||_(e))&&(r=!1),_(t)&&_(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var i=Le(t),s=Le(e);if(!y(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=_(t)?t:m(t),l=_(e)?e:m(e);if(u.length!==l.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+l.length+".\nActual:   "+u+".\nExpected: "+l+".");for(var c=0;c<l.length;++c){var h=u[c],p=l[c];if(!n(h,p))throw new Error("Arrays differ: actual["+c+"] = "+h+", expected["+c+"] = "+p+".\nActual:   "+u+".\nExpected: "+l+".")}}function jh(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var Xh=Object.freeze({TEST_EPSILON_FLOAT16:qh,expectArraysClose:function(t,e,n){return null==n&&(n=$h()),Kh(t,e,function(t,e){return jh(t,e,n)})},testEpsilon:$h,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return M(t)||M(t[0])||M(e)||M(e[0])?Kh(t,n,function(t,e){return t==e}):Kh(t,e,function(t,e){return jh(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=$h()),!jh(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}});var Yh=Object.freeze({gpgpu_util:Ga,webgl_util:_e,forceHalfFloat:function(){t.ENV.set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:ns,setWebGLContext:Ft,GPGPUContext:Ha}),Qh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map(function(t){return{name:t.name,tensor:a[t.name]}});this.applyGradients(i)}else this.applyGradients(a);return Me(a),e?o:(o.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return kr(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Me(this.iterations_)},e.prototype.saveIterations=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:on(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},e.prototype.extractIterations=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}})})},e}(Wh);Object.defineProperty(Qh,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Jh=function(t){function e(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=St.backend.epsilon()),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=St.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Fe(function(){return yn(o).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Fe(function(){return yn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Fe(function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Me(this.accumulatedGrads.map(function(t){return t.variable})),Me(this.accumulatedUpdates.map(function(t){return t.variable})))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,!1,this.accumulatedGrads=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="Adadelta",e}(Qh);zh(Jh);var Zh=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=St.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Fe(function(){return fn(o.shape,e.initialAccumulatorValue).variable(!1)})}}var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Fe(function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(St.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Me(this.accumulatedGrads.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulatedGrads=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(Qh);zh(Zh);var tp=function(t){function e(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Fe(function(){a.accBeta1=on(n).variable(),a.accBeta2=on(r).variable()}),null==o&&(a.epsilon=St.backend.epsilon()),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Fe(function(){var r=Eu(1,e.accBeta1),o=Eu(1,e.accBeta2);n.forEach(function(n,a){var i=St.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Fe(function(){return yn(i).variable(!1)})}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Fe(function(){return yn(i).variable(!1)})});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedSecondMoment[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2).add(s.square().mul(1-e.beta2)),p=c.div(r),d=h.div(o);u.assign(c),l.assign(h);var f=p.div(d.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(f)}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Me(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&Me(this.accumulatedSecondMoment.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e,n=this;return o(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Fe(function(){n.accBeta1.assign(xu(n.beta1,n.iterations_+1)),n.accBeta2.assign(xu(n.beta2,n.iterations_+1))}),e=t.length/2,!1,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(Qh);zh(tp);var ep=function(t){function e(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Fe(function(){i.iteration=on(0).variable(),i.accBeta1=on(n).variable()}),null==o&&(i.epsilon=St.backend.epsilon()),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Fe(function(){var r=Eu(1,e.accBeta1),o=uu(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,a){var i=St.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:yn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:yn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedWeightedInfNorm[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2),p=s.abs(),d=h.maximum(p);u.assign(c),l.assign(d);var f=o.div(r).mul(c.div(d.add(e.epsilon))).add(i);i.assign(f)}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Me(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&Me(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(Qh);zh(ep);var np=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=St.registeredVariables[n];Fe(function(){var t=e.c.mul(o).add(a);a.assign(t)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Be(on(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(Qh);zh(np);var rp=function(t){function e(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=on(o.momentum),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=St.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:Fe(function(){return yn(o).variable(!1)})}}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Fe(function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Me(this.accumulations.map(function(t){return t.variable}))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulations=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="Momentum",e}(np);zh(rp);var op=function(t){function e(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;return i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=St.backend.epsilon()),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=St.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Fe(function(){return yn(o).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Fe(function(){return yn(o).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Fe(function(){return yn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Fe(function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),l=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(l);var c=o.sub(l);o.assign(c)}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));l=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(l);c=o.sub(l);o.assign(c)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Me(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&Me(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&Me(this.accumulatedMoments.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,!1,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(Qh);zh(op);var ap=function(){function t(){}return t.sgd=function(t){return new np(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new rp(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new op(t,e,n,r,o)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new tp(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new Jh(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new ep(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new Zh(t,e)},t}(),ip={sgd:ap.sgd,momentum:ap.momentum,adadelta:ap.adadelta,adagrad:ap.adagrad,rmsprop:ap.rmsprop,adamax:ap.adamax,adam:ap.adam},sp="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};ut=Fc,t.AdadeltaOptimizer=Jh,t.AdagradOptimizer=Zh,t.AdamOptimizer=tp,t.AdamaxOptimizer=ep,t.DataStorage=_r,t.Environment=a,t.KernelBackend=Or,t.MomentumOptimizer=rp,t.Optimizer=Qh,t.RMSPropOptimizer=op,t.SGDOptimizer=np,t.Tensor=ct,t.TensorBuffer=it,t.Variable=ht,t.abs=rs,t.acos=os,t.acosh=as,t.add=ou,t.addN=au,t.addStrict=iu,t.all=Cl,t.any=El,t.argMax=Nl,t.argMin=Rl,t.asin=is,t.asinh=ss,t.atan=us,t.atan2=su,t.atanh=ls,t.avgPool=pl,t.avgPool3d=vl,t.backend=function(){return St.backend},t.backend_util=Jr,t.basicLSTMCell=Ul,t.batchNorm=js,t.batchNorm2d=Xs,t.batchNorm3d=Ys,t.batchNorm4d=Qs,t.batchNormalization=Ks,t.batchNormalization2d=Hs,t.batchNormalization3d=qs,t.batchNormalization4d=$s,t.batchToSpaceND=Vn,t.booleanMaskAsync=Uu,t.browser=Vh,t.buffer=Pn,t.cast=Wn,t.ceil=cs,t.clipByValue=hs,t.clone=Un,t.complex=Ze,t.concat=xn,t.concat1d=bn,t.concat2d=wn,t.concat3d=Cn,t.concat4d=En,t.conv1d=$u,t.conv2d=Ku,t.conv2dDerFilter=Xu,t.conv2dDerInput=Yu,t.conv2dTranspose=Zu,t.conv3d=ju,t.conv3dTranspose=tl,t.cos=ps,t.cosh=ds,t.cumsum=zn,t.customGrad=Sr,t.deprecationWarn=Oe,t.depthToSpace=Gn,t.depthwiseConv2d=Qu,t.diag=tc,t.disableDeprecationWarnings=function(){t.ENV.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},t.dispose=Me,t.disposeVariables=function(){St.disposeVariables()},t.div=uu,t.divStrict=lu,t.dot=nl,t.dropout=ec,t.elu=Ol,t.enableDebugMode=function(){t.ENV.set("DEBUG",!0)},t.enableProdMode=function(){t.ENV.set("PROD",!0)},t.environment=u,t.equal=Ru,t.equalStrict=Iu,t.erf=fs,t.exp=vs,t.expandDims=Hn,t.expm1=ms,t.eye=qn,t.fft=Kl,t.fill=fn,t.findBackend=function(t){return St.findBackend(t)},t.findBackendFactory=function(t){return St.findBackendFactory(t)},t.floor=gs,t.floorDiv=cu,t.frame=ac,t.fused=Oc,t.gather=Vu,t.gatherND=Zl,t.getBackend=function(){return St.backendName},t.grad=function(t){return d(V(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){var r=We(e,"x","tf.grad",null),o=null!=n?We(n,"dy","tf.grad"):null;return St.tidy(function(){var e=St.gradients(function(){return t(r)},[r],o),n=e.value,a=e.grads;return null!=o&&f(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ar(a),a[0]})}},t.grads=function(t){return d(V(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){d(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var r=Ue(e,"args","tf.grads",null),o=null!=n?We(n,"dy","tf.grads"):null;return St.tidy(function(){var e=St.gradients(function(){return t.apply(void 0,r)},r,o),n=e.value,a=e.grads;return null!=o&&f(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ar(a),a})}},t.greater=ku,t.greaterEqual=Su,t.greaterEqualStrict=Au,t.greaterStrict=Tu,t.hammingWindow=oc,t.hannWindow=rc,t.ifft=jl,t.imag=en,t.image=Tc,t.inTopKAsync=lc,t.io=Mh,t.irfft=Yl,t.isFinite=As,t.isInf=Ss,t.isNaN=ks,t.keep=Be,t.leakyRelu=Fl,t.less=Du,t.lessEqual=_u,t.lessEqualStrict=Ou,t.lessStrict=Fu,t.linalg=Ec,t.linspace=vn,t.localResponseNormalization=Vl,t.log=ys,t.log1p=xs,t.logSigmoid=bs,t.logSoftmax=Dr,t.logSumExp=Il,t.logicalAnd=Js,t.logicalNot=Zs,t.logicalOr=tu,t.logicalXor=eu,t.losses=xc,t.matMul=el,t.math=Ph,t.max=kl,t.maxPool=hl,t.maxPool3d=fl,t.maximum=hu,t.maximumStrict=pu,t.mean=Sl,t.memory=function(){return St.memory()},t.min=Al,t.minimum=du,t.minimumStrict=fu,t.mod=vu,t.modStrict=mu,t.moments=Tl,t.movingAverage=Gl,t.mul=gu,t.mulStrict=yu,t.multiRNNCell=zl,t.multinomial=$n,t.neg=ws,t.nextFrame=function(){return new Promise(function(t){return sp(function(){return t()})})},t.norm=Wl,t.notEqual=Mu,t.notEqualStrict=Bu,t.oneHot=Kn,t.ones=pn,t.onesLike=gn,t.op=Je,t.outerProduct=rl,t.pad=jn,t.pad1d=Xn,t.pad2d=Yn,t.pad3d=Qn,t.pad4d=Jn,t.pool=dl,t.pow=xu,t.powStrict=bu,t.prelu=Ml,t.print=Ln,t.prod=_l,t.profile=function(t){return St.profile(t)},t.rand=Zn,t.randomGamma=er,t.randomNormal=tr,t.randomUniform=nr,t.range=mn,t.ready=function(){return St.ready()},t.real=tn,t.reciprocal=Cs,t.registerBackend=function(t,e,n){return void 0===n&&(n=1),St.registerBackend(t,e,n)},t.relu=Bl,t.removeBackend=function(t){St.removeBackend(t)},t.reshape=rr,t.reverse=ol,t.reverse1d=al,t.reverse2d=il,t.reverse3d=sl,t.reverse4d=ul,t.rfft=Xl,t.round=Es,t.rsqrt=Ns,t.scalar=on,t.scatterND=$l,t.selu=Pl,t.separableConv2d=Ju,t.serialization=Gh,t.setBackend=function(t){return St.setBackend(t)},t.setPlatform=function(e,n){t.ENV.setPlatform(e,n)},t.setdiff1dAsync=cr,t.sigmoid=Rs,t.sign=Is,t.signal=sc,t.sin=Ts,t.sinh=Ds,t.slice=ml,t.slice1d=gl,t.slice2d=yl,t.slice3d=xl,t.slice4d=bl,t.softmax=Tr,t.softplus=_s,t.spaceToBatchND=or,t.sparseToDense=Jl,t.spectral=Ql,t.split=Nn,t.sqrt=Os,t.square=Fs,t.squaredDifference=wu,t.squaredDifferenceStrict=Cu,t.squeeze=ar,t.stack=ir,t.step=Ms,t.stft=ic,t.stridedSlice=Hl,t.sub=Eu,t.subStrict=Nu,t.sum=Dl,t.tan=Bs,t.tanh=Ps,t.tensor=nn,t.tensor1d=an,t.tensor2d=sn,t.tensor3d=un,t.tensor4d=ln,t.tensor5d=cn,t.tensor6d=hn,t.tensor_util=Rt,t.test_util=Xh,t.tidy=Fe,t.tile=sr,t.time=function(t){return St.time(t)},t.topk=ql,t.train=ip,t.transpose=Ll,t.truncatedNormal=ur,t.unsortedSegmentSum=Wu,t.unstack=lr,t.util=Y,t.valueAndGrad=function(t){return d(V(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){d(e instanceof ct,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),d(null==n||n instanceof ct,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=St.gradients(function(){return t(e)},[e],n),o=r.grads,a=r.value;return Ar(o),{grad:o[0],value:a}}},t.valueAndGrads=function(t){return d(V(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){d(Array.isArray(e)&&e.every(function(t){return t instanceof ct}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),d(null==n||n instanceof ct,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=St.gradients(function(){return t.apply(void 0,e)},e,n);return null!=n&&f(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ar(r.grads),r}},t.variable=gt,t.variableGrads=kr,t.version_core="1.2.9",t.webgl=Yh,t.where=nu,t.whereAsync=ru,t.zeros=dn,t.zerosLike=yn,Object.defineProperty(t,"__esModule",{value:!0})});
  //# sourceMappingURL=tf-core.min.js.map
  