/**
 * @license
 * Copyright 2020 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,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return i(n,e[0],e[1]),e.join("=")})),n);if("tfjsflags"in r)r.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,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function s(){return t.ENV}t.ENV=null;var u=new Map,c=new Map;function l(t,e){var n=v(t,e);return u.get(n)}function h(t){return c.get(t)}function d(t){for(var e=u.entries(),n=[];;){var r=e.next(),o=r.done,a=r.value;if(o)break;var i=a[0],s=a[1];i.split("_")[0]===t&&n.push(s)}return n}function f(t){var e=t.kernelName,n=t.backendName,r=v(e,n);if(u.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");u.set(r,t)}function p(t){var e=t.kernelName;c.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),c.set(e,t)}function v(t,e){return e+"_"+t}function m(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 g(t,e,n){return Math.max(t,Math.min(e,n))}function y(t){return t%2==0?t:t+1}function x(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function b(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function w(t,e,n){void 0===n&&(n=""),b(I(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function C(t){b(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function E(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||W(t)&&!n)for(var r=0;r<t.length;++r)E(t[r],e,n);else e.push(t);return e}function R(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function I(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 k(t){return t%1==0}function S(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 A(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function D(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function T(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{a++;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 F(t,e){var n=e.length;return b((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})),b(t.every((function(t){return k(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 _(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||o?null:F(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 O(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 M(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 B(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 P(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function L(t,e){return"complex64"!==e&&(("float32"!==e||"complex64"===t)&&(("int32"!==e||"float32"===t||"complex64"===t)&&("bool"!==e||"bool"!==t)))}function W(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function U(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 z(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function V(t){return"string"==typeof t||t instanceof String}function G(t){return"boolean"==typeof t}function H(t){return"number"==typeof t}function q(t){return Array.isArray(t)?q(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":H(t)?"float32":V(t)?"string":G(t)?"bool":"float32"}function K(t){return!!(t&&t.constructor&&t.call&&t.apply)}function j(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function X(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 Y(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=E(t)),n&&B(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 $(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 Q(t,e){for(var n=J(t,e),r=0;r<n.length;r++)n[r]=1;return n}function J(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 Z(){return s().platform.now()}function tt(t){t.forEach((function(e){b(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function et(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",s().platform.encode(t,e)}function nt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",s().platform.decode(t,e)}function rt(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],o=0;o<t.length-1;++o)r+=n[o]*t[o];return r}function ot(t,e,n){if(0===e)return[];if(1===e)return[t];for(var r=new Array(e),o=0;o<r.length-1;++o)r[o]=Math.floor(t/n[o]),t-=r[o]*n[o];return r[r.length-1]=t,r}var at=Object.freeze({shuffle:m,clamp:g,nearestLargerEven:y,sum:x,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:b,assertShapesMatch:w,assertNonNull:C,flatten:E,sizeFromShape:R,isScalarShape:function(t){return 0===t.length},arraysEqual:I,isInt:k,tanh:S,sizeToSquarishShape:A,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return m(e),e},rightPad:D,repeatedTry:T,inferFromImplicitShape:N,parseAxisParam:F,squeezeShape:_,getTypedArrayFromDType:O,getArrayFromDType:M,checkConversionForErrors:B,isValidDtype:P,hasEncodingLoss:L,isTypedArray:W,bytesPerElement:U,bytesFromStringArray:z,isString:V,isBoolean:G,isNumber:H,inferDtype:q,isFunction:K,nearestDivisor:j,computeStrides:X,toTypedArray:Y,toNestedArray:$,makeOnesTypedArray:Q,makeZerosTypedArray:J,now:Z,assertNonNegativeIntegerDimensions:tt,fetch:function(t,e){return s().platform.fetch(t,e)},encodeString:et,decodeString:nt,locToIndex:rt,indexToLoc:ot}),it=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new st)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,a=this.backendTimer.time((function(){r=n()}));return 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 st=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,a){var i="number"==typeof r?D(r+"ms",9):r.error,s=D(t,25),u=e.rank,c=e.size,l=D(e.shape.toString(),14),h="";for(var d in o){var f=o[d].shape||e.shape,p=f.length;h+=d+": "+p+"D "+(p>0?f:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+h+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();var ut=20,ct=3,lt=7;function ht(t,e,n,r){var o=X(e),a=function(t,e,n,r){var o=R(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?pt(t):t;if(s>1)for(var c=0;c<o/a;c++)for(var l=c*a,h=0;h<a;h++)i[h]=Math.max(i[h],dt(u[l+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,u=n[0],c=n.length;if(0===c){return"complex64"===r?[dt(pt(e)[0],0,r)]:"bool"===r?[ft(e[0])]:[e[0].toString()]}if(1===c){if(u>ut){var l=ct*s,h=Array.from(e.slice(0,l)),d=Array.from(e.slice((u-ct)*s,u*s));return"complex64"===r&&(h=pt(h),d=pt(d)),["["+h.map((function(t,e){return dt(t,a[e],r)})).join(", ")+", ..., "+d.map((function(t,e){return dt(t,a[u-ct+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?pt(e):Array.from(e)).map((function(t,e){return dt(t,a[e],r)})).join(", ")+"]"]}var f=n.slice(1),p=o.slice(1),v=o[0]*s,m=[];if(u>ut){for(var g=0;g<ct;g++){var y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),f,r,p,a,!1))}m.push("...");for(g=u-ct;g<u;g++){y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),f,r,p,a,g===u-1))}}else for(g=0;g<u;g++){var x;y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),f,r,p,a,g===u-1))}var b=2===c?",":"";m[0]="["+m[0]+b;for(g=1;g<m.length-1;g++)m[g]=" "+m[g]+b;var w=",\n";for(g=2;g<c;g++)w+="\n";return m[m.length-1]=" "+m[m.length-1]+"]"+(i?"":w),m}(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 dt(t,e,n){return D(Array.isArray(t)?parseFloat(t[0].toFixed(lt))+" + "+parseFloat(t[1].toFixed(lt))+"j":V(t)?"'"+t+"'":"bool"===n?ft(t):parseFloat(t.toFixed(lt)).toString(),e)}function ft(t){return 0===t?"false":"true"}function pt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var vt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=R(t),null!=n){var o=n.length;b(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||M(e,this.size),this.strides=X(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]),b(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 mt().makeTensor(this.values,this.shape,this.dtype)},t}(),mt=null,gt=null,yt=null;var xt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=R(t),this.strides=X(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),b(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(),gt.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,gt.buffer(this.shape,this.dtype,t)]}}))}))},t.prototype.bufferSync=function(){return gt.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,$(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return $(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=mt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map((function(t){return nt(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=mt().readSync(this.dataId);if("string"===this.dtype)try{return t.map((function(t){return nt(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,mt().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||(mt().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),gt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),gt.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),gt.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),gt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),gt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),gt.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),gt.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),ht(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),gt.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),gt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),gt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),gt.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(),gt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),gt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),gt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),gt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),gt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),gt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),gt.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),gt.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),yt("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(),gt.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(),gt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),gt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),gt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),gt.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),gt.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),gt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),gt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),gt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),gt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),gt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),gt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),gt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),gt.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),gt.div(this,t)},t.prototype.divNoNan=function(t){return this.throwIfDisposed(),gt.divNoNan(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),gt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),gt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),gt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),gt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),gt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),gt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),gt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),gt.modStrict(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),gt.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),gt.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),gt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),gt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),gt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),gt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),gt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),gt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),gt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),gt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),gt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),gt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),gt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),gt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),gt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),gt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),gt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),gt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),gt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),gt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),gt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),gt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),gt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),gt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),gt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),gt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),gt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),gt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),gt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),gt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),gt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),gt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),gt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),gt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),gt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),gt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),gt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),gt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),gt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),gt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),gt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),gt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),gt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),gt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),gt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),gt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),gt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),gt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),gt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),gt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),gt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),gt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),gt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),gt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),gt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),gt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),gt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),gt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),gt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),gt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),gt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),gt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),gt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),gt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),gt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),gt.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(),gt.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(),gt.conv2d(this,t,e,n,r,o,a)},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),gt.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(),gt.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(),gt.separableConv2d(this,t,e,n,r,o,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),gt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),gt.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),gt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),gt.pool(this,t,e,n,r,o)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),mt().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),gt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),gt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),gt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),gt.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(),gt.stridedSlice(this,t,e,n,r,o,a,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),gt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),gt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),gt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),gt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),gt.spectral.irfft(this)},t}();Object.defineProperty(xt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var bt,wt,Ct,Et,Rt,It=function(t){function e(e,n,r,o){var a=t.call(this,e.shape,e.dtype,e.dataId,o)||this;return a.trainable=n,a.name=r,a}return n(e,t),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(!I(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");mt().disposeTensor(this),this.dataId=t.dataId,mt().incRef(this,null)},e.prototype.dispose=function(){mt().disposeVariable(this),this.isDisposedInternal=!0},e}(xt);Object.defineProperty(It,Symbol.hasInstance,{value:function(t){return t instanceof xt&&null!=t.assign&&t.assign instanceof Function}}),(bt=t.Rank||(t.Rank={})).R0="R0",bt.R1="R1",bt.R2="R2",bt.R3="R3",bt.R4="R4",bt.R5="R5",bt.R6="R6",function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(wt||(wt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(Ct||(Ct={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(Et||(Et={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(Rt||(Rt={}));var kt={float32:Et,int32:wt,bool:Ct,complex64:Rt};function St(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return kt[t][e]}function At(t){return St(t,"int32")}function Dt(t,e){if(t.dtype===e.dtype)return[t,e];var n=St(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Tt(t,e){b(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function Nt(t){var e=[];return function t(e,n,r){if(null==e)return;if(e instanceof xt)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 Ft,_t=Object.freeze({makeTypesMatch:Dt,assertTypesMatch:Tt,isTensorInList:function(t,e){return e.some((function(e){return e.id===t.id}))},getTensorsInContainer:Nt}),Ot=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.numDataMovesStack=[],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}(),Mt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ot}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() or await tf.setBackend() 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() or await tf.setBackend() 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.setupRegisteredKernels(),this.profiler=new it(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;d(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;d(t).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])}))},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.disposeRegisteredKernels(t),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){var n=this.state.tensorInfo.get(e),r=n.backend,o=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},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=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(function(t){return{x:function(){return t.toFloat()}}}),[]),e},t.prototype.runKernel=function(t,e,n,r,o){return this.runKernelFunc(null,e,null,t,n,r,o)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),o=0;n.forEach((function(t){o+="complex64"===t.dtype?3:1}));var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-e-o-a;if(i>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,o,a,i){var s,u=this;void 0===a&&(a=[]),void 0===i&&(i=[]);var c=[],h=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var d,f=function(t){h&&(c=t.map((function(t){return u.keep(u.clone(t))})))},p=this.state.numBytes,v=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,g=l(r,this.backendName);return d=null!=g?function(){var t=u.backend.numDataIds();m=g.kernelFunc({inputs:e,attrs:o,backend:u.backend});var n=Array.isArray(m)?m:[m];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)})),c=s.filter((function(t,e){return i[e]}));return f((a||[]).slice().concat(c)),s}:function(){var e=u.backend.numDataIds();m=u.tidy((function(){return t(u.backend,f)}));var n=Array.isArray(m)?m:[m];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n},this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return d()})):d()})),h&&this.addTapeNode(r,e,s,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-v,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(m)?s:s[0]},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var o=t;"string"===n&&V(t[0])&&(o=t.map((function(t){return et(t)})));var a=r.write(o,e,n),i=new xt(e,n,a,this.nextTensorId());if(this.incRef(i,r),"string"===n){var s=this.state.tensorInfo.get(a),u=z(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return i},t.prototype.makeTensorFromDataId=function(t,e,n,r){var o=new xt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(o,r),o},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var o=new It(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},t.prototype.incRef=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*U(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof It||this.track(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,r,o){var a=this,i={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:o},s=h(t);null!=s&&(r=s.gradFunc),null!=r&&(i.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],o=J(r.size,r.dtype);return a.makeTensor(o,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],o)}),this.state.activeTape.push(i)},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=Nt(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),b(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)}));b(a instanceof xt,(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=(p=t[a]).inputs;for(var s in i){for(var u=i[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){p.outputs.forEach((function(t){return r[t.id]=!0})),c=!0,o[p.id]=!0;break}if(c)break}}var h={};h[n.id]=!0;var d={};for(a=t.length-1;a>=0;a--)for(i=(p=t[a]).inputs,l=0;l<p.outputs.length;l++)if(h[p.outputs[l].id]){for(var s in i)h[i[s].id]=!0,d[p.id]=!0;break}var f=[];for(a=0;a<t.length;a++){var p;if(o[(p=t[a]).id]&&d[p.id]){var v={};for(var s in p.inputs){var m=p.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},p);g.inputs=v,g.outputs=p.outputs,f.push(g)}}return f}(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=Q(R(t),"float32"),Bt.makeTensor(r,t,"float32")):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];null!=n?a.push(n):a.push(null)})),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");var i=o.gradient(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.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!I(r.shape,a.shape))throw new Error("Error in gradient for op "+o.kernelName+". 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=0,n=t.saved;e<n.length;e++){n[e].dispose()}})),o.state.activeTape=null),{value:a,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return b(K(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];b(r.every((function(t){return t instanceof xt})),(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.runKernelFunc((function(e,o){return b((n=t.apply(void 0,r.concat([o]))).value instanceof xt,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),b(K(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];b(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(...)."})),b(a.every((function(t){return t instanceof xt})),(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.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.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=Z(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=Z()-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 Ot,this.registry)this.disposeRegisteredKernels(t),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 Bt=function(){var e=function(){if(null==Ft){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}Ft=t}return Ft}();if(null==e._tfengine){var n=new a(e);e._tfengine=new Mt(n)}return function(e){t.ENV=e}(e._tfengine.ENV),mt=function(){return e._tfengine},e._tfengine}();function Pt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Lt=s();Lt.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.")})),Lt.registerFlag("IS_BROWSER",(function(){return Pt()})),Lt.registerFlag("IS_NODE",(function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node})),Lt.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Lt.registerFlag("PROD",(function(){return!1})),Lt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Lt.getBool("DEBUG")})),Lt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Lt.registerFlag("IS_TEST",(function(){return!1}));var Wt,Ut,zt,Vt={},Gt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ht(t,e){Vt[t]=e}function qt(t){t in Vt||(Vt[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=function(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")}(t);if(e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Vt[t]}),!1),1===t)return e.getContext("webgl",Gt)||e.getContext("experimental-webgl",Gt);return e.getContext("webgl2",Gt)}(t));var e=Vt[t];return e.isContextLost()?(delete Vt[t],qt(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),Vt[t])}function Kt(t,e){return[e,t]}function jt(t){var e=R(t);return A(Math.ceil(e/4))}function Xt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Yt(t,e){var n,r,o,a,i,u,c,l,h,d=t;return 2===s().getNumber("WEBGL_VERSION")?(n=d.R32F,r=d.R16F,o=d.RGBA16F,a=d.RGBA32F,i=d.RED,u=4,c=1,l=d.HALF_FLOAT,h=d.FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=d.RGBA,i=t.RGBA,u=4,c=4,l=null!=e?e.HALF_FLOAT_OES:null,h=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:h}}function $t(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+te(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Wt||(Wt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Ut||(Ut={})),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"}(zt||(zt={}));var Qt=5.96e-8,Jt=65504;function Zt(t){return!!(s().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Qt<Math.abs(t)&&Math.abs(t)<Jt)}function te(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 ee(t,e,n){return Re(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function ne(t,e,n){var r=Re(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if($t(t,e,(function(){return t.shaderSource(r,n)})),$t(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 re(t,e,n){var r=Re(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if($t(t,e,(function(){return t.shaderSource(r,n)})),$t(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=ie.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 D((e+1).toString(),a)+t})),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var c=i.slice(0,r-1),l=i.slice(r-1,r),h=i.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+D(l[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 oe,ae,ie=/ERROR: [0-9]+:([0-9]+):/g;function se(t,e){return Re(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function ue(t,e,n){if($t(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 ce(t,e,n){if($t(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 le(t,e,n){var r=Re(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return $t(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),$t(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function he(t,e,n){var r=Re(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return $t(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),$t(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function de(t,e){return Re(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function fe(t,e){var n=s().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n){r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+n+"x"+n+"]")+".")}}function pe(t,e){return Re(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function ve(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&($t(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,o)})),$t(t,e,(function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)})),$t(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function me(t,e,n,r){Ie(t,r),$t(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function ge(t,e,n,r){return Re(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function ye(t,e,n){return t.getUniformLocation(e,n)}function xe(t,e,n,r,o,a){$t(t,e,(function(){return me(t,e,r,a)})),$t(t,e,(function(){return t.uniform1i(o,a)}))}function be(t,e,n,r){$t(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),$t(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function we(t,e,n){$t(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),$t(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ee(t,e))}function Ee(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 Re(t,e,n,r){var o=$t(t,e,(function(){return n()}));if(null==o)throw new Error(r);return o}function Ie(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 ke(t,e){return void 0===e&&(e=2),R(t.slice(0,t.length-e))}function Se(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 Ae(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[ke(t)].concat(Se(t))),e}function De(t,e){var n;void 0===e&&(e=!1);var r=s().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map((function(e,n){return n>=t.length-2?y(t[n]):t[n]}))).length&&(t=[2,t[0]])),2!==t.length){var o=_(t);t=o.newShape}var a=R(t);if(t.length<=1&&a<=r)return[1,a];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var i=ke(t),u=2,c=2;return t.length&&(u=(n=Se(t))[0],c=n[1]),A(a=i*(u/2)*(c/2)).map((function(t){return 2*t}))}return A(a)}function Te(t){return t%2==0}function Ne(t,e){if(I(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(Te(n)&&Te(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Te(t[0])&&Te(e[0])}function Fe(t){if(null==oe){var e=qt(t);oe=e.getParameter(e.MAX_TEXTURE_SIZE)}return oe}function _e(t){if(null==ae){var e=qt(t);ae=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ae)}function Oe(t){if(0===t)return 0;var e=qt(t);return Me(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Me(e,"EXT_disjoint_timer_query")?1:0}function Me(t,e){return null!=t.getExtension(e)}function Be(t){try{if(null!=qt(t))return!0}catch(t){return!1}return!1}function Pe(t){if(0===t)return!1;var e=qt(t);if(1===t){if(!Me(e,"OES_texture_float"))return!1}else if(!Me(e,"EXT_color_buffer_float"))return!1;return We(e)}function Le(t){if(0===t)return!1;var e=qt(t);if(1!==t){if(Me(e,"EXT_color_buffer_float"))return We(e);if(Me(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Yt(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!!Me(e,"OES_texture_float")&&(!!Me(e,"WEBGL_color_buffer_float")&&We(e))}function We(t){var e=Yt(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 Ue(t){return 2===t&&null!=qt(t).fenceSync}var ze=Object.freeze({callAndCheck:$t,canBeRepresented:Zt,getWebGLErrorMessage:te,getExtensionOrThrow:ee,createVertexShader:ne,createFragmentShader:re,createProgram:se,linkProgram:ue,validateProgram:ce,createStaticVertexBuffer:le,createStaticIndexBuffer:he,getNumChannels:function(){return 2===s().getNumber("WEBGL_VERSION")?1:4},createTexture:de,validateTextureSize:fe,createFramebuffer:pe,bindVertexBufferToProgramAttribute:ve,bindTextureUnit:me,unbindTextureUnit:function(t,e,n){Ie(t,n),$t(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:ge,getProgramUniformLocation:ye,bindTextureToProgramUniformSampler:xe,bindCanvasToFramebuffer:function(t,e){$t(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),$t(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),$t(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:be,unbindColorTextureFromFramebuffer:we,validateFramebuffer:Ce,getFramebufferErrorMessage:Ee,getBatchDim:ke,getRowsCols:Se,getShapeAs3D:Ae,getTextureShapeFromLogicalShape:De,isReshapeFree:Ne,getWebGLMaxTextureSize:Fe,resetMaxTextureSize:function(){oe=null},resetMaxTexturesInShader:function(){ae=null},getMaxTexturesInShader:_e,getWebGLDisjointQueryTimerVersion:Oe,hasExtension:Me,isWebGLVersionEnabled:Be,isCapableOfRenderingToFloatTexture:Pe,isDownloadFloatTextureEnabled:Le,isWebGLFenceEnabled:Ue}),Ve=s();function Ge(t){s().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function He(t,e){return Bt.tidy(t,e)}function qe(t){Nt(t).forEach((function(t){return t.dispose()}))}function Ke(t){return Bt.keep(t)}function je(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];s().getBool("IS_TEST")||console.warn.apply(console,t)}function Xe(t,e){var n=t;if(W(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||W(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&s().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],!Array.isArray(e)&&!W(e))return void b(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}));b(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),b(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var o=n.slice(1),a=0;a<e.length;++a)t(e[a],o,r.concat(a))}(t,r,[]),r}function Ye(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 $e(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof xt)return Ye(r,t.dtype,e,n),t;var o=q(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),Ye(r,o,e,n),null==t||!W(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=Xe(t,o);W(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?Y(t,o,s().getBool("DEBUG")):E(t,[],!0);return Bt.makeTensor(u,i,o)}function Qe(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 $e(t,e+"["+r+"]",n)}),r)}function Je(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function Ze(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 tn(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 en(t,e){return Ze(t,e.map((function(t){return 1})),e)}function nn(t,e,n){b(Je(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function rn(t,e){if(Je(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 on(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 an(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function sn(t,e){var n=t[0].length;t.forEach((function(t,e){b(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+")"}))})),b(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++)b(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 un(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function cn(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];Bt.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Bt.endScope(o),o}catch(t){throw Bt.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}Ve.registerFlag("HAS_WEBGL",(function(){return Ve.getNumber("WEBGL_VERSION")>0})),Ve.registerFlag("WEBGL_VERSION",(function(){return Be(2)?2:Be(1)?1:0})),Ve.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Ve.get("WEBGL_VERSION")})),Ve.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Ve.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Ve.registerFlag("WEBGL_PACK",(function(){return Ve.getBool("HAS_WEBGL")})),Ve.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_CLIP",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Ve.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_PACK_REDUCE",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_CONV_IM2COL",(function(){return Ve.getBool("WEBGL_PACK")})),Ve.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Fe(Ve.getNumber("WEBGL_VERSION"))})),Ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return _e(Ve.getNumber("WEBGL_VERSION"))})),Ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=Ve.getNumber("WEBGL_VERSION");return 0===t?0:Oe(t)})),Ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=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(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t})),Ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Pe(Ve.getNumber("WEBGL_VERSION"))})),Ve.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Ve.getBool("WEBGL_FORCE_F16_TEXTURES")&&Ve.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Ve.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Le(Ve.getNumber("WEBGL_VERSION"))})),Ve.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return Ue(Ve.getNumber("WEBGL_VERSION"))})),Ve.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Ve.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),yt=Ge;var ln=cn({complex_:function(t,e){var n=$e(t,"real","complex"),r=$e(e,"imag","complex");return w(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Bt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),hn=cn({real_:function(t){var e=$e(t,"input","real");return Bt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),dn=cn({imag_:function(t){var e=$e(t,"input","imag");return Bt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function fn(t,e,n){return pn(t,e,Xe(t,n),n)}function pn(t,e,n,r){if(null==r&&(r=q(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!W(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)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!=e){tt(e);var o=R(e),a=R(n);b(o===a,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a}));for(var i=0;i<n.length;++i){var u=n[i],c=i!==n.length-1||u!==R(e.slice(i));b(n[i]===e[i]||!c,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return W(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?Y(t,r,s().getBool("DEBUG")):E(t,[],!0),Bt.makeTensor(t,e,r)}function vn(t,e){if((W(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&&W(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return pn(t,[],[],e)}function mn(t,e){C(t);var n=Xe(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return pn(t,null,n,e)}function gn(t,e,n){if(C(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=Xe(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 pn(t,e,r,n)}function yn(t,e,n){if(C(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=Xe(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 pn(t,e,r,n)}function xn(t,e,n){if(C(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=Xe(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 pn(t,e,r,n)}function bn(t,e,n){if(C(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=Xe(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 pn(t,e,r,n)}function wn(t,e,n){if(C(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=Xe(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 pn(t,e=e||r,r,n)}function Cn(t,e,n,r){return void 0===e&&(e=!0),Bt.makeVariable(t,e,n,r)}function En(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=En(t,"float32"),r=Rn(t,"float32");return ln(n,r)}var o=Q(R(t),e);return Bt.makeTensor(o,t,e)}function Rn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Rn(t,"float32"),r=Rn(t,"float32");return ln(n,r)}var o=J(R(t),e);return Bt.makeTensor(o,t,e)}function In(t,e,n){return Bt.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function kn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Bt.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})}function Sn(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 Rn([0],r);var o=J(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 mn(o,r)}var An=cn({onesLike_:function(t){var e=$e(t,"x","onesLike");if("complex64"===e.dtype){var n=An(hn(e)),r=Dn(dn(e));return ln(n,r)}return Bt.runKernelFunc((function(t){return t.onesLike(e)}),{$x:e},(function(t,e){return{$x:function(){return Dn(t)}}}))}}),Dn=cn({zerosLike_:function(t){var e=$e(t,"x","zerosLike");return Bt.runKernelFunc((function(t){return t.zerosLike(e)}),{$x:e},(function(t,e){return{$x:function(){return Dn(t)}}}))}});var Tn=cn({concat_:function(t,e){void 0===e&&(e=0),b(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=Qe(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=F(e,n[0].shape)[0];var r=un(n.map((function(t){return t.shape})),e);if(0===R(r))return fn([],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}));sn(o,e);var a=n,i={axis:e};return Bt.runKernelFunc((function(t){return t.concat(n,e)}),a,(function(t){var n=o.map((function(t){return t[e]}));return Mn(t,n,e).map((function(t){return function(){return t}}))}),"Concat",i)}}),Nn=cn({concat1d_:function(t){return Tn(t,0)}}),Fn=cn({concat2d_:function(t,e){return Tn(t,e)}}),_n=cn({concat3d_:function(t,e){return Tn(t,e)}}),On=cn({concat4d_:function(t,e){return Tn(t,e)}}),Mn=cn({split_:function(t,e,n){void 0===n&&(n=0);var r,o=$e(t,"x","split");return n=F(n,o.shape)[0],"number"==typeof e?(b(o.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(o.shape[n]/e)):(b(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),Bt.runKernelFunc((function(t){return t.split(o,r,n)}),{$x:o},(function(t){return{$x:function(){return Tn(t,n)}}}))}});"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Bn(t,e){return t(e={exports:{}},e.exports),e.exports}var Pn=Bn((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()+11102230246251565e-32*(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)})),Ln=Bn((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)})),Wn=Bn((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)})),Un=Bn((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)})),zn=Bn((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)})),Vn=Bn((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)})),Gn=Bn((function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),c=n.pow(2,52),l=2*c,h=a-1;function d(t,h,d){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 f(g),b=function(){for(var t=x.g(i),e=u,n=0;t<c;)t=(t+n)*a,e*=a,n=x.g(1);for(;t>=l;)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||d||function(t,e,r,o){return o&&(o.S&&p(o,x),t.state=function(){return p(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function f(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 p(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]=d,v(n.random(),e),t.exports){t.exports=d;try{r=require("crypto")}catch(t){}}}([],Math)}));Gn.alea=Pn,Gn.xor128=Ln,Gn.xorwow=Wn,Gn.xorshift7=Un,Gn.xor4096=zn,Gn.tychei=Vn;var Hn=Gn.alea,qn=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=Hn(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}(),Kn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=Hn(o.toString()),this.randn=new qn(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}(),jn=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=Hn(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 Xn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",tt(t),new vt(t,e,n)}function Yn(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var $n=cn({batchToSpaceND_:function(t,e,n){var r=$e(t,"x","batchToSpaceND"),o=e.reduce((function(t,e){return t*e}));return b(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),b(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length  "+e.length})),b(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})),Bt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),Qn=cn({broadcastTo_:function(t,e){var n=$e(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.length<n.rank)throw new Error("broadcastTo(): shape.length="+e.length+" < input.rank="+n.rank+".");if(e.length>n.rank){for(var o=n.shape.slice();o.length<e.length;)o.unshift(1);n=n.reshape(o)}for(var a=Array.from(e),i=e.length-1;i>=0;i--)if(n.shape[i]===e[i])a[i]=1;else if(1!==n.shape[i])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var s=a.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));return 0===s.length?n.clone():Bt.runKernelFunc((function(t){return t.tile(n,a)}),{input:n},(function(t){return{input:function(){return t.sum(s,!0)}}}))}}),Jn=cn({cast_:function(t,e){var n=$e(t,"x","cast");if(!P(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");var r={dtype:e};return Bt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),Zn=cn({clone_:function(t){var e=$e(t,"x","clone",null);return Bt.runKernelFunc((function(){return Bt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{$x:e},(function(t){return{$x:function(){return t.toFloat()}}}))}}),tr=cn({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=$e(t,"x","cumsum"),a=rn([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=an(1,o.rank)[0],u=Bt.runKernelFunc((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}}),er=cn({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=$e(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 b(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})),b(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})),b(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})),Bt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),nr=cn({expandDims_:function(t,e){void 0===e&&(e=0);var n=$e(t,"x","expandDims",null);b(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(b(-(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),vr(n,r)}}),rr=cn({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=Xn([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 xr(nr(s,0),[n[0],1,1]);if(2===n.length)return xr(nr(nr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return xr(nr(nr(nr(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.")}}),or=cn({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=$e(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=Bt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===i?u.as1D():u}}),ar=cn({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=$e(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),Bt.runKernelFunc((function(t){return t.oneHot(o,e,n,r)}),{$indices:o},(function(t){return{$indices:function(){return Rn(o.shape,"float32")}}})).reshape(a)}}),ir=cn({pad_:function(t,e,n){void 0===n&&(n=0);var r=$e(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:e,constantValue:n};return Bt.runKernelFunc((function(t){return t.pad(r,e,n)}),{x:r},(function(t){var n=e.map((function(t){return t[0]}));return{x:function(){return t.slice(n,r.shape)}}}),"PadV2",o)}}),sr=cn({pad1d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),ir(t,[e],n)}}),ur=cn({pad2d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),ir(t,e,n)}}),cr=cn({pad3d_:function(t,e,n){return void 0===n&&(n=0),b(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."})),ir(t,e,n)}}),lr=cn({pad4d_:function(t,e,n){return void 0===n&&(n=0),b(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."})),ir(t,e,n)}}),hr=cn({rand_:function(t,e,n){var r=R(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 Bt.makeTensor(o,t,n)}}),dr=cn({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 qn(e,n,r,!1,o),i=Xn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),fr=cn({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 Kn(e,n,r,o),i=Xn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),pr=cn({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=Xn(t,r),i=new jn(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),vr=cn({reshape_:function(t,e){var n=$e(t,"x","reshape",null);e=N(e,n.size),b(n.size===R(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Bt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),mr=cn({spaceToBatchND_:function(t,e,n){var r=$e(t,"x","spaceToBatchND");return b(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),b(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),b(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()})),Bt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),gr=cn({squeeze_:function(t,e){var n=$e(t,"x","squeeze");return vr(n,_(n.shape,e).newShape)}}),yr=cn({stack_:function(t,e){void 0===e&&(e=0);var n=Qe(t,"tensors","stack");if(b(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;b(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){w(o,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){b(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 Tn(i,e)}}),xr=cn({tile_:function(t,e){var n=$e(t,"x","tile",null);b(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],o={reps:e};return Bt.runKernelFunc((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=Dn(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}}}),"Tile",o,r)}}),br=cn({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 qn(e,n,r,!0,o),i=Xn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),wr=cn({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=$e(t,"x","unstack");b(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);var r={axis:e};return Bt.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return yr(t,e)}}}),"Unpack",r)}}),Cr=function(t,e){return r(this,void 0,void 0,(function(){var n,r,a,i,s,u,c,l,h,d;return o(this,(function(o){switch(o.label){case 0:return n=$e(t,"x","setdiff1d"),r=$e(e,"y","setdiff1d"),b(n.dtype===r.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."})),b(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),b(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(c=new vt([u],n.dtype),l=new vt([u],"int32"),h=0,d=0;h<a.length;h++)s.has(a[h])||(c.values[d]=a[h],l.values[d]=h,d++);return[2,[c.toTensor(),l.toTensor()]]}}))}))};function Er(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 Rr(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 Ir(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 kr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function Sr(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 Ar(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 c=X(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,o,u,c]}var Dr=Object.freeze({prepareAndValidate:Ar}),Tr=30;function Nr(t){return t<=Tr?t:j(t,Math.floor(Math.sqrt(t)))}function Fr(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]+")")}function _r(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)}Fr(n,e,t)}function Or(t,e,n){for(var r=e.shape.length,o=r>1?e.shape[r-1]:1,a=n.length,i=1,s=o;s<a;++s)i*=n[s];var u=o<1?1:o;return{sliceRank:o,numUpdates:R(e.shape)/u,sliceSize:i,strides:X(n.slice(0,o)).concat([1]),outputSize:R(n)}}var Mr=Object.freeze({validateUpdateShape:Fr,validateInput:_r,calculateShapes:Or});function Br(t,e,n){b(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+")."})),b(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){b(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)}function Pr(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function Lr(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 Wr(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=g(0,a,s-1)}function Ur(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?g(0,a,s):g(-1,a,s-1)}function zr(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 Vr(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}var Gr=Object.freeze({assertParamsValid:Br,maskToAxes:Pr,computeOutShape:Lr,startForAxis:Wr,stopForAxis:Ur,isSliceContinous:zr,computeFlatOffset:Vr});function Hr(t,e){b(K(t),(function(){return"The f passed in variableGrads(f) must be a function"})),b(null==e||Array.isArray(e)&&e.every((function(t){return t instanceof It})),(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=[],Bt.registeredVariables)e.push(Bt.registeredVariables[r]);var o=n?e.filter((function(t){return!t.trainable})):null,a=e.length;b((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=Bt.gradients(t,e,null,!0),s=i.value,u=i.grads;b(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()."})),b(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var c={};return e.forEach((function(t,e){null!=u[e]&&(c[t.name]=u[e])})),null!=o&&o.forEach((function(t){return c[t.name]=null})),{value:s,grads:c}}function qr(t){return Bt.customGrad(t)}function Kr(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 jr=cn({softmax_:function(t,e){void 0===e&&(e=-1);var n=$e(t,"logits","softmax","float32");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 Bt.runKernelFunc((function(t,r){var o=t.softmax(n,e);return r([o]),o}),{logits:n},(function(t,n){var r=n[0],o=t.mul(r);return{logits:function(){return o.sub(o.sum([e],!0).mul(r))}}}),"Softmax",{dim:e},[],[!0])}}),Xr=cn({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=$e(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 qr((function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());n([a]);return{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),Yr=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}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.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),$r=function(){function t(){}return t.prototype.time=function(t){return Qr("time")},t.prototype.read=function(t){return Qr("read")},t.prototype.readSync=function(t){return Qr("readSync")},t.prototype.numDataIds=function(){return Qr("numDataIds")},t.prototype.disposeData=function(t){return Qr("disposeData")},t.prototype.write=function(t,e,n){return Qr("write")},t.prototype.move=function(t,e,n,r){return Qr("move")},t.prototype.memory=function(){return Qr("memory")},t.prototype.floatPrecision=function(){return Qr("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return Qr("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights;return Qr("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return Qr("slice")},t.prototype.stridedSlice=function(t,e,n,r){return Qr("stridedSlice")},t.prototype.unstack=function(t,e){return Qr("unstack")},t.prototype.reverse=function(t,e){return Qr("reverse")},t.prototype.concat=function(t,e){return Qr("concat")},t.prototype.neg=function(t){return Qr("neg")},t.prototype.add=function(t,e){return Qr("add")},t.prototype.addN=function(t){return Qr("addN")},t.prototype.subtract=function(t,e){return Qr("subtract")},t.prototype.multiply=function(t,e){return Qr("multiply")},t.prototype.realDivide=function(t,e){return Qr("realDivide")},t.prototype.floorDiv=function(t,e){return Qr("floorDiv")},t.prototype.sum=function(t,e){return Qr("sum")},t.prototype.prod=function(t,e){return Qr("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return Qr("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return Qr("argMin")},t.prototype.argMax=function(t,e){return Qr("argMax")},t.prototype.equal=function(t,e){return Qr("equal")},t.prototype.notEqual=function(t,e){return Qr("notEqual")},t.prototype.less=function(t,e){return Qr("less")},t.prototype.lessEqual=function(t,e){return Qr("lessEqual")},t.prototype.greater=function(t,e){return Qr("greater")},t.prototype.greaterEqual=function(t,e){return Qr("greaterEqual")},t.prototype.logicalNot=function(t){return Qr("logicalNot")},t.prototype.logicalAnd=function(t,e){return Qr("logicalAnd")},t.prototype.logicalOr=function(t,e){return Qr("logicalOr")},t.prototype.where=function(t){return Qr("where")},t.prototype.select=function(t,e,n){return Qr("select")},t.prototype.topk=function(t,e,n){return Qr("topk")},t.prototype.min=function(t,e){return Qr("min")},t.prototype.minimum=function(t,e){return Qr("minimum")},t.prototype.mod=function(t,e){return Qr("mod")},t.prototype.max=function(t,e){return Qr("max")},t.prototype.maximum=function(t,e){return Qr("maximum")},t.prototype.all=function(t,e){return Qr("all")},t.prototype.any=function(t,e){return Qr("any")},t.prototype.squaredDifference=function(t,e){return Qr("squaredDifference")},t.prototype.ceil=function(t){return Qr("ceil")},t.prototype.floor=function(t){return Qr("floor")},t.prototype.round=function(t){return Qr("round")},t.prototype.sign=function(t){return Qr("sign")},t.prototype.isNaN=function(t){return Qr("isNaN")},t.prototype.isInf=function(t){return Qr("isInf")},t.prototype.isFinite=function(t){return Qr("isFinite")},t.prototype.pow=function(t,e){return Qr("pow")},t.prototype.exp=function(t){return Qr("exp")},t.prototype.expm1=function(t){return Qr("expm1")},t.prototype.softmax=function(t,e){return Qr("softmax")},t.prototype.log=function(t){return Qr("log")},t.prototype.log1p=function(t){return Qr("log1p")},t.prototype.sqrt=function(t){return Qr("sqrt")},t.prototype.rsqrt=function(t){return Qr("rsqrt")},t.prototype.square=function(t){return Qr("square")},t.prototype.reciprocal=function(t){return Qr("reciprocal")},t.prototype.relu=function(t){return Qr("relu")},t.prototype.relu6=function(t){return Qr("relu6")},t.prototype.prelu=function(t,e){return Qr("prelu")},t.prototype.elu=function(t){return Qr("elu")},t.prototype.eluDer=function(t,e){return Qr("eluDer")},t.prototype.selu=function(t){return Qr("selu")},t.prototype.int=function(t){return Qr("int")},t.prototype.clip=function(t,e,n){return Qr("clip")},t.prototype.abs=function(t){return Qr("abs")},t.prototype.complexAbs=function(t){return Qr("complexAbs")},t.prototype.sigmoid=function(t){return Qr("sigmoid")},t.prototype.softplus=function(t){return Qr("softplus")},t.prototype.sin=function(t){return Qr("sin")},t.prototype.cos=function(t){return Qr("cos")},t.prototype.tan=function(t){return Qr("tan")},t.prototype.asin=function(t){return Qr("asin")},t.prototype.acos=function(t){return Qr("acos")},t.prototype.atan=function(t){return Qr("atan")},t.prototype.atan2=function(t,e){return Qr("atan2")},t.prototype.sinh=function(t){return Qr("sinh")},t.prototype.cosh=function(t){return Qr("cosh")},t.prototype.tanh=function(t){return Qr("tanh")},t.prototype.asinh=function(t){return Qr("asinh")},t.prototype.acosh=function(t){return Qr("acosh")},t.prototype.atanh=function(t){return Qr("atanh")},t.prototype.erf=function(t){return Qr("erf")},t.prototype.step=function(t,e){return Qr("step")},t.prototype.fusedConv2d=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return Qr("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return Qr("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return Qr("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return Qr("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return Qr("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return Qr("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return Qr("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return Qr("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return Qr("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return Qr("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return Qr("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return Qr("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return Qr("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return Qr("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return Qr("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return Qr("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return Qr("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return Qr("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return Qr("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return Qr("reshape")},t.prototype.cast=function(t,e){return Qr("cast")},t.prototype.tile=function(t,e){return Qr("tile")},t.prototype.pad=function(t,e,n){return Qr("pad")},t.prototype.transpose=function(t,e){return Qr("transpose")},t.prototype.gather=function(t,e,n){return Qr("gather")},t.prototype.gatherND=function(t,e){return Qr("gatherND")},t.prototype.scatterND=function(t,e,n){return Qr("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return Qr("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return Qr("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return Qr("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return Qr("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return Qr("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return Qr("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,o,a){return Qr("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){return Qr("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){return Qr("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return Qr("multinomial")},t.prototype.oneHot=function(t,e,n,r){return Qr("oneHot")},t.prototype.cumsum=function(t,e,n,r){return Qr("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return Qr("nonMaxSuppression")},t.prototype.fft=function(t){return Qr("fft")},t.prototype.ifft=function(t){return Qr("ifft")},t.prototype.complex=function(t,e){return Qr("complex")},t.prototype.real=function(t){return Qr("real")},t.prototype.imag=function(t){return Qr("imag")},t.prototype.cropAndResize=function(t,e,n,r,o,a){return Qr("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return Qr("depthToSpace")},t.prototype.split=function(t,e,n){return Qr("split")},t.prototype.sparseToDense=function(t,e,n,r){return Qr("sparseToDense")},t.prototype.diag=function(t){return Qr("diag")},t.prototype.fill=function(t,e,n){return Qr("fill")},t.prototype.onesLike=function(t){return Qr("onesLike")},t.prototype.zerosLike=function(t){return Qr("zerosLike")},t.prototype.linspace=function(t,e,n){return Qr("linspace")},t.prototype.dispose=function(){return Qr("dispose")},t}();function Qr(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function Jr(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 Zr(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 to(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 eo(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=io(e),c=u[0],l=u[1];if("channelsLast"===i)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[c,l,t[1],t[1]]}return ro(t,s,n,r,o,a,!1,i)}function no(t,e,n,r,o,a,i){void 0===i&&(i="NDHWC");var s,u,c=so(e),l=c[0],h=c[1],d=c[2];if("NDHWC"===i)u="channelsLast",s=[l,h,d,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,h,d,t[1],t[1]]}return oo(t,s,n,r,o,!1,u,a)}function ro(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],d=u[3];if("channelsLast"===s)c=t[0],l=t[1],h=t[2],d=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],d=t[1],l=t[2],h=t[3]}var f,p=e[0],v=e[1],m=e[3],g=io(n),y=g[0],x=g[1],w=io(r),C=w[0],E=w[1],R=uo(p,C),I=uo(v,E),S=function(t,e,n,r,o,a,i,s){var u,c,l;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var h=function(t,e,n,r,o){null==r&&(r=ao(t,e,n));var a=t[0],i=t[1],s=co((a-e+2*r)/n+1,o);b(k(s),(function(){return"The output # of rows ("+s+") must be an integer. Change the stride and/or zero pad parameters"}));var u=co((i-e+2*r)/n+1,o);return b(k(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);c=h[0],l=h[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/o);var d=Math.max(0,(c-1)*r+a-e),f=Math.max(0,(l-1)*o+i-n),p=Math.floor(d/2),v=d-p,m=Math.floor(f/2);u={top:p,bottom:v,left:m,right:f-m,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-a+1)/r),l=Math.ceil((n-i+1)/o)}return{padInfo:u,outHeight:c,outWidth:l}}(o,l,h,y,x,R,I,a),A=S.padInfo,D=S.outHeight,T=S.outWidth,N=i?m*d:m;return"channelsFirst"===s?f=[c,N,D,T]:"channelsLast"===s&&(f=[c,D,T,N]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:h,inChannels:d,outHeight:D,outWidth:T,outChannels:N,padInfo:A,strideHeight:y,strideWidth:x,filterHeight:p,filterWidth:v,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:C,dilationWidth:E,inShape:t,outShape:f,filterShape:e}}function oo(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],c=u[0],l=u[1],h=u[2],d=u[3],f=u[4];if("channelsLast"===i)c=t[0],l=t[1],h=t[2],d=t[3],f=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);c=t[0],f=t[1],l=t[2],h=t[3],d=t[4]}var p,v=e[0],m=e[1],g=e[2],y=e[4],x=so(n),w=x[0],C=x[1],E=x[2],R=so(r),I=R[0],S=R[1],A=R[2],D=uo(v,I),T=uo(m,S),N=uo(g,A),F=function(t,e,n,r,o,a,i,s,u,c,l){var h,d,f,p;if("number"==typeof t){h={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var v=function(t,e,n,r,o,a){null==o&&(o=ao(t,e,r));var i=t[0],s=t[1],u=t[2],c=co((i-e+2*o)/r+1,a);b(k(c),(function(){return"The output # of depths ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var l=co((s-e+2*o)/r+1,a);b(k(l),(function(){return"The output # of rows ("+l+") must be an integer. Change the stride and/or zero pad parameters"}));var h=co((u-e+2*o)/r+1,a);return b(k(h),(function(){return"The output # of columns ("+h+") must be an integer. Change the stride and/or zero pad parameters"})),[c,l,h,n]}([e,n,r,1],s,1,o,t,l);d=v[0],f=v[1],p=v[2]}else if("same"===t){d=Math.ceil(e/o),f=Math.ceil(n/a),p=Math.ceil(r/i);var m=(d-1)*o+s-e,g=(f-1)*a+u-n,y=(p-1)*i+c-r,x=Math.floor(m/2),w=m-x,C=Math.floor(g/2),E=g-C,R=Math.floor(y/2);h={top:C,bottom:E,left:R,right:y-R,front:x,back:w,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"},d=Math.ceil((e-s+1)/o),f=Math.ceil((n-u+1)/a),p=Math.ceil((r-c+1)/i)}return{padInfo:h,outDepth:d,outHeight:f,outWidth:p}}(o,l,h,d,w,C,E,D,T,N,s),_=F.padInfo,O=F.outDepth,M=F.outHeight,B=F.outWidth,P=a?y*f:y;return"channelsFirst"===i?p=[c,P,O,M,B]:"channelsLast"===i&&(p=[c,O,M,B,P]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:h,inWidth:d,inChannels:f,outDepth:O,outHeight:M,outWidth:B,outChannels:P,padInfo:_,strideDepth:w,strideHeight:C,strideWidth:E,filterDepth:v,filterHeight:m,filterWidth:g,effectiveFilterDepth:D,effectiveFilterHeight:T,effectiveFilterWidth:N,dilationDepth:I,dilationHeight:S,dilationWidth:A,inShape:t,outShape:p,filterShape:e}}function ao(t,e,n,r){void 0===r&&(r=1);var o=uo(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function io(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function so(t){return"number"==typeof t?[t,t,t]:t}function uo(t,e){return e<=1?t:t+(t-1)*(e-1)}function co(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 lo(t){var e=io(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function ho(t,e){return lo(t)||lo(e)}function fo(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function po(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Rn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a}if(!L(t.dtype,e))return Bt.makeTensorFromDataId(t.dataId,t.shape,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=vn(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 vo(t,e){return Bt.makeTensorFromDataId(t.dataId,e,t.dtype)}function mo(t,e,n){var r=(e-t)/(n-1),o=J(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return mn(o,"float32")}var go=Object.freeze({castTensor:po,reshapeTensor:vo,linspaceImpl:mo,upcastType:St,axesAreInnerMostDims:Je,combineLocations:Ze,computeOutAndReduceShapes:tn,expandShapeToKeepDim:en,assertAxesAreInnerMostDims:nn,getAxesPermutation:rn,getUndoAxesPermutation:on,getInnerMostAxes:an,getBroadcastDims:Jr,getReductionAxes:Zr,assertAndGetBroadcastShape:to,assertParamsConsistent:sn,computeOutShape:un,computePool2DInfo:eo,computePool3DInfo:no,computeConv2DInfo:ro,computeConv3DInfo:oo,computeDefaultPad:ao,tupleValuesAreOne:lo,eitherStridesOrDilationsAreOne:ho,convertConv2DDataFormat:fo,PARALLELIZE_THRESHOLD:Tr,computeOptimalWindowSize:Nr});function yo(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 xo(t,e){return{real:t[2*e],imag:t[2*e+1]}}function bo(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function wo(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Co(t,e,n){var r=function(t,e,n){return function(t,e,n){var r=0,o=t.length,a=0,i=!1;for(;r<o;){var s=n(e,t[a=r+(o-r>>>1)]);s>0?r=a+1:(o=a,i=!s)}return i?r:-r-1}(t,e,n||Eo)}(t,e,n),o=r<0?-(r+1):r;t.splice(o,0,e)}function Eo(t,e){return t>e?1:t<e?-1:0}function Ro(t,e,n,r,o){return ko(t,e,n,r,o,0).selectedIndices}function Io(t,e,n,r,o,a){var i=ko(t,e,n,r,o,a,!0);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function ko(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1);for(var u=Array.from(e).map((function(t,e){return{score:t,boxIndex:e,suppressBeginIndex:0}})).filter((function(t){return t.score>o})).sort(Do),c=a>0?-.5/a:0,l=[],h=[];l.length<n&&u.length>0;){var d=u.pop(),f=d.score,p=d.boxIndex,v=d.suppressBeginIndex;if(f<o)break;for(var m=!1,g=l.length-1;g>=v;--g){var y=So(t,p,l[g]);if(y>=r){m=!0;break}if(d.score=d.score*Ao(r,c,y),d.score<=o)break}d.suppressBeginIndex=l.length,m||(d.score===f?(l.push(p),h.push(d.score)):d.score>o&&Co(u,d,Do))}var x=l.length;return s&&(l.fill(0,x),h.fill(0,x)),{selectedIndices:mn(l,"int32"),selectedScores:mn(h,"float32"),numValidOutputs:vn(x,"int32")}}function So(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]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),d=Math.max(o[1],o[3]),f=(s-a)*(u-i),p=(h-c)*(d-l);if(f<=0||p<=0)return 0;var v=Math.max(a,c),m=Math.max(i,l),g=Math.min(s,h),y=Math.min(u,d),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(f+p-x)}function Ao(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Do(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function To(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 No(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=Xn(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 Fo(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],c=O(n,s*r),l=O("int32",s*r),h=0;h<s;h++){for(var d=h*u,f=t.subarray(d,d+u),p=[],v=0;v<f.length;v++)p.push({value:f[v],index:v});p.sort((function(t,e){return e.value-t.value}));var m=h*r,g=c.subarray(m,m+r),y=l.subarray(m,m+r);for(v=0;v<r;v++)g[v]=p[v].value,y[v]=p[v].index}var x=e.slice();return x[x.length-1]=r,[fn(c,x,n),fn(l,x,"int32")]}function _o(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=Xn(t,"int32"),a=Xn([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 Oo=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    "},Mo=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!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    "},Bo=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 Lo(t,e){return 1===e?[t]:Po(t,e)}function Wo(){var t,e,n,r,o,a,i,u,c,l;return 2===s().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",i="out vec4 outputColor;",u="\n      bool isnan_custom(float val) {\n        return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n      }\n\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan_custom(val.x),\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n      }\n\n      #define isnan(value) isnan_custom(value)\n    ",c="",l="\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    "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",i="",u="\n      #define isnan(value) isnan_custom(value)\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n      }\n    ",c="\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    ",l="\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:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:u,defineSpecialInf:c,defineRound:l}}function Uo(t,e,n){void 0===n&&(n="index");var r=X(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 zo(t){var e=X(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 Vo="\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 Go(t,e,n,r){var o=[];t.forEach((function(t){var e=R(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?qo(t):Ho(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=Jr(t.shapeInfo.logicalShape,e.logicalShape),c=Jo(s),l=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+l]+" = 0;"})).join("\n");var d="";d=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+l]})).join(", ");var f="return outputValue;",p=1===R(t.shapeInfo.logicalShape),v=1===R(e.logicalShape);if(1!==i||p||v){if(p&&!v)f=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,g=i-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?f="return vec4(outputValue.x);":u.indexOf(m)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return"\n    vec4 "+a+"() {\n      "+c+" coords = getOutputCoords();\n      "+n+"\n      vec4 outputValue = get"+o+"("+d+");\n      "+f+"\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&&I(i,a))return"\n      float "+o+"() {\n        return sampleTexture("+n+", resultUV);\n      }\n    ";var c,l=Jo(u),h=Jr(t.shapeInfo.logicalShape,e.logicalShape),d=u-s,f=["x","y","z","w","u","v"];c=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map((function(t){return"coords."+f[t+d]+" = 0;"})).join("\n");var p="";p=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+f[e+d]})).join(", ");return"\n    float "+o+"() {\n      "+l+" coords = getOutputCoords();\n      "+c+"\n      return get"+r+"("+p+");\n    }\n  "}(t,e));return r}(t,e,r)})).join("\n"),c=e.texShape,l=Wo(),h=function(t){return"\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+t.texture2D+"(textureSampler, uv).r;\n    }\n  "}(l),d=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    "+t.defineSpecialNaN+"\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    "+Ko+"\n    "+jo+"\n    "+Xo+"\n  "}(l);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(I(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,c),i=function(t){return"\n    void setOutput(vec4 val) {\n      "+t.output+" = val;\n    }\n  "}(l)):(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(I(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=Uo(["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=Uo(["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=Uo(["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=Uo(["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,c),i=function(t){return"\n    void setOutput(float val) {\n      "+t.output+" = vec4(val, 0, 0, 0);\n    }\n  "}(l)),r&&(d+=Yo),[d,h,i,s,a,u,n].join("\n")}function Ho(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],c=$o(e);return"\n    float "+n+"() {\n      vec2 uv = uvFromFlat("+s+", "+u+", "+c+");\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        "+Qo(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=$o(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&&I(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=_(e),u=s.newShape,c=s.keptDims,l=u;if(l.length<e.length){var h=Zo(t,l);return"\n      "+Ho(h)+"\n      float "+r+"(int row, int col) {\n        return "+r+"("+ta(["row","col"],c)+");\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        "+Qo(t)+"\n      }\n    ";var d=o[0],f=o[1],p=$o(n);if(1===f)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+d+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";if(1===d)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+f+".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 + "+p+";\n    vec2 uv = uvFromFlat("+d+", "+f+", 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=_(e),s=i.newShape,u=i.keptDims,c=s;if(c.length<e.length){var l=Zo(t,c);return"\n        "+Ho(l)+"\n        float "+r+"(int row, int col, int depth) {\n          return "+r+"("+ta(["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        "+Qo(t)+"\n      }\n    ";var h=t.shapeInfo.texShape,d=h[0],f=h[1],p=t.shapeInfo.flatOffset;if(f===o&&null==p)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("+f+".0, "+d+".0);\n          return sampleTexture("+n+", uv);\n        }\n      ";if(f===a&&null==p)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("+f+".0, "+d+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";var v=$o(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("+d+", "+f+", 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=_(e),u=s.newShape,c=s.keptDims;if(u.length<e.length){var l=Zo(t,u);return"\n      "+Ho(l)+"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        return "+r+"("+ta(["row","col","depth","depth2"],c)+");\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        "+Qo(t)+"\n      }\n    ";var h=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,f=d[0],p=d[1];if(p===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("+p+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(p===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("+p+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var v=$o(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("+f+", "+p+", 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=_(e),c=u.newShape,l=u.keptDims;if(c.length<e.length){var h=Zo(t,c);return"\n      "+Ho(h)+"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+r+"("+ta(["row","col","depth","depth2","depth3"],l)+");\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        "+Qo(t)+"\n      }\n    ";var d=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,p=f[0],v=f[1];if(v===s&&null==d)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, "+p+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(v===o&&null==d)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, "+p+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var m=$o(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("+p+", "+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=_(e),a=o.newShape,i=o.keptDims;if(a.length<e.length){var s=Zo(t,a);return"\n      "+Ho(s)+"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+r+"("+ta(["row","col","depth","depth2","depth3","depth4"],i)+");\n      }\n    "}var u=e[5],c=e[4]*u,l=e[3]*c,h=e[2]*l,d=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("+d+", "+h+", "+l+", "+c+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+u+", 1)));\n        "+Qo(t)+"\n      }\n    ";var f=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,v=p[0],m=p[1];if(m===d&&null==f)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+", "+l+", "+c+", "+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==f)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=$o(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 * "+d+" + col * "+h+" + depth * "+l+" +\n          depth2 * "+c+" + 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 qo(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=Wo(),"\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=Wo();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=Wo();if(null!=o&&I(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)],c=Math.ceil(e[1]/2);return"\n    vec4 "+r+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+c+", "+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=Zo(t,i);return"\n        "+qo(s)+"\n        vec4 "+r+"(int b, int row, int col) {\n          return "+r+"("+ta(["b","row","col"],[1,2])+");\n        }\n      "}var u=a[0],c=a[1],l=Math.ceil(e[2]/2),h=l*Math.ceil(e[1]/2),d=Wo();return"\n    vec4 "+r+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+u+", "+c+", "+h+", "+l+", b, row, col);\n      return "+d.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],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),h="int b, int row, int col",d="b * "+l+" + (row / 2) * "+c+" + (col / 2)",f=2;f<n-1;f++)h="int b"+f+", "+h,l*=e[n-f-1],d="b"+f+" * "+l+" + "+d;var p=Wo();return"\n    vec4 "+o+"("+h+") {\n      int index = "+d+";\n      int texR = index / "+u+";\n      int texC = index - texR * "+u+";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n      return "+p.texture2D+"("+r+", uv);\n    }\n  "}(t)}}var Ko="\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",jo="\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",Xo="\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",Yo="\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 $o(t){return"offset"+t}function Qo(t){var e=t.name,n=R(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 Jo(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 Zo(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function ta(t,e){return e.map((function(e){return t[e]})).join(", ")}var ea=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,b(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,c=u.length,l=Jo(c),h=Lo("coords",c);if(1===a){var d=Jo(s=c+1);i="\n        "+d+" sourceLocR = "+d+"("+h.join()+", 0);\n        ++"+h[c-1]+";\n        "+d+" sourceLocG = "+d+"("+h.join()+", 0);\n        ++"+h[c-2]+";\n        "+d+" sourceLocA = "+d+"("+h.join()+", 0);\n        --"+h[c-1]+";\n        "+d+" sourceLocB = "+d+"("+h.join()+", 0);\n        --"+h[c-2]+";"}else s=c,i="\n        "+l+" sourceLocR = coords;\n        ++"+h[c-1]+";\n        "+l+" sourceLocG = coords;\n        ++"+h[c-2]+";\n        "+l+" sourceLocA = coords;\n        --"+h[c-1]+";\n        "+l+" sourceLocB = coords;\n        --"+h[c-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),p="."+f[s-1],v=f.map((function(t){return"int "+t})),m=Lo("sourceLocR",s-1).concat("inIdx.r"),g=Lo("sourceLocG",s-1).concat("inIdx.g"),y=Lo("sourceLocB",s-1).concat("inIdx.b"),x=Lo("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n                             getBestIndicesAChannel("+g.join()+"),\n                             getBestIndicesAChannel("+y.join()+"),\n                             getBestIndicesAChannel("+x.join()+")));",E="vec4(\n            getAChannel("+m.join()+"),\n            hasNextCol ? getAChannel("+g.join()+") : 0.,\n            hasNextRow ? getAChannel("+y.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",R=r?"":"\n      float getBestIndicesAChannel("+v.join()+") {\n        return getChannel(getBestIndicesA("+f.join()+"),\n                                          vec2("+f.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+v.join()+") {\n        return getChannel(getA("+f.join()+"),\n                               vec2("+f.slice(-2).join()+"));\n      }\n      "+R+"\n      void main() {\n        "+l+" coords = getOutputCoords();\n        bool hasNextCol = "+h[c-1]+" < "+(u[c-1]-1)+";\n        bool hasNextRow = "+h[c-2]+" < "+(u[c-2]-1)+";\n        "+i+"\n        ivec4 srcIdx = ivec4(sourceLocR"+p+", sourceLocG"+p+",\n          sourceLocB"+p+", sourceLocA"+p+") * "+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    "},na=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,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n      const ivec2 pads = ivec2("+c+", "+l+");\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    "},ra=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,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=l-1-t.padInfo.front,p=h-1-t.padInfo.top,v=d-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n      const ivec3 pads = ivec3("+f+", "+p+", "+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 < "+l+";\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 < "+d+";\n                wC += "+c+") {\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    "},oa=function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],to(t,e),to(t,n);var i="0.0";null!=r&&(to(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(to(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    "},aa=function(t,e,n,r,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],to(t,e),to(t,n);var i="vec4(0.0)";null!=r&&(to(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(to(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    "},ia="return areal * breal - aimag * bimag;",sa="return areal * bimag + aimag * breal;",ua=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=to(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    "},ca="return a + b;",la="return a - b;",ha="return a * b;",da="return (a < 0.) ? b * a : a;",fa=function(t,e,n){this.variableNames=["A","B"],this.outputShape=to(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    "},pa="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",va=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=to(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===R(this.outputShape))a="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else if(a="\n          "+Jo(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=Lo("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    "},ma=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}(),ga=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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}(),ya=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    "},xa=function(t){this.outputShape=[],this.outputShape=un(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    "},ba=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=un(t,e);var n=this.outputShape,r=n.length,o=Jo(r),a=Lo("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 c=i[e],l=i.slice(-2),h=i.join(),d="if ("+c+" < "+s[0]+") {\n        return getChannel(\n            getT0("+h+"), vec2("+l.join()+"));\n        }";for(u=1;u<s.length;u++){var f=s[u-1];d+="\n        if ("+c+" < "+s[u]+"  && "+c+" >= "+s[u-1]+") {\n          return getChannel(\n            getT"+u+"("+wa(i,c,f)+"),\n            vec2("+wa(l,c,f)+"));\n        }"}var p=s.length,v=s[s.length-1];d+="\n        return getChannel(\n          getT"+p+"("+wa(i,c,v)+"),\n          vec2("+wa(l,c,v)+"));",this.userCode="\n      float getValue("+i.map((function(t){return"int "+t}))+") {\n        "+d+"\n      }\n\n      void main() {\n        "+o+" coords = getOutputCoords();\n        vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n        "+a[r-1]+" = "+a[r-1]+" + 1;\n        if ("+a[r-1]+" < "+n[r-1]+") {\n          result.g = getValue("+a+");\n        }\n\n        "+a[r-2]+" = "+a[r-2]+" + 1;\n        if ("+a[r-2]+" < "+n[r-2]+") {\n          result.a = getValue("+a+");\n        }\n\n        "+a[r-1]+" = "+a[r-1]+" - 1;\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    "};function wa(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var Ca=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    "},Ea=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,c=a?2:3,l=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["+l+"];\n\n        ivec2 dyCorner = ivec2(coords["+u+"], coords["+c+"]) - 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    "},Ra=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    "},Ia=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,c=r-1-t.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+s+", "+u+", "+c+");\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    "},ka=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    "},Sa=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    "},Aa=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,c=t.dilationWidth,l=t.filterHeight,h=t.filterWidth,d=4*Math.floor(t.inChannels/4),f=t.inChannels%4,p="channelsLast"===t.dataFormat,v=p?1:2,m=p?2:3,g=p?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 < "+l+"; 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 * "+c+";\n\n            if (xC < 0 || xC >= "+t.inWidth+") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < "+d+"; 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 ("+p+") {\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===f)+") {\n\n              if ("+p+") {\n                dotProd +=\n                    getX(batch, xR, xC, "+d+") *\n                    getW(wR, wC, "+d+", d2);\n              } else {\n                dotProd +=\n                    getX(batch, "+d+", xR, xC) *\n                    getW(wR, wC, "+d+", d2);\n              }\n\n            } else if ("+(2===f)+") {\n              vec2 wValues = vec2(\n                getW(wR, wC, "+d+", d2),\n                getW(wR, wC, "+d+" + 1, d2)\n              );\n\n              if ("+p+") {\n                vec2 xValues = vec2(\n                  getX(batch, xR, xC, "+d+"),\n                  getX(batch, xR, xC, "+d+" + 1)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec2 xValues = vec2(\n                  getX(batch, "+d+", xR, xC),\n                  getX(batch, "+d+" + 1, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            } else if ("+(3===f)+") {\n              vec3 wValues = vec3(\n                getW(wR, wC, "+d+", d2),\n                getW(wR, wC, "+d+" + 1, d2),\n                getW(wR, wC, "+d+" + 2, d2)\n              );\n\n              if ("+p+") {\n                vec3 xValues = vec3(\n                  getX(batch, xR, xC, "+d+"),\n                  getX(batch, xR, xC, "+d+" + 1),\n                  getX(batch, xR, xC, "+d+" + 2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec3 xValues = vec3(\n                  getX(batch, "+d+", xR, xC),\n                  getX(batch, "+d+" + 1, xR, xC),\n                  getX(batch, "+d+" + 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    "},Da=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,c=t.dilationWidth,l=t.filterDepth,h=t.filterHeight,d=t.filterWidth,f=4*Math.floor(t.inChannels/4),p=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 < "+l+"; 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 < "+d+"; wC++) {\n              int xC = xCCorner + wC * "+c+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if ("+(1===p)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+f+") *\n                  getW(wF, wR, wC, "+f+", d2);\n              } else if ("+(2===p)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3===p)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1),\n                  getX(batch, xF, xR, xC, "+f+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2),\n                  getW(wF, wR, wC, "+f+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Ta=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.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,d=t.filterHeight,f=t.filterWidth,p=t.outChannels/t.inChannels,v="",m="";n&&(v=r?"float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          "+n+"\n        }":"\n          float activation(float x) {\n            "+n+"\n          }\n        ",m="result = activation(result);");var g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+v+"\n\n      const ivec2 strides = ivec2("+u+", "+c+");\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / "+p+";\n        int q = d2 - d1 * "+p+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < "+d+"; wR++) {\n          int xR = xRCorner + wR * "+l+";\n\n          if (xR < 0 || xR >= "+o+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+f+"; wC++) {\n            int xC = xCCorner + wC * "+h+";\n\n            if (xC < 0 || xC >= "+a+") {\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\n        float result = dotProd;\n        "+g+"\n        "+m+"\n        setOutput(result);\n      }\n    "},Na=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.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,d=t.filterHeight,f=t.filterWidth,p=f,v="int xR; int xC; int xCOffset;",m=0;m<d;m++)for(var g=0;g<f;g++)v+="\n          vec4 xTexelR"+m+"C"+2*g+" = vec4(0.);\n          vec4 wR"+m+"C"+g+" = vec4(0.);\n          vec4 xR"+m+"C"+g+" = vec4(0.);";for(m=0;m<d;m++)for(var x=0;x<p;x++){if(v+="\n          xR = xRCorner + "+m*l+";\n          xC = xCCorner + "+(g=2*x)*h+";\n        ",1===c){if(g<f&&(v+=s%2==1?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if(xCOffset + 1 >= "+a+") {\n                    xTexelR"+m+"C"+g+".zw = vec2(0.);\n                  }\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if(xCOffset + 1 >= "+a+") {\n                    previous.zw = vec2(0.);\n                  }\n\n                  xR"+m+"C"+g+" = vec4(previous.zw, xTexelR"+m+"C"+g+".xy);\n                } else {\n                  xR"+m+"C"+g+" = vec4(0, 0, xTexelR"+m+"C"+g+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = xTexelR"+m+"C"+g+";\n              ",g+1<f)){var b=s%2==0?y(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(v+="\n                  xCOffset = xC + "+s%2+" + "+b+";\n\n                  if(xR >= 0 && xR < "+o+" &&\n                    xCOffset >= 0 && xCOffset < "+a+") {\n                    xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",h>1&&(v+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+o+" &&\n                      xCOffset >= 0 && xCOffset < "+a+") {\n                      xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+m+"C"+g+" = vec4(0.);\n                    }\n                  "),v+="\n                  xR"+m+"C"+(g+1)+" = vec4(\n                    xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".xy);\n                "):v+="\n                  xCOffset = xC + "+b+";\n\n                  if(xR >= 0 && xR < "+o+" &&\n                    xCOffset >= 0 && xCOffset < "+a+") {\n                    xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+m+"C"+(g+1)+" = xTexelR"+m+"C"+(g+2)+";\n                "}}else g<f&&(v+="\n              if(xR >= 0 && xR < "+o+") {\n            ",s%2==1?(v+="\n                xCOffset = xC + 1 - "+c+";\n                if(xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+a+") {\n                  xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = vec4(\n                  xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n              ",g+1<f&&(v+="\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + "+c+";\n                  if(xCOffset >= 0 && xCOffset < "+a+") {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR"+m+"C"+(g+1)+" = vec4(xTexelR"+m+"C"+(g+2)+".xy, final.xy);\n                ")):(v+="\n                if(xC >= 0 && xC < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+c+";\n                if(xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = vec4(\n                  xTexelR"+m+"C"+g+".xy, xTexelR"+m+"C"+(g+2)+".xy);\n              ",g+1<f&&(v+="\n                  xR"+m+"C"+(g+1)+" = vec4(\n                    xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n                ")),v+="}");g<f&&(v+="\n            vec4 wTexelR"+m+"C"+g+" = getW("+m+", "+g+", d1, q);\n            wR"+m+"C"+g+" = vec4(wTexelR"+m+"C"+g+".xz, wTexelR"+m+"C"+g+".xz);\n          ",g+1<f&&(v+="\n              vec4 wTexelR"+m+"C"+(g+1)+" = getW("+m+", "+(g+1)+", d1, q);\n              wR"+m+"C"+(g+1)+" =\n                vec4(wTexelR"+m+"C"+(g+1)+".xz, wTexelR"+m+"C"+(g+1)+".xz);"))}for(m=0;m<d;m++)for(g=0;g<f;g++)v+="dotProd += xR"+m+"C"+g+" * wR"+m+"C"+g+";";var w="",C="";n&&(w=r?"vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          "+n+"\n        }":"vec4 activation(vec4 x) {\n          "+n+"\n        }",C="result = activation(result);");var E=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+w+"\n\n      const ivec2 strides = ivec2("+u+", "+c+");\n      const ivec2 pads = ivec2("+i+", "+s+");\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 dotProd = vec4(0.);\n\n        "+v+"\n\n        vec4 result = dotProd;\n        "+E+"\n        "+C+"\n        setOutput(result);\n      }\n    "},Fa=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],c=e[0],l=n[0],h=n[1];this.outputShape=[c,l,h,u];var d="bilinear"===r?1:0,f=[i-1+".0",s-1+".0"],p=f[0],v=f[1],m=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],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 > "+p+" ) {\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("+d+" == 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    "},_a=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        "+Jo(r)+" coords = getOutputCoords();\n        int end = "+Oa(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          "+Oa(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 Oa(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 Ma=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Wt.DENSE;var e=jt(t),n=Wo();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+Uo(["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    "},Ba=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Wt.DENSE;var e=jt(t),n=Wo();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+Uo(["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}(),La=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    "},Wa=function(t){this.variableNames=["A"],this.outTexUsage=Ut.DOWNLOAD;var e=Wo();this.outputShape=t,this.userCode="\n      "+Vo+"\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+e.output+" = encode_float(x);\n      }\n    "},Ua=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ut.DOWNLOAD;var e=Wo();this.outputShape=t,this.userCode="\n      "+Vo+"\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    "},za=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=Wo(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n      "+zo(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    "},Va=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=Wo(),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 c=0;c<=1;c++){var l=2*u+c;i+="\n          localCoords = coords;\n          if(localCoords[2] + "+c+" < "+t[2]+") {\n            localCoords[2] += "+c+";\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["+l+"] = values[0];\n              } else if(offset == 1) {\n                result["+l+"] = values[1];\n              } else if(offset == 2) {\n                result["+l+"] = values[2];\n              } else {\n                result["+l+"] = values[3];\n              }\n            }\n          }\n        "}this.userCode="\n      "+zo(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    "},Ga="return real * expR - imag * expI;",Ha="return real * expI + imag * expR;",qa=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    "},Ka=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}(),ja=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=Jo(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 Xa=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Jo(e.length),o=Jo(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 Ya(t,e){var n=Wo();return ne(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 $a(t,e){return le(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 Qa(t,e){return he(t,e,new Uint16Array([0,1,2,2,1,3]))}function Ja(t,e,n,r,o,a,i){fe(n,r);var s=de(t,e),u=t.TEXTURE_2D;return $t(t,e,(function(){return t.bindTexture(u,s)})),$t(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),$t(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),$t(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),$t(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),$t(t,e,(function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)})),$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function Za(t,e,n,r,o){var a=Kt(n,r);return Ja(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function ti(t,e,n,r,o){var a=Kt(n,r);return Ja(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function ei(t,e,n,r,o){var a=Kt(n,r);return Ja(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ni(t,e,n,r,o){var a=Xt(n,r);return Ja(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ri(t,e,n,r,o){var a=Xt(n,r);return Ja(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function oi(t,e,n,r){return $t(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),ve(t,e,n,"clipSpacePos",r,3,20,0)&&ve(t,e,n,"uv",r,2,20,12)}function ai(t,e,n,r,o,a,i){var s,u,c;$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,c=i.internalFormatPackedFloat),s.set(a),$t(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)})),$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function ii(t,e,n,r){$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?$t(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):$t(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),$t(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function si(t,e,n,r,o){var a=t.createBuffer();$t(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)}));var i=16*n*r;return $t(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)})),$t(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),$t(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),a}function ui(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 ci(t,e,n,r,o){var a=Kt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return $t(t,e,(function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function li(t,e,n,r,o,a,i,s){var u=t,c=new Float32Array(function(t,e){var n=Xt(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,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function hi(t,e,n,r){var o=new Float32Array(n*r*4);return $t(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)})),o}var di=Object.freeze({createVertexShader:Ya,createVertexBuffer:$a,createIndexBuffer:Qa,createFloat32MatrixTexture:Za,createFloat16MatrixTexture:ti,createUnsignedBytesMatrixTexture:ei,createPackedMatrixTexture:ni,createFloat16PackedMatrixTexture:ri,bindVertexProgramAttributeStreams:oi,uploadDenseMatrixToTexture:ai,uploadPixelDataToTexture:ii,createBufferFromOutputTexture:si,downloadFloat32MatrixFromBuffer:ui,downloadByteEncodedFloatMatrixFromOutputTexture:ci,downloadPackedMatrixFromBuffer:li,downloadMatrixFromPackedOutputTexture:hi}),fi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=s().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ht(e,t)):this.gl=qt(e);var n="WEBGL_color_buffer_float";if(1===s().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=ee(this.gl,this.debug,"OES_texture_float"),Me(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=ee(this.gl,this.debug,"OES_texture_half_float");else if(s().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Me(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=ee(this.gl,this.debug,"EXT_color_buffer_half_float");else if(s().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Me(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Me(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=$a(this.gl,this.debug),this.indexBuffer=Qa(this.gl,this.debug),this.framebuffer=pe(this.gl,this.debug),this.textureConfig=Yt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return s().getBool("DEBUG")},enumerable:!0,configurable:!0}),t.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;$t(e,this.debug,(function(){return e.finish()})),$t(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),$t(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),$t(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),$t(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),$t(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Za(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),ti(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),ei(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),ii(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),ai(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ri(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ni(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(we(this.gl,this.debug,this.framebuffer),this.outputTexture=null),$t(this.gl,this.debug,(function(){return e.gl.deleteTexture(t)}))},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return ci(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return li(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return ui(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=si(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(s().getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=a}else s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return hi(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=re(e,this.debug,t),r=Ya(e,this.debug),o=se(e,this.debug);return $t(e,this.debug,(function(){return e.attachShader(o,r)})),$t(e,this.debug,(function(){return e.attachShader(o,n)})),ue(e,this.debug,o),this.debug&&ce(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=oi(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&$t(this.gl,this.debug,(function(){return e.gl.deleteProgram(t)}))},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&ce(this.gl,this.debug,this.program),$t(this.gl,this.debug,(function(){return e.gl.useProgram(t)}))},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ge(this.gl,this.debug,t,e):ye(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),$t(this.gl,this.debug,(function(){return n.gl.getAttribLocation(t,e)}))},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),xe(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Xt(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&ce(this.gl,this.debug,this.program),Ce(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),$t(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),$t(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=ee(this.gl,this.debug,2===s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return r(this,void 0,void 0,(function(){var e=this;return o(this,(function(n){switch(n.label){case 0:return[4,T((function(){return e.disposed||e.isQueryAvailable(t,s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),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},t.prototype.pollFence=function(t){var e=this;return new Promise((function(n){e.addItemToPoll((function(){return t.isFencePassed()}),(function(){return n()}))}))},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length;++e){if(!t[e]())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)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||T((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),be(this.gl,this.debug,t,this.framebuffer),this.debug&&Ce(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(be(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Ce(this.gl)):we(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;be(r,this.debug,t,this.framebuffer),this.debug&&Ce(r),this.outputTexture=t,$t(r,this.debug,(function(){return r.viewport(0,0,e,n)})),$t(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),$t(this.gl,this.debug,(function(){return o.gl.scissor(t,e,n,r)}))},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function pi(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(!I(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(!I(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}}))}var vi=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,h=n.dataFormat,d=s.left,f=s.top,p=o*r,v=Wo(),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+" - "+f+";\n            d0 = offsetY + "+l+" * (pos / "+p+");\n\n            if(d0 < "+e[g]+" && d0 >= 0) {\n\n              offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+d+".);\n              d1 = offsetX + "+c+" * (int(mod(float(pos), "+p+".) / "+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    "},mi=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    "},gi=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    "},yi=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!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    "},xi=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    "},bi=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,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,h=u-1-t.padInfo.top,d=c-1-t.padInfo.left,f=s*u*c-1;this.userCode="\n      const ivec3 pads = ivec3("+l+", "+h+", "+d+");\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 < "+c+";\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 = "+f+" -\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+" * "+c+" +\n                  wR * "+c+" + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},wi=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.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),c=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],d=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",p="";a&&(f=i?"vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          "+a+"\n        }":"vec4 activation(vec4 x) {\n          "+a+"\n        }",p="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+f+"\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, "+c+");\n          vec4 b = getMatrixB(rc.x, "+l+");\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += ("+h[0]+" * "+d[0]+");\n          result += ("+h[1]+" * "+d[1]+");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        "+v+"\n\n        "+p+"\n\n        setOutput(result);\n      }\n    "},Ci=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}(),Ei=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    "},Ri=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var n=Lo("rc",e),r=Jo(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 Ii=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=Jo(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      "},ki=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,o=Jo(r),a=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=Lo("rc",r),u=Lo("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n       if("+c+") {\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("+c+") {"],d=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",p=0,v=1===r?2:4;p<v;p++)f+="\n        "+h[p]+"\n        if ("+d+") {\n          result["+p+"] = float("+n+");\n        } else {\n          "+o+" source = rc - start;\n          result["+p+"] = getChannel(getX("+u.join()+"), "+l+");\n        }\n      ";f+=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        "+f+"\n        setOutput(result);\n      }\n    "},Si=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,c=t.effectiveFilterWidth,l=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var d="avg"===e,f="0.0";if(d||(f="-1.0 / 1e-20"),n)this.userCode="\n        const ivec2 strides = ivec2("+o+", "+a+");\n        const ivec2 pads = ivec2("+l+", "+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 < "+c+";\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 * "+c+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var p=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(p="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n      if ("+d+") {\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("+l+", "+h+");\n      const float initializationValue = "+f+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xR, int xC, int d) {\n        if (xC < 0 || xC >= "+t.inWidth+") {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4("+f+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+u+";\n            wR += "+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("+p+");\n      }\n    "}},Ai=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,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.front,p=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("+f+", "+p+", "+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 < "+l+";\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 < "+d+";\n                  wC += "+c+") {\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+" * "+d+" +\n                      wR * "+d+" + 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("+f+", "+p+", "+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 < "+l+";\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 * "+c+";\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+c+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n                getValue(batch, xD, xR, xC + 3 * "+c+", 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 + "+c+", 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 + "+c+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n                initializationValue\n              );\n\n              "+w+"\n            }\n          }\n          setOutput("+y+");\n        }\n      }\n    "}},Di=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 c=4*Math.floor(n/4),l=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    ",d="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      ",d="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      ",d="bvec4");var f="";o%n>0&&(f="\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        "+f+"\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+n+";\n\n        vec4 minMaxValue = vec4("+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 < "+c+"; i += 4) {\n          int inIdx = inOffset + i;\n          "+d+" values = "+d+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          "+h+"\n        }\n\n        int inIdx = inOffset + "+c+";\n        if ("+(1===l)+") {\n          "+d+" values = "+d+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(2===l)+") {\n          "+d+" values = "+d+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(3===l)+") {\n          "+d+" values = "+d+"(\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    "},Ti=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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      "+Uo(["r","c","d"],e)+"\n      return ivec3(r, c, d);\n    }\n  \n      "+zo(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 Ni=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],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],d=c[1]/l[1],f=1/h,p=1/d,v=2*Math.ceil(f)+2,m=2*Math.ceil(p)+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("+d+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+p+");\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    "},Fi=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],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/c[0]+",\n          "+u[1]/c[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    "},_i=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+u[0]/c[0]+",\n          "+u[1]/c[1]+",\n          "+u[1]/c[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    "},Oi=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],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],d=c[1]/l[1],f=1/h,p=1/d,v=2*Math.ceil(f)+2,m=2*Math.ceil(p)+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("+d+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+p+");\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("+c[0]+") *\n                (float(dyR) / float("+l[0]+"));\n\n            float sourceFracCol =\n                float("+c[1]+") *\n                  (float(dyC) / float("+l[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    "},Mi=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],c=[r&&e>1?e-1:e,r&&n>1?n-1:n],l=r?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/c[0]+",\n          "+u[1]/c[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 + "+l+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    "},Bi=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=Jo(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      "},Pi=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!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=Lo("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=Jo(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    "},Li=function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Jo(o.length),u=Jo(a.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var d="getUpdates("+h+")",f=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("+l+");\n              flattenedIndex += index * "+f+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+d+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      "},Wi=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,c="\n        sumValue += dot(values, segFilter);\n    ",l="";o%n>0&&(l="\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        "+l+"\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          "+c+"\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          "+c+"\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          "+c+"\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          "+c+"\n        }\n        setOutput(sumValue);\n      }\n    "},Ui=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 c=Jo(n);this.userCode="\n      void main() {\n        "+c+" 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    "},zi=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Jo(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return Vi.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."+Vi[e]+" = start["+e+"] + coords."+Vi[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}(),Vi=["x","y","z","w","u","v"];var Gi=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Jo(this.rank),n=Lo("coords",this.rank),r=Lo("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}(),Hi=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=Jo(n.length),a=Jo(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    "},qi=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=Ki(e,n),a=ji(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===zt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===zt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===zt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===zt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===zt.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=ji(e,Ki(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 Ki(t,e){if(t===Ut.UPLOAD)return zt.PACKED_2X2_FLOAT32;if(t===Ut.RENDER||null==t)return function(t){return s().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?zt.PACKED_2X2_FLOAT32:zt.UNPACKED_FLOAT32:t?zt.PACKED_2X2_FLOAT16:zt.UNPACKED_FLOAT16}(e);if(t===Ut.DOWNLOAD||t===Ut.PIXELS)return zt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function ji(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Xi=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=Jo(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 Yi=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=Jo(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 $i=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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=Jo(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],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n    void main() {\n      "+o+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+c+";\n      if("+u+") {\n        result[1] = "+c+";\n      }\n      --"+a[this.rank-1]+";\n      if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n        result[2] = "+c+";\n        if("+u+") {\n          result[3] = "+c+";\n        }\n      }\n      setOutput(result);\n    }\n    "},Qi=1.7580993408473768,Ji=1.0507009873554805,Zi=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    "},ts="if (isnan(x)) return x;",es="return x;",ns="return abs(x);",rs=ts+"\n  return (x < 0.0) ? 0.0 : x;\n",os=ts+"\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n",as="return (x >= 0.0) ? x : (exp(x) - 1.0);",is="\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+Qi+";\n  float scale = "+Ji+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var ss="return -x;",us="return ceil(x);",cs="return floor(x);",ls="return exp(x);",hs="return exp(x) - 1.0;",ds=ts+"\n  return sin(x);\n",fs=ts+"\n  return cos(x);\n",ps=ts+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n",vs=ts+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n",ms=ts+"\n  return atan(x);\n",gs=ts+"return log(x + sqrt(x * x + 1.0));",ys=ts+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));",xs=ts+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\n  return (log(1.0 + x) - log(1.0 - x)) / 2.0;",bs="return x;",ws="return x;",Cs="\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",Es="\n  vec4 result = min(x, vec4(6.)) * 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",Rs="\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",Is=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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    "},ks=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Lo("rc",e),r=Jo(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    "},Ss={};function As(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?ws:es;if("relu"===t)return e?Cs:rs;if("elu"===t)return e?Rs:as;if("relu6"===t)return e?Es:os;if("prelu"===t)return e?pa:da;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var Ds=600;var Ts=function(t){function e(e){var n,r=t.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!s().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var o=qt(s().getNumber("WEBGL_VERSION"));r.binaryCache=(n=s().getNumber("WEBGL_VERSION"))in Ss?Ss[n]:(Ss[n]={},Ss[n]),r.gpgpu=new fi(o),r.canvas=o.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new qi(r.gpgpu),r.numMBBeforeWarning=null==s().global.screen?1024:s().global.screen.height*s().global.screen.width*window.devicePixelRatio*Ds/1024/1024,r.texData=new Yr(r,Bt),r}return n(e,t),e.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},e.prototype.write=function(t,e,n){if(s().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:Ut.UPLOAD}),r},e.prototype.move=function(t,e,n,r){if(s().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:Ut.UPLOAD})},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 Is(i,bs):new Zi(i,bs);var c=this.runWebGLProgram(u,[{dataId:t,shape:i,dtype:r}],r),l=this.readSync(c.dataId);return this.disposeData(c.dataId),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var h,d,f=null!=this.activeTimers;(f&&(h=Z()),"complex64"===r)?d=yo(o.real.dataSync(),o.imag.dataSync()):d=this.getValuesFromTexture(t);return f&&(this.downloadWaitMs+=Z()-h),this.convertAndCacheOnCPU(t,d)},e.prototype.read=function(t){return r(this,void 0,void 0,(function(){var e,n,r,a,i,u,c,l,h,d,f,p,v,m,g,y,x,b,w,C,E,I;return o(this,(function(o){switch(o.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise((function(t){return e.push(t)}))];if(n=this.texData.get(t),r=n.values,a=n.shape,i=n.slice,u=n.dtype,c=n.complexTensors,l=n.isPacked,null!=i)return h=void 0,h=l?new Is(a,bs):new Zi(a,bs),d=this.runWebGLProgram(h,[{dataId:t,shape:a,dtype:u}],u),f=this.read(d.dataId),this.disposeData(d.dataId),[2,f];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!s().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===s().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return p=null,"complex64"!==u&&s().get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),m=this.texData.get(v.dataId),p=(I=this.gpgpu).createBufferFromTexture.apply(I,[m.texture].concat(jt(a)))),this.pendingRead.set(t,[]),"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([c.real.data(),c.imag.data()])];case 3:return y=o.sent(),x=y[0],b=y[1],g=yo(x,b),[3,5];case 4:null==p?g=this.getValuesFromTexture(t):(w=R(a),g=this.gpgpu.downloadFloat32MatrixFromBuffer(p,w)),o.label=5;case 5:return null!=v&&this.disposeData(v.dataId),C=this.convertAndCacheOnCPU(t,g),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach((function(t){return t(C)})),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}}))}))},e.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!Zt(n)){if(s().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},e.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.isPacked,i=R(r);if(s().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var u=this.decode(t),c=this.texData.get(u.dataId),l=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(jt(r))).subarray(0,i);return this.disposeData(u.dataId),l}var h=s().getBool("WEBGL_PACK")&&!0===a,d=h?Ae(r):r,f=h?new Ua(d):new Wa(d),p=this.runWebGLProgram(f,[{shape:d,dtype:o,dataId:t}],"float32"),v=this.texData.get(p.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,i);return this.disposeData(p.dataId),m},e.prototype.time=function(t){return r(this,void 0,void 0,(function(){var e,n,r,a,i,u,c;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=E(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),i=E(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,r&&(this.programTimersStack=null),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(a)]:[3,2];case 1:return c=o.sent(),u.kernelMs=x(c),u.getExtraProfileInfo=function(){return c.map((function(t,e){return{name:i[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},o.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}}))}))},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Z(),endMs:null}},e.prototype.endTimer=function(t){return s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=Z(),t)},e.prototype.getQueryTime=function(t){return r(this,void 0,void 0,(function(){var e;return o(this,(function(n){return s().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;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,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.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 s().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Bt.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.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Bt.keep(t.clone()),imag:Bt.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(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===R(n))return fn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=zr(t.shape,e,n);if(r||!o){var a=s().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Gi(n):new zi(n),i=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,i)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},e.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=this.makeOutput(n,t.dtype),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=Vr(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=Lr(e,n,r);if(o.some((function(t){return 0===t})))return fn([],o);var a=new Hi(e,r,o);return this.compileAndRun(a,[t])},e.prototype.reverse=function(t,e){var n=s().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Pi(t.shape,e):new Bi(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map((function(t){return hn(t)})),r=t.map((function(t){return dn(t)}));return ln(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>s().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),a=this.concat(t.slice(0,o),e),i=this.concat(t.slice(o),e);return this.concat([a,i],e)}if(s().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var u=new ba(t.map((function(t){return t.shape})),e);return this.compileAndRun(u,t)}var c=un(t.map((function(t){return t.shape})),e),l=t.map((function(t){return t.as2D(-1,R(t.shape.slice(e)))})),h=new xa(l.map((function(t){return t.shape})));return this.compileAndRun(h,l).reshape(c)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ss,t.dtype);var e=new Zi(t.shape,ss);return this.compileAndRun(e,[t])},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),c=1===a?2:1,l=1===a?e.as3D(s,1,i):e;return this.multiply(u,l).sum(c,!0)}var h=St(t.dtype,e.dtype),d=new wi(t.shape,[s,o,a],n,r);return this.compileAndRun(d,[t,e],h)},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],c=o?n.shape[1]:n.shape[2],l=e.shape[0],h=St(e.dtype,n.dtype),d=null!=a,f=null!=s,p=i?As(i,!0):null,v=new wi(e.shape,[l,u,c],r,o,d,p,f),m=[e,n];return a&&m.push(a),s&&m.push(s),this.compileAndRun(v,m,h)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new ua(ia,t.shape,e.shape),a=new ua(sa,t.shape,e.shape),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],u=this.compileAndRun(o,i),c=this.compileAndRun(a,i),l=this.complex(u,c);return u.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ha,t.dtype);var h=new fa(ha,t.shape,e.shape);return this.compileAndRun(h,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,a){var i=[t,e,n],u=null;null!=a&&(u=a.shape,i.push(a));var c=null;if(null!=o&&(c=o.shape,i.push(o)),s().getBool("WEBGL_PACK_NORMALIZATION")){var l=new aa(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(l,i)}var h=new oa(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(h,i)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=s().getBool("WEBGL_PACK_NORMALIZATION")?new yi(t.shape,e,n,r,o):new mi(t.shape,e,n,r,o);return this.compileAndRun(a,[t])},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new gi(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 nt(t)}));return No(Xn(t.shape,t.dtype,n),e)}var r=new Xi(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=s().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ki(t.shape,e,n):new Ii(t.shape,e,n);return this.compileAndRun(r,[t])},e.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=s().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $i(t.shape,e):new Yi(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ja(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){b(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=Er(t.shape,e,r),a=Rr(o.length,e.length),i=Ir(t.shape,e,r),s=kr(n,e.length),u=Sr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){b(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=Er(i.shape,e,r,!1),u=Rr(s.length,e.length,!1),c=Ir(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=Nr(o),i=new Di({windowSize:a,inSize:o,batchSize:r},e),s=this.compileAndRun(i,[t],n);return 1===s.shape[1]?s:this.reduce(s,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=Nr(o),i=new Bo({windowSize:a,inSize:o,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(i,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=Nr(r[r.length-1]),a=new ea(r,o,e,null==n),i=null==n?[t]:[t,n],s=this.compileAndRun(a,i,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){nn("sum",e,t.rank);var n=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o),i=At(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=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o),i=At(t.dtype);return this.reduce(a,"prod",i).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=rn([r],t.rank),a=t;null!=o&&(a=t.transpose(o),r=an(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=R([a.shape[r]]),u=a.as2D(-1,s),c=At(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(i);return null!=o&&(l=l.transpose(on(o))),l},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<=Tr?(n=t,r=!0):n=j(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=j(t,n+1);return n}(i,o),u=new Wi({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===o?c:(n=Sn(0,o).tile([i/s]),this.segOpCompute(c,e,n,r,o))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(nn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!s().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=tn(t.shape,r),a=o[0],i=R(o[1]),u=t.as2D(-1,i);return this.argReduce(u,n).reshape(a)}return this.argReducePacked(t,n)},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 _a(t.shape,n,r);return this.compileAndRun(o,[t])},e.prototype.equal=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(equal(a, b));\n","bool");var n=new fa("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(notEqual(a, b));\n","bool");var n=new fa("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThan(a, b));\n","bool");var n=new fa("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThanEqual(a, b));\n","bool");var n=new fa("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThan(a, b));\n","bool");var n=new fa("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var n=new fa("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new Zi(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new fa("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n","bool");var n=new fa("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var r=new Ui(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],St(e.dtype,n.dtype))},e.prototype.where=function(t){je("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return _o(t.shape,e)},e.prototype.topk=function(t,e,n){return Fo(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){nn("min",e,t.rank);var n=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\n  vec4 result = vec4(min(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new fa("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\n  vec4 result = mod(a, b);\n  vec4 isNaN = vec4(equal(b, vec4(0.0)));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new fa("if (b == 0.0) return NAN;\n  return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);nn("max",e,t.rank);var n=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\n  vec4 result = vec4(max(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new fa("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){nn("all",e,t.rank);var n=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},e.prototype.any=function(t,e){nn("any",e,t.rank);var n=tn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},e.prototype.realDivide=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS")){return this.packedBinaryOp(t,e,"\n  // vec4 one = vec4(equal(a, b));\n  // return one + (vec4(1.0) - one) * a / b;\n  vec4 result = a / b;\n  if(a.x == b.x) {\n    result.x = 1.;\n  }\n  if(a.y == b.y) {\n    result.y = 1.;\n  }\n  if(a.z == b.z) {\n    result.z = 1.;\n  }\n  if(a.w == b.w) {\n    result.w = 1.;\n  }\n\n  return result;\n","float32",!0)}var n=new fa("\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return this.compileAndRun(n,[t,e],"float32")},e.prototype.floorDiv=function(t,e){if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\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 n=new fa("\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",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,ca);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=St(t.dtype,e.dtype);if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ca,n);var r=new fa(ca,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Is(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new va(n,t.shape,e.shape,o);return this.compileAndRun(a,[t,e],r)},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.makeComplexComponentTensorInfo(t,a),u=r.makeComplexComponentTensorInfo(e,i),c=new fa(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],St(a.dtype,i.dtype))})),s=i[0],u=i[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>s().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var o=t.map((function(t){return t.dtype})).reduce((function(t,e){return St(t,e)})),a=t.map((function(t){return t.shape})),i=s().getBool("WEBGL_PACK")?new Mo(t[0].shape,a):new Oo(t[0].shape,a);return this.compileAndRun(i,t,o)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,la);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=St(t.dtype,e.dtype);if(s().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,la,t.dtype);var r=new fa(la,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\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",t.shape,e.shape):new fa("\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",t.shape,e.shape),r=St(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,us,t.dtype);var e=new Zi(t.shape,us);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,cs,t.dtype);var e=new Zi(t.shape,cs);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new Zi(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 Zi(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new Zi(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new Zi(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new Zi(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(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ls,t.dtype);var e=new Zi(t.shape,ls);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,hs,t.dtype);var e=new Zi(t.shape,hs);return this.compileAndRun(e,[t])},e.prototype.softmax=function(t,e){var n=F([e],t.shape),r=this.max(t,n),o=en(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return this.realDivide(i,s)},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\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",t.dtype);var e=new Zi(t.shape,"if (x < 0.0) return NAN;\n  return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new Zi(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Zi(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 Zi(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Zi(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=s().getBool("WEBGL_PACK")?new Is(t.shape,Cs):new Zi(t.shape,rs),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=s().getBool("WEBGL_PACK")?new Is(t.shape,Es):new Zi(t.shape,os),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va(pa,t.shape,e.shape):new fa(da,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Rs,t.dtype);var e=new Zi(t.shape,as);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new fa("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new Zi(t.shape,is);return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Zi(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,o=(r=s().getBool("WEBGL_PACK_CLIP")?new ga(t.shape):new ma(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(s().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ns,t.dtype);var e=new Zi(t.shape,ns);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new ya(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Zi(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Zi(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 Zi(t.shape,ds);return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Zi(t.shape,fs);return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Zi(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Zi(t.shape,ps);return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Zi(t.shape,vs);return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Zi(t.shape,ms);return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("\n  vec4 result = atan(a, b);\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new fa("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new Zi(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 Zi(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 Zi(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 Zi(t.shape,gs);return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Zi(t.shape,ys);return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Zi(t.shape,xs);return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Zi(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 sign = sign(x);\n  x = abs(x);\n  float t = 1.0 / (1.0 + p * x);\n  return sign * (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 Zi(t.shape,function(t){return void 0===t&&(t=0),ts+"\n    return x > 0.0 ? 1.0 : float("+t+");\n  "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,r,o,a){var i=t.shape,u=this.texData.get(t.dataId),c=n.inChannels,l=i[0]*i[1]*i[2],h=n.outChannels,d="channelsLast"===n.dataFormat,f=(1===l||1===h)&&c>1e3,p=i[2]%2!=0&&!!u.isPacked;if(f||!s().getBool("WEBGL_LAZILY_UNPACK")||!s().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!p){var v=d?i[0]*i[1]*i[2]:i[0]*i[2]*i[3],m=this.reshape(t,[1,v,n.inChannels]),g=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:g,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),n.outShape)}var y=d?i[0]*i[1]*(i[2]+1):i[0]*i[2]*(i[3]+1),x={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,b(Ne(u.shape,x.shape),(function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"}));var C=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:x,b:C,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),R=this.texData.get(E.dataId);return b(R.isPacked,(function(){return"batchMatMul result is expected to be packed"})),u.shape=w,R.shape=n.outShape,Bt.makeTensorFromDataId(E.dataId,n.outShape,E.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,h="channelsLast"===n.dataFormat,d=i*s*u,f=l*c,p=[d,f],v=t.squeeze([0]),m=e.reshape([1,d,-1]),g=new vi(p,v.shape,n),y=this.compileAndRun(g,[v]).reshape([1,p[0],p[1]]),x=null!=r,b=null!=a,w=o?As(o,!0):null,C=new wi(y.shape,[1,f,n.outChannels],!0,!1,x,w,b),E=[y,m];r&&E.push(r),b&&E.push(a);var R=this.compileAndRun(C,E);return h?R.reshape([1,l,c,n.outChannels]):R.reshape([1,n.outChannels,l,c])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights;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(s().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,a,i);var u=null!=o,c=null!=i,l=a?As(a,!1):null,h=new Aa(r,u,l,c),d=[e,n];return o&&d.push(o),i&&d.push(i),this.compileAndRun(h,d)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(s().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Aa(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Ea(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Ca(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,a=t.bias,i=t.activation,u=t.preluActivationWeights,c=s().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,l=i?As(i,c):null,h=[n,r],d=null!=a,f=null!=u;return d&&h.push(a),f&&h.push(u),c?(e=new Na(o,d,l,f),this.compileAndRun(e,h)):(e=new Ta(o,d,l,f),this.compileAndRun(e,h))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return s().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Na(n),this.compileAndRun(r,[t,e])):(r=new Ta(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Sa(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new ka(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Da(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new Ia(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new Ra(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Si(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Si(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var o=new Si(r,"max",!0),a=this.compileAndRun(o,[e]),i=new xi(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new na(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return po(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);return this.compileAndRun(n,[t],"float32")},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new ra(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new Ai(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new Ai(r,"max",!0),a=this.compileAndRun(o,[e]),i=new bi(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!Ne(t.shape,e)&&(null===n.texture||!Ne(n.shape,e))){var r=this.packedReshape(t,e);return Bt.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return vo(t,e)},e.prototype.resizeBilinear=function(t,e,n,r){var o=s().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new _i(t.shape,e,n,r):new Fi(t.shape,e,n,r);return this.compileAndRun(o,[t],"float32")},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new Ni(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new Mi(t.shape,e,n,r);return this.compileAndRun(o,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Oi(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var o=e?t:jr(t),a=o.shape[0],i=o.shape[1],s=new Ci(a,i,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],"int32",u)},e.prototype.oneHot=function(t,e,n,r){var o=new Ei(t.size,e,n,r);return this.compileAndRun(o,[t])},e.prototype.diag=function(t){var e=new La(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return je("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 Fa(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n],"float32")},e.prototype.depthToSpace=function(t,e,n){b(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,c=i/(e*e),l=new Pa("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},e.prototype.split=function(t,e,n){return To(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=Or(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/i,i],l=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return vo(fn([]),n);var d=vn(0),f=new Li(a,o,l.rank,h.rank,s,c);return this.compileAndRun(f,[h,l,d]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var o=Or(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,c=new Li(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[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 qa(Ga,t.shape,e),o=new qa(Ha,t.shape,e),a=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(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=Ar(t,e),a=o[0],i=o[1],s=o[2],u=o[3],c=e.reshape([i,r]),l=t.reshape([t.size/s,s]),h=new Xa(r,u,[i,s]);return this.compileAndRun(h,[l,c]).reshape(a)},e.prototype.fill=function(t,e,n){if("string"===(n=n||q(e))){var r=M(n,R(t));return r.fill(e),Bt.makeTensor(r,t,n,this)}var o=new Ka(t,e),a=o.getCustomSetupFunc(e);return this.compileAndRun(o,[],n,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 mo(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Bt.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new ks(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new Ri(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[ke(t.shape)].concat(Se(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},o=[ke(e)].concat(Se(e)),a=new Ti(o,n),i=this.runWebGLProgram(a,[r],t.dtype,null,!0);return{dataId:i.dataId,shape:e,dtype:i.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=Ae(o);e=r?new Ba(i):new Ma(i);return{dtype:a,shape:o,dataId:this.runWebGLProgram(e,[{shape:i,dtype:a,dataId:t}],a,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,o){var a=this;void 0===o&&(o=!1);var i=this.makeTensorInfo(t.outputShape,n),u=this.texData.get(i.dataId);if(t.packedOutput&&(u.isPacked=!0),t.outPackingScheme===Wt.DENSE){var c=jt(t.outputShape);u.texShape=c.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(u.usage=t.outTexUsage),0===R(i.shape))return u.values=O(i.dtype,0),i;var l=[],h=e.map((function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=a.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&R(e.shape)<=s().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),l.push(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!Ne(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),l.push(e),n=a.texData.get(e.dataId),r.shape=o}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);var d,f={shape:i.shape,texData:u,isUniform:!1},p=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}(t,h,f),v=this.getAndSaveBinary(p,(function(){return function(t,e,n,r){var o=e.userCode,a=n.map((function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}})),i=a.map((function(t){return t.shapeInfo})),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=Go(a,u,o,e.packedInputs),l=t.createProgram(c),h=null,d=t.getUniformLocation(l,"NAN",!1);1===s().getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(l,"INFINITY",!1));for(var f={},p=0;p<e.variableNames.length;p++){var v=e.variableNames[p];f[v]=t.getUniformLocation(l,v,!1),f["offset"+v]=t.getUniformLocation(l,"offset"+v,!1)}return{program:e,source:c,webGLProgram:l,uniformLocations:f,inShapeInfos:i,outShapeInfo:u,infLoc:h,nanLoc:d}}(a.gpgpu,t,h,f)})),m=null!=this.activeTimers;if(m&&(d=this.startTimer()),function(t,e,n,r,o){pi(e.inShapeInfos,n),pi([e.outShapeInfo],[r]);var a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,i[0],i[1]):t.setOutputMatrixTexture(a,i[0],i[1]),t.setProgram(e.webGLProgram),1===s().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach((function(n,r){var o=e.program.variableNames[r],a=e.uniformLocations[o],i=e.uniformLocations["offset"+o];if(null!=a)if(n.isUniform)if(R(n.shape)<2)t.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(a,s)}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r)})),null!=o&&o(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,v,h,f,r),l.forEach((function(t){return a.disposeData(t.dataId)})),m&&(d=this.endTimer(d),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(d)})),!s().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&!1===o){var g=this.unpackTensor(i);return this.disposeData(i.dataId),g}return i},e.prototype.compileAndRun=function(t,e,n,r,o){void 0===o&&(o=!1),n=n||e[0].dtype;var a=this.runWebGLProgram(t,e,n,r,o);return Bt.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},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(){var t=this;if(!this.disposed){if(!s().getBool("IS_TEST"))Object.keys(this.binaryCache).forEach((function(e){t.gpgpu.deleteProgram(t.binaryCache[e].webGLProgram),delete t.binaryCache[e]}));this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}},e.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=He((function(){if(!s().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=s().getBool("DEBUG");s().set("DEBUG",!1);var n=t.abs(vn(1e-8)).dataSync()[0];if(s().set("DEBUG",e),n>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 c,l=null!=this.activeTimers;l&&(c=Z());var h=n.texShape;if(null==h&&(h=De(r,u),n.texShape=h),null!=a){var d=Ae(r),f=void 0,p=h[1],v=h[0],m=a instanceof Uint8Array;u?(p=(e=Xt(h[0],h[1]))[0],v=e[1],f=new Va(d,[v,p],m)):f=new za(d,[v,p],m);var g=this.makeTensorInfo([v,p],o);this.texData.get(g.dataId).usage=m?Ut.PIXELS:Ut.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),p,v,a);var y=this.runWebGLProgram(f,[g],o,null,!0),x=this.texData.get(y.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(g.dataId),this.texData.delete(y.dataId),n.values=null,l&&(this.uploadWaitMs+=Z()-c)}else{var b=this.acquireTexture(h,s,o,u);n.texture=b}}},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]*U(e)},e}($r);Pt()&&Bt.registerBackend("webgl",(function(){return new Ts}),2);var Ns=cn({square_:function(t){var e=$e(t,"x","square"),n=[e];return Bt.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}}),Fs="SquaredDifference";var _s=cn({squaredDifference_:function(t,e){var n,r=$e(t,"a","squaredDifference"),o=$e(e,"b","squaredDifference");n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape);var a={a:r,b:o},i=[r,o];return Bt.runKernelFunc((function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n}),a,(function(t,e){var n=e[0],r=e[1],o=vn(2);return{a:function(){return t.mul(n.sub(r).mul(o))},b:function(){return t.mul(r.sub(n).mul(o))}}}),Fs,{},i,[])}});var Os=cn({abs_:function(t){var e=$e(t,"x","abs");return"complex64"===e.dtype?Bt.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Bt.runKernelFunc((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))}}}),"Abs")}}),Ms=cn({acos_:function(t){var e=$e(t,"x","acos");return Bt.runKernelFunc((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(vn(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Bs=cn({acosh_:function(t){var e=$e(t,"x","acosh");return Bt.runKernelFunc((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())}}}))}}),Ps=cn({asin_:function(t){var e=$e(t,"x","asin");return Bt.runKernelFunc((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(vn(1).sub(n.toFloat().square()).sqrt())}}}))}}),Ls=cn({asinh_:function(t){var e=$e(t,"x","asinh");return Bt.runKernelFunc((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(vn(1).add(n.toFloat().square()).sqrt())}}}))}}),Ws=cn({atan_:function(t){var e=$e(t,"x","atan");return Bt.runKernelFunc((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))}}}))}}),Us=cn({atanh_:function(t){var e=$e(t,"x","atanh");return Bt.runKernelFunc((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(vn(1).sub(n.toFloat().square()))}}}))}}),zs=cn({ceil_:function(t){var e=$e(t,"x","ceil");return Bt.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),Vs=cn({clipByValue_:function(t,e,n){var r=$e(t,"x","clipByValue");b(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var o=[r],a={min:e,max:n};return Bt.runKernelFunc((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)),Dn(t))}}}),"ClipByValue",a,o)}}),Gs=cn({cos_:function(t){var e=$e(t,"x","cos"),n=[e];return Bt.runKernelFunc((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)}}}),"Cos",{},n)}}),Hs=cn({cosh_:function(t){var e=$e(t,"x","cosh");return Bt.runKernelFunc((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)}}}))}}),qs=cn({erf_:function(t){var e=$e(t,"x","erf");return b("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Bt.runKernelFunc((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)))}}}))}}),Ks=cn({exp_:function(t){var e=$e(t,"x","exp");return Bt.runKernelFunc((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])}}}),"Exp",{},[],[!0])}}),js=cn({expm1_:function(t){var e=$e(t,"x","expm1");return Bt.runKernelFunc((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())}}}))}}),Xs=cn({floor_:function(t){var e=$e(t,"x","floor");return Bt.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),Ys=cn({log_:function(t){var e=$e(t,"x","log"),n=[e];return Bt.runKernelFunc((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())}}}),"Log",{},n)}}),$s=cn({log1p_:function(t){var e=$e(t,"x","log1p");return Bt.runKernelFunc((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))}}}))}}),Qs=cn({logSigmoid_:function(t){var e=$e(t,"x","logSigmoid");return Bt.runKernelFunc((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())}}}))}}),Js=cn({neg_:function(t){var e=$e(t,"x","neg"),n=[e];return Bt.runKernelFunc((function(t){return t.neg(e)}),{x:e},(function(t){return{x:function(){return t.neg()}}}),"Neg",{},n)}}),Zs=cn({reciprocal_:function(t){var e=$e(t,"x","reciprocal");return Bt.runKernelFunc((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())}}}))}}),tu=cn({round_:function(t){var e=$e(t,"x","round");return Bt.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),eu=cn({rsqrt_:function(t){var e=$e(t,"x","rsqrt"),n=[e];return Bt.runKernelFunc((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()}}}),"Rsqrt",{},n)}}),nu=cn({sigmoid_:function(t){var e=$e(t,"x","sigmoid");return Bt.runKernelFunc((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(vn(1).sub(n)))}}}),"Sigmoid")}}),ru=cn({sign_:function(t){var e=$e(t,"x","sign");return Bt.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),ou=cn({isNaN_:function(t){var e=$e(t,"x","isNaN");return Bt.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),au=cn({isInf_:function(t){var e=$e(t,"x","isInf");return Bt.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),iu=cn({isFinite_:function(t){var e=$e(t,"x","isFinite");return Bt.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return Dn(t)}}}))}}),su=cn({sin_:function(t){var e=$e(t,"x","sin"),n=[e];return Bt.runKernelFunc((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)}}}),"Sin",{},n)}}),uu=cn({sinh_:function(t){var e=$e(t,"x","sinh");return Bt.runKernelFunc((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)}}}))}}),cu=cn({softplus_:function(t){var e=$e(t,"x","softplus");return Bt.runKernelFunc((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())}}}))}}),lu=cn({sqrt_:function(t){var e=$e(t,"x","sqrt");return Bt.runKernelFunc((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))}}}))}}),hu=cn({step_:function(t,e){void 0===e&&(e=0);var n=$e(t,"x","step");return Bt.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return Dn(t)}}}))}}),du=cn({tan_:function(t){var e=$e(t,"x","tan");return Bt.runKernelFunc((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())}}}))}}),fu=cn({tanh_:function(t){var e=$e(t,"x","tanh");return Bt.runKernelFunc((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 vn(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}});function pu(t,e,n,r,o,a){var i,s,u=$e(t,"x","batchNorm"),c=$e(e,"mean","batchNorm"),l=$e(n,"variance","batchNorm");return null!=o&&(i=$e(o,"scale","batchNorm")),null!=r&&(s=$e(r,"offset","batchNorm")),b(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),b(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),b(2===l.rank||1===l.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."})),null!=i&&b(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&&b(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),gu(u,c,l,s,i,a)}function vu(t,e,n,r,o,a){var i,s,u=$e(t,"x","batchNorm"),c=$e(e,"mean","batchNorm"),l=$e(n,"variance","batchNorm");return null!=o&&(i=$e(o,"scale","batchNorm")),null!=r&&(s=$e(r,"offset","batchNorm")),b(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),b(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),b(3===l.rank||1===l.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."})),null!=i&&b(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&&b(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),gu(u,c,l,s,i,a)}function mu(t,e,n,r,o,a){var i,s,u=$e(t,"x","batchNorm"),c=$e(e,"mean","batchNorm"),l=$e(n,"variance","batchNorm");return null!=o&&(i=$e(o,"scale","batchNorm")),null!=r&&(s=$e(r,"offset","batchNorm")),b(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),b(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),b(4===l.rank||1===l.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."})),null!=i&&b(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&&b(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),gu(u,c,l,s,i,a)}function gu(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,c=$e(t,"x","batchNorm"),l=$e(e,"mean","batchNorm"),h=$e(n,"variance","batchNorm");null!=o&&(i=$e(o,"scale","batchNorm")),null!=r&&(s=$e(r,"offset","batchNorm")),b(l.rank===h.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),b(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),b(null==i||l.rank===i.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."})),u=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var d=[c,l,h,i];return Bt.runKernelFunc((function(t,e){var n=t.batchNormalization(u,yu(l),yu(h),a,yu(i),yu(s));return e([c,l,h,i]),n}),{x:c,mean:l,variance:h,scale:i,offset:s},(function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],c=null==s?vn(1):s,l=Zr(o.shape,u.shape),h=[];if(1===o.rank){for(var d=0;d<u.shape.length-1;++d)h.push(u.shape[d]);h.push(1)}var f=r.sub(o),p=t.mul(c),v=eu(i.add(vn(a))),m=v.mul(v).mul(v).mul(vn(-.5));return{x:function(){return 1===o.rank?t.mul(xr(v.as4D(1,1,1,o.shape[0]),h)).mul(c).reshape(r.shape):t.mul(v).mul(c).reshape(r.shape)},mean:function(){var t=v.mul(vn(-1)).mul(p);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},variance:function(){var t=m.mul(f).mul(p);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},scale:function(){var e=f.mul(v),n=t.mul(e);return 1===o.rank&&(n=n.sum(l)),n.reshape(o.shape)},offset:function(){var e=t;return 1===o.rank&&(e=e.sum(l)),e.reshape(o.shape)}}}),"BatchNormalization",{varianceEpsilon:a},d).reshape(c.shape)}function yu(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 xu(){Ge("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var bu=cn({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),xu(),pu(t,e,n,a,o,r)}}),wu=cn({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),xu(),vu(t,e,n,a,o,r)}}),Cu=cn({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),xu(),mu(t,e,n,a,o,r)}}),Eu=cn({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),xu(),gu(t,e,n,a,o,r)}}),Ru=cn({batchNorm_:gu}),Iu=cn({batchNorm2d_:pu}),ku=cn({batchNorm3d_:vu}),Su=cn({batchNorm4d_:mu});var Au=cn({logicalAnd_:function(t,e){var n=$e(t,"a","logicalAnd","bool"),r=$e(e,"b","logicalAnd","bool");return to(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Du=cn({logicalNot_:function(t){var e=$e(t,"x","logicalNot","bool");return Bt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),Tu=cn({logicalOr_:function(t,e){var n=$e(t,"a","logicalOr","bool"),r=$e(e,"b","logicalOr","bool");return to(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),Nu=cn({logicalXor_:function(t,e){var n=$e(t,"a","logicalXor","bool"),r=$e(e,"b","logicalXor","bool");return to(n.shape,r.shape),Tu(t,e).logicalAnd(Au(t,e).logicalNot())}}),Fu=cn({where_:function(t,e,n){var r=$e(e,"a","where"),o=$e(n,"b","where"),a=$e(t,"condition","where","bool");return w(r.shape,o.shape,"Error in where: "),1===a.rank?b(a.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):w(a.shape,o.shape,"Error in where: "),Bt.runKernelFunc((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 Dn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),_u=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=$e(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=_o(e.shape,n),t!==e&&e.dispose(),[2,r]}}))}))};var Ou=cn({add_:function(t,e){var n,r=$e(t,"a","add"),o=$e(e,"b","add");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((function(t){return t.add(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Zr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Zr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}}),"Add")}}),Mu=cn({addN_:function(t){b(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),b(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 $e(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(!I(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Bt.runKernelFunc((function(t){return t.addN(e)}),r,(function(t){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}),"AddN")}}),Bu=cn({addStrict_:function(t,e){var n=$e(t,"a","addStrict"),r=$e(e,"b","addStrict");return w(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Pu=cn({atan2_:function(t,e){var n,r=$e(t,"a","atan2"),o=$e(e,"b","atan2");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((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=Zr(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=Js(t.mul(n.div(e))),i=Zr(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}}))}}),Lu=cn({div_:function(t,e){var n,r=$e(t,"a","div"),o=$e(e,"b","div");if(n=Dt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return zu(r,o);var a=to(r.shape,o.shape);return Bt.runKernelFunc((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=Zr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Zr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"Div")}}),Wu=cn({divNoNan_:function(t,e){var n,r=$e(t,"a","div"),o=$e(e,"b","div");r=(n=Dt(r,o))[0],o=n[1];var a=Lu(r,o),i=Dn(a),s=o.equal(i);return Fu(s,i,a)}}),Uu=cn({divStrict_:function(t,e){var n=$e(t,"a","div"),r=$e(e,"b","div");return w(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),zu=cn({floorDiv_:function(t,e){var n,r=$e(t,"a","floorDiv"),o=$e(e,"b","floorDiv");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((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=Zr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Zr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"FloorDiv")}}),Vu=cn({maximum_:function(t,e){var n,r=$e(t,"a","maximum"),o=$e(e,"b","maximum");return n=Dt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),to(r.shape,o.shape),Bt.runKernelFunc((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())}}}),"Maximum")}}),Gu=cn({maximumStrict_:function(t,e){var n=$e(t,"a","maximumStrict"),r=$e(e,"b","maximumStrict");return w(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Hu=cn({minimum_:function(t,e){var n,r=$e(t,"a","minimum"),o=$e(e,"b","minimum");return n=Dt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),to(r.shape,o.shape),Bt.runKernelFunc((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())}}}),"Minimum")}}),qu=cn({minimumStrict_:function(t,e){var n=$e(t,"a","minimumStrict"),r=$e(e,"b","minimumStrict");return w(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Ku=cn({mod_:function(t,e){var n,r=$e(t,"a","mod"),o=$e(e,"b","mod");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((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=Zr(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=Zr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}))}}),ju=cn({modStrict_:function(t,e){var n=$e(t,"a","modStrict"),r=$e(e,"b","modStrict");return w(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Xu=cn({mul_:function(t,e){var n,r=$e(t,"a","mul"),o=$e(e,"b","mul");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((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=Zr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Zr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}),"Mul")}}),Yu=cn({mulStrict_:function(t,e){var n=$e(t,"a","mul"),r=$e(e,"b","mul");return w(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),$u=cn({pow_:function(t,e){var n,r=$e(t,"base","pow"),o=$e(e,"exp","pow");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape),i=[r,o];return Bt.runKernelFunc((function(t,e){var n=t.pow(r,o);return e([r,o,n]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1],o=e[2];return{a:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(vn(1))))),i=Zr(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},b:function(){var e=n.greater(0),i=n.log().where(e,Dn(n)),s=t.mul(o.mul(i)),u=Zr(r.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},i,[!0])}}),Qu=cn({powStrict_:function(t,e){return w(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Ju=cn({squaredDifferenceStrict_:function(t,e){var n=$e(t,"a","squaredDifferenceStrict"),r=$e(e,"b","squaredDifferenceStrict");return w(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Zu=cn({sub_:function(t,e){var n,r=$e(t,"a","sub"),o=$e(e,"b","sub");n=Dt(r,o),r=n[0],o=n[1];var a=to(r.shape,o.shape);return Bt.runKernelFunc((function(t){return t.subtract(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Zr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Zr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}}),"Sub")}}),tc=cn({subStrict_:function(t,e){var n=$e(t,"a","subStrict"),r=$e(e,"b","subStrict");return w(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var ec=cn({equal_:function(t,e){var n,r=$e(t,"a","equal"),o=$e(e,"b","equal");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((function(t){return t.equal(r,o)}),{$a:r,$b:o})}}),nc=cn({equalStrict_:function(t,e){var n=$e(t,"a","equalStrict"),r=$e(e,"b","equalStrict");return w(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),rc=cn({greater_:function(t,e){var n,r=$e(t,"a","greater"),o=$e(e,"b","greater");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((function(t){return t.greater(r,o)}),{a:r,b:o},null,"Greater")}}),oc=cn({greaterEqual_:function(t,e){var n,r=$e(t,"a","greaterEqual"),o=$e(e,"b","greaterEqual");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((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 Dn(n)},b:function(){return Dn(r)}}}),"GreaterEqual")}}),ac=cn({greaterEqualStrict_:function(t,e){var n=$e(t,"a","greaterEqualStrict"),r=$e(e,"b","greaterEqualStrict");return w(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),ic=cn({greaterStrict_:function(t,e){var n=$e(t,"a","greaterStrict"),r=$e(e,"b","greaterStrict");return w(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),sc=cn({less_:function(t,e){var n,r=$e(t,"a","less"),o=$e(e,"b","less");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((function(t){return t.less(r,o)}),{a:r,b:o},null,"Less")}}),uc=cn({lessEqual_:function(t,e){var n,r=$e(t,"a","lessEqual"),o=$e(e,"b","lessEqual");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((function(t,e){var n=t.lessEqual(r,o);return e([r,o]),n}),{a:r,b:o},null,"LessEqual")}}),cc=cn({lessEqualStrict_:function(t,e){var n=$e(t,"a","lessEqualStrict"),r=$e(e,"b","lessEqualStrict");return w(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),lc=cn({lessStrict_:function(t,e){var n=$e(t,"a","lessStrict"),r=$e(e,"b","lessStrict");return w(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),hc=cn({notEqual_:function(t,e){var n,r=$e(t,"a","notEqual"),o=$e(e,"b","notEqual");return n=Dt(r,o),r=n[0],o=n[1],to(r.shape,o.shape),Bt.runKernelFunc((function(t){return t.notEqual(r,o)}),{a:r,b:o},null,"NotEqual")}}),dc=cn({notEqualStrict_:function(t,e){var n=$e(t,"a","notEqualStrict"),r=$e(e,"b","notEqualStrict");return w(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function fc(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function pc(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 vc=cn({gather_:function(t,e,n){void 0===n&&(n=0);var r=$e(t,"x","gather"),o=$e(e,"indices","gather","int32");n=F(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 Bt.runKernelFunc((function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a}),{x:r,indices:o},(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),c=u.length,l=fc(0,s),h=fc(s+1,s+1+c),d=pc([i,[a],u]),f=t.reshape(d),p=o.reshape([a]),v=pc([[s],l,h]),m=f.transpose(v),g=mc(m,p,r.shape[n]),y=on(v);return g=g.transpose(y)},indices:function(){return o}}}),"Gather",{axis:n}).reshape(a.outputShape)}}),mc=cn({unsortedSegmentSum_:function(t,e,n){var r=$e(t,"x","unsortedSegmentSum"),o=$e(e,"segmentIds","unsortedSegmentSum","int32");return b(k(n),(function(){return"numSegments must be of dtype int"})),Bt.runKernelFunc((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=Vu(e,Dn(e)),r=vc(t,n),o=oc(e,vn(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=nr(o,i+1);o=Au(o,En(r.shape,"bool"));var s=Dn(r);return Fu(o,r,s)}(t,n)}}}))}});var gc=function(t,e,n){return r(this,void 0,void 0,(function(){var r,a,i,s,u,c,l,h,d,f,p,v,m;return o(this,(function(o){switch(o.label){case 0:for(r=$e(t,"tensor","boolMask"),a=$e(e,"mask","boolMask","bool"),i=null==n?0:n,s=a.rank,u=r.shape,b(s>0,(function(){return"mask cannot be scalar"})),w(u.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),c=1,l=i;l<i+s;l++)c*=u[l];return h=u.slice(0,i).concat([c],u.slice(i+s)),d=r.reshape(h),f=a.reshape([-1]),[4,_u(f)];case 1:return p=o.sent(),v=p.squeeze([1]),m=vc(d,v,i),t!==r&&r.dispose(),e!==a&&a.dispose(),v.dispose(),d.dispose(),f.dispose(),p.dispose(),[2,m]}}))}))};function yc(t,e,n,r,o,a,i){void 0===a&&(a="NHWC"),b(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var s=t,u=e,c=!1;3===e.rank&&(c=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),b(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),b(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),b(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var l="NHWC"===a?s[3]:s[1],h="NHWC"===a?u.shape[3]:u.shape[1];b(l===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."})),b(h===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."})),null!=i&&b(k(o),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var d=fo(a),f=ro(s,n.shape,r,1,o,i,!1,d),p=Bt.runKernelFunc((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 Cc(t,n,r,o,a,1,i)},filter:function(){return Rc(t,s,n.shape,r,o,a,i)}}}));return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function xc(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 bc(t,e,n,r,o){b(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],c=i.shape[4];b(5===a.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."})),b(5===i.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank})),b(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),b(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),b(c===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."}));var l=oo(a,n.shape,r,1,o),h=Bt.runKernelFunc((function(t){return t.conv3dDerInput(i,n,l)}),{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var wc=cn({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=$e(t,"x","conv1d"),u=$e(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),b(3===c.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."})),b(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=i&&b(k(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."})),b(c.shape[2]===u.shape[1],(function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."})),b(ho(n,a),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"})),b("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]),d=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),f=Cc(d,h,[1,n],r,"NHWC",[1,a],i);return l?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),Cc=cn({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=$e(t,"x","conv2d"),u=$e(e,"filter","conv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===c.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."})),b(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=i&&b(k(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h="NHWC"===o?c.shape[3]:c.shape[1];b(h===u.shape[2],(function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."})),b(ho(n,a),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}));var d=fo(o),f=ro(c.shape,u.shape,n,a,r,i,!1,d),p=[u,c],v=Bt.runKernelFunc((function(t,e){var n=t.conv2d(c,u,f);return e([u,c]),n}),{x:c,filter:u},(function(t,e){var i=e,s=i[0],u=i[1];return b(lo(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 Ic(u.shape,t,s,n,r,o)},filter:function(){return Rc(u,t,s.shape,n,r,o)}}}),"Conv2D",f,p);return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Ec=cn({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=$e(t,"x","conv3d"),s=$e(e,"filter","conv3d"),u=i,c=!1;4===i.rank&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),b(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),b(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),b(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]+"."})),b(function(t,e){return xc(t)||xc(e)}(n,a),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),b("NDHWC"===o,(function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."}));var l=oo(u.shape,s.shape,n,a,r),h=Bt.runKernelFunc((function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){b(xc(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 bc(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]));b(5===a.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."})),b(5===i.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."})),b(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),b(a.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."})),b(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=oo(a.shape,n,r,1,o);return Bt.runKernelFunc((function(t){return t.conv3dDerFilter(a,i,s)}),{x5D:a,dy5D:i})}(o,t,i.shape,n,r)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Rc=cn({conv2dDerFilter_:function(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])),b(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),b(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),b(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var c="NHWC"===a?s.shape[3]:s.shape[1],l="NHWC"===a?u.shape[3]:u.shape[1];b(c===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."})),b(l===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."})),null!=i&&b(k(o),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var h=fo(a),d=ro(s.shape,n,r,1,o,i,!1,h);return Bt.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,d)}),{x4D:s,dy4D:u})}}),Ic=cn({conv2dDerInput_:yc}),kc=cn({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=$e(t,"x","depthwiseConv2d"),u=$e(e,"filter","depthwiseConv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===c.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."})),b(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),b(c.shape[3]===u.shape[2],(function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."})),null==a&&(a=[1,1]),b(ho(n,a),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=i&&b(k(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h=ro(c.shape,u.shape,n,a,r,i,!0),d=[c,u],f=Bt.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(c,u,h);return e([c,u]),n}),{x:c,filter:u},(function(t,e){b(lo(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 Sc(n.shape,t,r,h)},filter:function(){return Ac(n,t,r.shape,h)}}}),"DepthwiseConv2dNative",h,d);return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),Sc=cn({depthwiseConv2dDerInput_: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=Bt.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(o,n,r)}),{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),Ac=cn({depthwiseConv2dDerFilter_: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])),Bt.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(o,a,r)}),{x4D:o,dy4D:a})}}),Dc=cn({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=$e(t,"x","separableConv2d"),u=$e(e,"depthwiseFilter","separableConv2d"),c=$e(n,"pointwiseFilter","separableConv2d"),l=s,h=!1;if(3===s.rank&&(h=!0,l=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");b(4===l.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."})),b(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),b(4===c.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),b(1===c.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+c.shape[0]+"."})),b(1===c.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."}));var d=u.shape[2],f=u.shape[3];b(c.shape[2]===d*f,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+d*f+", but got "+c.shape[2]+"."}));var p=kc(l,u,r,o,i,a),v=Cc(p,c,1,"valid",i);return h?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Tc=cn({conv2dTranspose_:function(t,e,n,r,o,a){return yc(n,$e(t,"x","conv2dTranspose"),$e(e,"filter","conv2dTranspose"),r,o,"NHWC",a)}}),Nc=cn({conv3dTranspose_:function(t,e,n,r,o){return bc(n,$e(t,"x","conv3dTranspose"),$e(e,"filter","conv3dTranspose"),r,o)}});var Fc=cn({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=$e(t,"a","matMul"),i=$e(e,"b","matMul");o=Dt(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],c=n?a.shape[a.rank-1]:a.shape[a.rank-2],l=r?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),d=i.shape.slice(0,-2),f=R(h),p=R(d);b(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+"."})),b(I(h,d),(function(){return"Error in matMul: outer dimensions ("+h+") and ("+d+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."})),b(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 v=a.shape.slice(0,-2).concat([c,l]),m=n?a.as3D(f,s,c):a.as3D(f,c,s),g=r?i.as3D(p,l,u):i.as3D(p,u,l),y={transposeA:n,transposeB:r};return Bt.runKernelFunc((function(t,e){var o=t.batchMatMul(m,g,n,r);return e([m,g]),o}),{a:m,b:g},(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)}}}),"BatchMatMul",y).reshape(v)}}),_c=cn({dot_:function(t,e){var n=$e(t,"t1","dot"),r=$e(e,"t2","dot");b(!(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 b(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]))}}),Oc=cn({outerProduct_:function(t,e){var n=$e(t,"v1","outerProduct"),r=$e(e,"v2","outerProduct");return b(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 Mc=cn({reverse_:function(t,e){var n=$e(t,"x","reverse");if(0===n.rank)return n.clone();var r=F(e,n.shape);return Bt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),Bc=cn({reverse1d_:function(t){var e=$e(t,"x","reverse");return b(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),Mc(e,0)}}),Pc=cn({reverse2d_:function(t,e){var n=$e(t,"x","reverse");return b(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),Mc(n,e)}}),Lc=cn({reverse3d_:function(t,e){var n=$e(t,"x","reverse");return b(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),Mc(n,e)}}),Wc=cn({reverse4d_:function(t,e){var n=$e(t,"x","reverse");return b(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),Mc(n,e)}});function Uc(t,e,n,r,o,a){var i=$e(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]),b(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),b(ho(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=a&&b(k(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=eo(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&I(c.inShape,c.outShape))return i.clone();var l=[s],h=Bt.runKernelFunc((function(t,e){var n=t.maxPool(s,c);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=$e(t,"dy","maxPoolBackprop"),c=$e(e,"input","maxPoolBackprop"),l=$e(n,"output","maxPoolBackprop");b(c.rank===u.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"})),null==a&&(a=[1,1]);b(ho(o,a),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),b(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),b(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."})),null!=s&&b(k(i),(function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var h=eo(c.shape,r,o,a,i,s);return Bt.runKernelFunc((function(t){return t.maxPoolBackprop(u,c,l,h)}),{$dy:u,$input:c})}(t,i,s,e,n,r,o)}}}),"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function zc(t,e,n,r,o,a){var i=$e(t,"x","avgPool","float32");null==r&&(r=[1,1]),b(ho(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])),b(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=a&&b(k(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=eo(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&I(c.inShape,c.outShape))return i.clone();var l=Bt.runKernelFunc((function(t){return t.avgPool(s,c)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,o,a){var i=$e(t,"dy","avgPoolBackprop"),s=$e(e,"input","avgPoolBackprop");b(s.rank===i.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"})),null==o&&(o=[1,1]);b(ho(r,o),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}));var u=s,c=i,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));b(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),b(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var h=eo(u.shape,n,r,o,a),d=Bt.runKernelFunc((function(t){return t.avgPoolBackprop(c,u,h)}),{dy4D:c,input4D:u});if(l)return d.as3D(d.shape[1],d.shape[2],d.shape[3]);return d}(t,s,e,n,r,o)}}}),"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var Vc=cn({maxPool_:function(t,e,n,r,o){return Uc(t,e,n,1,r,o)}}),Gc=cn({avgPool_:function(t,e,n,r,o){return zc(t,e,n,1,r,o)}}),Hc=cn({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=$e(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])),b(ho(a,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"}));var c,l=eo(s.shape,e,a,o,r),h=[l.dilationHeight,l.dilationWidth];c="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]]}))}([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var d=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]]})),c=e.map((function(t,e){return[0,i[e]]}));return[u,c]}([l.inHeight,l.inWidth],h,c),p=f[0],v=f[1],m=d?r:"valid",g=d?s:mr(s,h,p),y=("avg"===n?function(){return zc(g,e,a,1,m)}:function(){return Uc(g,e,a,1,m)})(),x=d?y:$n(y,h,v);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),qc=cn({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=$e(t,"x","maxPool3d"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),b(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),b("NDHWC"===a,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),b(ho(n,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&b(k(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=no(u.shape,e,n,i,r,o,a),h=Bt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,l);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=$e(t,"dy","maxPool3dBackprop"),c=$e(e,"input","maxPool3dBackprop"),l=$e(n,"output","maxPool3dBackprop"),h=u,d=c,f=l,p=!1;4===c.rank&&(p=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),f=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]));b(5===h.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."})),b(5===d.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+d.rank+"."})),b(5===f.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+f.rank+"."})),null==a&&(a=[1,1,1]);b(ho(o,a),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),null!=s&&b(k(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var v=no(d.shape,r,o,a,i,s),m=Bt.runKernelFunc((function(t){return t.maxPool3dBackprop(h,d,f,v)}),{dy5D:h,input5D:d});if(p)return m.as4D(m.shape[1],m.shape[2],m.shape[3],m.shape[4]);return m}(t,s,u,e,n,i,r,o)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Kc=cn({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=$e(t,"x","avgPool3d","float32"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),b(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),b("NDHWC"===a,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),b(ho(n,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&b(k(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=no(u.shape,e,n,i,r,o,a),h=Bt.runKernelFunc((function(t){return t.avgPool3d(u,l)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=$e(t,"dy","avgPool3dBackprop"),u=$e(e,"input","avgPool3dBackprop"),c=s,l=u,h=!1;4===u.rank&&(h=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),l=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]));b(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),b(5===l.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."})),null==o&&(o=[1,1,1]);b(ho(r,o),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"})),null!=i&&b(k(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var d=no(l.shape,n,r,o,a,i),f=Bt.runKernelFunc((function(t){return t.avgPool3dBackprop(c,l,d)}),{dy5D:c,input5D:l});if(h)return f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]);return f}(t,u,e,n,i,r,o)}}}));return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}});var jc=cn({slice_:function(t,e,n){var r,o,a=$e(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){b(-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:(b(-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])})),Br(a,r,o);var i=a.shape,s={begin:r,size:o};return Bt.runKernelFunc((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)}}}),"Slice",s)}}),Xc=cn({slice1d_:function(t,e,n){var r=$e(t,"x","slice1d");return b(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),jc(r,[e],[n])}}),Yc=cn({slice2d_:function(t,e,n){var r=$e(t,"x","slice2d");return b(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),jc(r,e,n)}}),$c=cn({slice3d_:function(t,e,n){var r=$e(t,"x","slice3d");return b(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),jc(r,e,n)}}),Qc=cn({slice4d_:function(t,e,n){var r=$e(t,"x","slice4d");return b(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),jc(r,e,n)}});function Jc(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(en(e.shape,r))),t.rank<n.rank&&(t=t.reshape(en(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}var Zc=cn({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","all","bool"),o=F(e,r.shape),a=o,i=rn(a,r.rank);null!=i&&(r=r.transpose(i),a=an(a.length,r.rank));var s=Bt.runKernelFunc((function(t){return t.all(r,a)}),{$x:r});if(n){var u=en(s.shape,o);return s.reshape(u)}return s}}),tl=cn({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","any","bool"),o=F(e,r.shape),a=o,i=rn(a,r.rank);null!=i&&(r=r.transpose(i),a=an(a.length,r.rank));var s=Bt.runKernelFunc((function(t){return t.any(r,a)}),{$x:r});if(n){var u=en(s.shape,o);return s.reshape(u)}return s}}),el=cn({argMax_:function(t,e){void 0===e&&(e=0);var n=$e(t,"x","argMax");null==e&&(e=0);var r=F(e,n.shape),o=rn(r,n.rank);null!=o&&(n=n.transpose(o),r=an(r.length,n.rank));var a={axis:r[0]},i=[n];return Bt.runKernelFunc((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 Dn(n)}}}),"ArgMax",a,i)}}),nl=cn({argMin_:function(t,e){void 0===e&&(e=0);var n=$e(t,"x","argMin");null==e&&(e=0);var r=F(e,n.shape),o=rn(r,n.rank);return null!=o&&(n=n.transpose(o),r=an(r.length,n.rank)),Bt.runKernelFunc((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 Dn(n)}}}))}}),rl=cn({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","logSumExp"),o=F(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=en(s.shape,o);return s.reshape(u)}return s}}),ol=cn({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","max"),o=r,a=F(e,r.shape),i=a,s=rn(i,r.rank);null!=s&&(r=r.transpose(s),i=an(i.length,r.rank));var u=[r],c=Bt.runKernelFunc((function(t,e){var n=t.max(r,i);return e([o,n]),n}),{x:r},(function(t,e){return Jc(t,e[1],e[0],a,s)}),"Max",{axes:i},u,[!0]);if(n){var l=en(c.shape,a);c=c.reshape(l)}return c}}),al=cn({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","mean"),o=F(e,r.shape),a=R(tn(r.shape,o)[1]);return qr((function(t){var r=vn(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(En(t.shape,"float32")).div(a)}}}))(r)}}),il=cn({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","min"),o=r,a=F(e,r.shape),i=a,s=rn(i,r.rank);null!=s&&(r=r.transpose(s),i=an(i.length,r.rank));var u=[r],c=Bt.runKernelFunc((function(t,e){var n=t.min(r,i);return e([o,n]),n}),{x:r},(function(t,e){return Jc(t,e[1],e[0],a,s)}),"Min",{axes:i},u,[!0]);if(n){var l=en(c.shape,a);c=c.reshape(l)}return c}}),sl=cn({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=F(e,(t=$e(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=en(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)}}}),ul=cn({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=F(e,r.shape);return qr((function(t){var e=rn(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=an(r.length,t.rank));var i=function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(En(t.shape,"float32"))},s={axes:r},u=Bt.runKernelFunc((function(t){return t.sum(a,r)}),{x:a},(function(t){return{x:function(){return i(t)}}}),"Sum",s);if(n){var c=en(u.shape,o);u=u.reshape(c)}return{value:u,gradFunc:i}}))(r)}}),cl=cn({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=$e(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=F(e,r.shape),a=rn(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=an(i.length,r.rank));var u=Bt.runKernelFunc((function(t){return t.prod(s,i)}),{permutedX:s});if(n){var c=en(u.shape,o);u=u.reshape(c)}return u}});var ll=cn({elu_:function(t){var e=$e(t,"x","elu");return Bt.runKernelFunc((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 Bt.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),hl=cn({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=$e(t,"x","leakyRelu");return Vu(vn(e).mul(n),n)}}),dl=cn({prelu_:function(t,e){var n=$e(t,"x","prelu"),r=$e(e,"alpha","prelu");return Bt.runKernelFunc((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 Fu(o,t,t.mul(r))},alpha:function(){var e=Fu(o,Dn(t),t.mul(n)),a=Zr(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}}),"Prelu")}}),fl=cn({relu_:function(t){var e=$e(t,"x","relu");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((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())}}}),"Relu")}}),pl=cn({relu6_:function(t){var e=$e(t,"x","relu6");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),vl=cn({selu_:function(t){var e=$e(t,"x","selu");return Bt.runKernelFunc((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(vn(0)),r=vn(Qi),o=vn(Ji),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return Fu(e,a,i)}}}))}});var ml=cn({transpose_:function(t,e){var n=$e(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),b(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){b(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)return n.clone();var r={perm:e};return Bt.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},(function(t){var n=on(e);return{x:function(){return t.transpose(n)}}}),"Transpose",r)}});var gl=cn({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=$e(t,"x","localResponseNormalization");b(4===a.rank||3===a.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+a.rank+"."})),b(k(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=Bt.runKernelFunc((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 Bt.runKernelFunc((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 yl=cn({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){void 0===r&&(r=null);if(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(vn(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=$e(t,"x","norm"),e,n),a=o.shape;if(r){var i=F(n,t.shape);a=en(o.shape,i)}return o.reshape(a)}});var xl=cn({basicLSTMCell_:function(t,e,n,r,o,a){var i=$e(t,"forgetBias","basicLSTMCell"),s=$e(e,"lstmKernel","basicLSTMCell"),u=$e(n,"lstmBias","basicLSTMCell"),c=$e(r,"data","basicLSTMCell"),l=$e(o,"c","basicLSTMCell"),h=$e(a,"h","basicLSTMCell"),d=c.concat(h,1).matMul(s).add(u),f=d.shape[0],p=d.shape[1]/4,v=[f,p],m=d.slice([0,0],v),g=d.slice([0,p],v),y=d.slice([0,2*p],v),x=d.slice([0,3*p],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(l.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),bl=cn({multiRNNCell_:function(t,e,n,r){for(var o=$e(e,"data","multiRNNCell"),a=Qe(n,"c","multiRNNCell"),i=Qe(r,"h","multiRNNCell"),s=o,u=[],c=0;c<t.length;c++){var l=t[c](s,a[c],i[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var h=[],d=[];for(c=0;c<u.length;c+=2)h.push(u[c]),d.push(u[c+1]);return[h,d]}});var wl=cn({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=$e(t,"v","movingAverage"),i=$e(e,"x","movingAverage"),s=$e(n,"decay","movingAverage");Tt(a,i),b(I(a.shape,i.shape),(function(){return"Shape mismatch in v and x"}));var u=vn(1),c=u.sub(s),l=i.sub(a).mul(c);if(o){b(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var h=$e(r,"step","movingAverage");l=l.div(u.sub($u(s,h)))}return a.add(l)}});var Cl=cn({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 c=$e(t,"x","stridedSlice"),l=Pr(s),h=c.shape.slice();l.forEach((function(t){e[t]=0,n[t]=1,h.splice(t,0,1)})),c=c.reshape(h);for(var d=0;d<c.rank;d++)e[d]=Wr(o,e,r,c.shape,d),n[d]=Ur(a,n,r,c.shape,d),r[d]=r[d]||1;var f=Pr(u);f.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var p=Lr(e,n,r),v=p.filter((function(t,e){return-1===f.indexOf(e)}));return r.every((function(t){return 1===t}))?jc(c,e,p).reshape(v):Bt.runKernelFunc((function(t){return t.stridedSlice(c,e,n,r)}),{$x:c}).reshape(v)}});var El=cn({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=$e(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=Bt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:a[0],indices:a[1]}}});var Rl=cn({scatterND_:function(t,e,n){var r=$e(t,"indices","scatterND","int32"),o=$e(e,"updates","scatterND");return _r(o,r,n),Bt.runKernelFunc((function(t){return t.scatterND(r,o,n)}),{indices:r,updates:o},null,"ScatterNd",{shape:n})}});var Il=cn({fft_:function(t){b("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),kl=cn({ifft_:function(t){b("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),Sl=cn({rfft_:function(t,e){b("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(Rn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=ln(n,u).as2D(o,r),l=Il(c),h=Math.floor(r/2)+1,d=hn(l),f=dn(l),p=d.split([h,r-h],d.shape.length-1),v=f.split([h,r-h],f.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=h,ln(p[0],v[0]).reshape(m)}}),Al=cn({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=kl(r);return hn(o)}var a=[n,2*(e-1)],i=hn(t).as2D(n,e),s=dn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(vn(-1)),l=i.concat(u,1),h=s.concat(c,1);return r=ln(l,h).as2D(a[0],a[1]),o=kl(r),hn(o)}}),Dl=Object.freeze({fft:Il,ifft:kl,rfft:Sl,irfft:Al});var Tl=cn({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=$e(t,"sparseIndices","sparseToDense","int32"),a=$e(e,"sparseValues","sparseToDense"),i=$e(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),Bt.runKernelFunc((function(t){return t.sparseToDense(o,a,n,i)}),{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var Nl=cn({gatherND_:function(t,e){var n=$e(e,"indices","gatherND","int32"),r=$e(t,"x","gatherND");return Bt.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}});var Fl=cn({diag_:function(t){var e=$e(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Bt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}});var _l=cn({dropout_:function(t,e,n,r){var o=$e(t,"x","dropout");if(b("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."})),b(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof xt?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(I(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=pr(a,0,1,"float32",r).add(i).floor().div(i);return o.mul(s)}});function Ol(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 mn(o,"float32")}var Ml=cn({hannWindow_:function(t){return Ol(t,.5,.5)}}),Bl=cn({hammingWindow_:function(t){return Ol(t,.54,.46)}}),Pl=cn({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(jc(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=Tn([jc(t,a,e-s),In([s],o)]);i.push(u),a+=n}return 0===i.length?gn([],[0,e]):Tn(i).as2D(i.length,e)}}),Ll=cn({stft_:function(t,e,n,r,o){var a;void 0===o&&(o=Ml),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=Pl(t,e,n),s=Xu(i,o(e)),u=[],c=0;c<i.shape[0];c++)u.push(Sl(s.slice([c,0],[1,e]),r));return Tn(u)}}),Wl=Object.freeze({hannWindow:Ml,hammingWindow:Bl,frame:Pl,stft:Ll});var Ul,zl=function(t,e,n){return void 0===n&&(n=1),r(this,void 0,void 0,(function(){var r,a,i,s,u,c,l,h,d,f,p,v,m,g;return o(this,(function(o){switch(o.label){case 0:return r=$e(t,"predictions","inTopK"),a=$e(e,"targets","inTopK"),b(r.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),b(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})),w(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],b(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(),c=[s.length/i,i],h=c[1],d=O("bool",l=c[0]),f=0;f<l;f++){for(p=f*h,v=s.subarray(p,p+h),m=[],g=0;g<v.length;g++)m.push({value:v[g],index:g});for(m.sort((function(t,e){return e.value-t.value})),d[f]=0,g=0;g<n;g++)if(m[g].index===u[f]){d[f]=1;break}}return t!==r&&r.dispose(),e!==a&&a.dispose(),[2,fn(d,a.shape,"bool")]}}))}))};(Ul=t.Reduction||(t.Reduction={}))[Ul.NONE=0]="NONE",Ul[Ul.MEAN=1]="MEAN",Ul[Ul.SUM=2]="SUM",Ul[Ul.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";var Vl=cn({absoluteDifference_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=$e(e,"labels","absoluteDifference"),i=$e(n,"predictions","absoluteDifference"),s=null;null!=r&&(s=$e(r,"weights","absoluteDifference")),w(a.shape,i.shape,"Error in absoluteDifference: ");var u=a.sub(i).abs();return Gl(u,s,o)}}),Gl=cn({computeWeightedLoss_:function(e,n,r){void 0===r&&(r=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=$e(e,"losses","computeWeightedLoss"),a=null;null!=n&&(a=$e(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(vn(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(vn(o.size));var c=a.mul(En(o.shape)).notEqual(vn(0)).sum().toFloat();return i.sum().div(c)}throw Error("Unknown reduction: "+r)}}),Hl=cn({cosineDistance_:function(e,n,r,o,a){void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=$e(e,"labels","cosineDistance"),s=$e(n,"predictions","cosineDistance"),u=null;null!=o&&(u=$e(o,"weights","cosineDistance")),w(i.shape,s.shape,"Error in cosineDistance: ");var c=vn(1).sub(i.mul(s).sum(r,!0));return Gl(c,u,a)}}),ql=cn({hingeLoss_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=$e(e,"labels","hingeLoss"),i=$e(n,"predictions","hingeLoss"),s=null;null!=r&&(s=$e(r,"weights","hingeLoss")),w(a.shape,i.shape,"Error in hingeLoss: ");var u=vn(1);a=vn(2).mul(a).sub(u);var c=u.sub(a.mul(i)).relu();return Gl(c,s,o)}}),Kl=cn({huberLoss_:function(e,n,r,o,a){void 0===o&&(o=1),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=$e(e,"labels","huberLoss"),s=$e(n,"predictions","huberLoss"),u=null;null!=r&&(u=$e(r,"weights","huberLoss")),w(i.shape,s.shape,"Error in huberLoss: ");var c=vn(o),l=s.sub(i).abs(),h=Hu(l,c),d=l.sub(h),f=vn(.5).mul(h.square()).add(c.mul(d));return Gl(f,u,a)}}),jl=cn({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=$e(e,"labels","logLoss"),s=$e(n,"predictions","logLoss"),u=null;null!=r&&(u=$e(r,"weights","logLoss")),w(i.shape,s.shape,"Error in logLoss: ");var c=vn(1),l=vn(o),h=i.mul(s.add(l).log()).neg().sub(c.sub(i).mul(c.sub(s).add(l).log()));return Gl(h,u,a)}}),Xl=cn({meanSquaredError_:function(e,n,r,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=$e(e,"labels","meanSquaredError"),i=$e(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=$e(r,"weights","meanSquaredError")),w(a.shape,i.shape,"Error in meanSquaredError: ");var u=a.squaredDifference(i);return Gl(u,s,o)}}),Yl=cn({sigmoidCrossEntropy_:function(e,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=$e(e,"multiClassLabels","sigmoidCrossEntropy"),s=$e(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=$e(r,"weights","sigmoidCrossEntropy")),w(i.shape,s.shape,"Error in sigmoidCrossEntropy: "),o>0){var c=vn(o),l=vn(1),h=vn(.5);i=i.mul(l.sub(c)).add(h.mul(c))}var d=function(t,e){var n=$e(t,"labels","sigmoidCrossEntropyWithLogits"),r=$e(e,"logits","sigmoidCrossEntropyWithLogits");w(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 Gl(d,u,a)}}),$l=cn({softmaxCrossEntropy_:function(e,n,r,o,a){void 0===o&&(o=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=$e(e,"onehotLabels","softmaxCrossEntropy"),s=$e(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=$e(r,"weights","softmaxCrossEntropy")),w(i.shape,s.shape,"Error in softmaxCrossEntropy: "),o>0){var c=vn(o),l=vn(1),h=vn(i.shape[1]);i=i.mul(l.sub(c)).add(c.div(h))}var d=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 qr((function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);r([t,a]);return{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=en(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 Gl(d,u,a)}}),Ql=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:Vl,computeWeightedLoss:Gl,cosineDistance:Hl,hingeLoss:ql,huberLoss:Kl,logLoss:jl,meanSquaredError:Xl,sigmoidCrossEntropy:Yl,softmaxCrossEntropy:$l});function Jl(t,e){return void 0===e&&(e=!1),Bt.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=rr(n),a=t.clone(),i=gn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,c=function(t){var e,u=a,c=s,l=o;e=Bt.tidy((function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),c=a.slice([t,t],[1,1]),l=gn([[-1]]).where(c.greater(0),gn([[1]])),h=c.sub(l.mul(u)),d=e.div(h);s=1===d.shape[0]?i.clone():i.concat(d.slice([1,0],[d.shape[0]-1,d.shape[1]]),0);var f=l.matMul(h).div(u).neg(),p=a.slice([t,0],[n-t,r]),v=f.mul(s);if(0===t)a=p.sub(v.matMul(s.transpose().matMul(p)));else{var m=p.sub(v.matMul(s.transpose().matMul(p)));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],qe([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]}))}var Zl=cn({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=$e(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var o=r.shape,a=r.shape.slice(-2),i=a[0],s=a[1];if(!(e<=i))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+i+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=i),n<0&&(n=s);var u=Sn(0,i,1,"int32").reshape([-1,1]),c=Sn(0,s,1,"int32"),l=Zu(u,c),h=Au(l.lessEqual(vn(+e,"int32")),l.greaterEqual(vn(-n,"int32"))),d=Rn([i,s],r.dtype);return yr(wr(r.reshape([-1,i,s])).map((function(t){return Fu(h,t,d)}))).reshape(o)}}),th=cn({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,b(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){b(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=Mn(t,t.shape[0],0).map((function(t){return gr(t,[0])}));b(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(Bt.tidy((function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=ul(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(yl(e,"euclidean"))})))};for(o=0;o<t.length;++o)s(o);return e?yr(a,0):a}}),eh=cn({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 Jl(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=wr(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=Jl(t,e),r=n[0],i=n[1];o.push(r),a.push(i)})),[yr(o,0).reshape(t.shape),yr(a,0).reshape(t.shape)]}}),nh=Object.freeze({bandPart:Zl,gramSchmidt:th,qr:eh});function rh(t,e,n,r,o,a){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY),null==a&&(a=0);var i=t.shape[0];return n=Math.min(n,i),b(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),b(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),b(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),b(1===e.rank,(function(){return"scores must be a 1D tensor"})),b(e.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]})),b(0<=a&&a<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:a}}var oh=cn({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=$e(t,"images","resizeBilinear");b(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),b(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=Bt.runKernelFunc((function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)}),{x:o},(function(t,e){return{x:function(){return Bt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),ah=cn({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=$e(t,"images","resizeNearestNeighbor");b(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),b(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),b("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=Bt.runKernelFunc((function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)}),{batchImages:o},(function(t,e){return{batchImages:function(){return Bt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),ih=cn({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=$e(t,"boxes","nonMaxSuppression"),i=$e(e,"scores","nonMaxSuppression"),s=rh(a,i,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return Bt.runKernelFunc((function(t){return t.nonMaxSuppression(a,i,n,r,o)}),{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),sh=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,c,l,h,d;return o(this,(function(o){switch(o.label){case 0:return r=$e(t,"boxes","nonMaxSuppressionAsync"),s=$e(e,"scores","nonMaxSuppressionAsync"),u=rh(r,s,n,a,i),n=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,Promise.all([r.data(),s.data()])];case 1:return c=o.sent(),l=c[0],h=c[1],d=Ro(l,h,n,a,i),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,d]}}))}))},uh=cn({nonMaxSuppressionWithScore_:function(t,e,n,r,o,a){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===a&&(a=0);var i=$e(t,"boxes","nonMaxSuppression"),s=$e(e,"scores","nonMaxSuppression"),u=rh(i,s,n,r,o,a),c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},l=Bt.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),ch=function(t,e,n,a,i,s){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),void 0===s&&(s=0),r(this,void 0,void 0,(function(){var r,u,c,l,h,d,f;return o(this,(function(o){switch(o.label){case 0:return r=$e(t,"boxes","nonMaxSuppressionAsync"),u=$e(e,"scores","nonMaxSuppressionAsync"),c=rh(r,u,n,a,i,s),n=c.maxOutputSize,a=c.iouThreshold,i=c.scoreThreshold,s=c.softNmsSigma,[4,Promise.all([r.data(),u.data()])];case 1:return l=o.sent(),h=l[0],d=l[1],f=Io(h,d,n,a,i,s),r!==t&&r.dispose(),u!==e&&u.dispose(),[2,f]}}))}))},lh=cn({cropAndResize_:function(t,e,n,r,o,a){var i=$e(t,"image","cropAndResize"),s=$e(e,"boxes","cropAndResize","float32"),u=$e(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return b(4===i.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),b(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),b(1===u.rank&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),b(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),b(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),b("bilinear"===o||"nearest"===o,(function(){return"method must be bilinear or nearest, but was "+o})),Bt.runKernelFunc((function(t,e){return t.cropAndResize(i,s,u,r,o,a)}),{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:r})}}),hh=Object.freeze({resizeBilinear:oh,resizeNearestNeighbor:ah,nonMaxSuppression:ih,nonMaxSuppressionAsync:sh,nonMaxSuppressionWithScore:uh,nonMaxSuppressionWithScoreAsync:ch,cropAndResize:lh}),dh=function(t,e){return!(t>0)||"linear"===e},fh=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},ph=function(t,e){var n=e,r=Zr(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},vh=function(t,e,n){if("linear"===e)return t;if("relu"===e)return fl(t);if("elu"===e)return ll(t);if("relu6"===e)return pl(t);if("prelu"===e)return dl(t,n);throw new Error("Unknown fused activation "+e+".")};var mh=cn({fusedMatMul_: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,c=t.activation,l=void 0===c?"linear":c,h=t.preluActivationWeights;if(!1===dh(Bt.state.gradientDepth,l)){var d=Fc(n,r,a,s);return null!=u&&(d=Ou(d,u)),vh(d,l,h)}var f=$e(n,"a","fused matMul"),p=$e(r,"b","fused matMul");e=Dt(f,p),f=e[0],p=e[1];var v=a?f.shape[f.rank-2]:f.shape[f.rank-1],m=s?p.shape[p.rank-1]:p.shape[p.rank-2],g=a?f.shape[f.rank-1]:f.shape[f.rank-2],y=s?p.shape[p.rank-2]:p.shape[p.rank-1],x=f.shape.slice(0,-2),w=p.shape.slice(0,-2),C=R(x),E=R(w);b(f.rank>=2&&p.rank>=2&&f.rank===p.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+f.rank+" and "+p.rank+"."})),b(I(x,w),(function(){return"Error in fused matMul: outer dimensions ("+x+") and ("+w+") of Tensors with shapes "+f.shape+" and "+p.shape+" must match."})),b(v===m,(function(){return"Error in fused matMul: inner shapes ("+v+") and ("+m+") of Tensors with shapes "+f.shape+" and "+p.shape+" and transposeA="+a+" and transposeB="+s+" must match."}));var k,S,A=f.shape.slice(0,-2).concat([g,y]),D=a?f.as3D(C,v,g):f.as3D(C,g,v),T=s?p.as3D(E,y,m):p.as3D(E,m,y);null!=u&&to(A,(k=Dt(k=$e(u,"bias","fused matMul"),f)[0]).shape),null!=h&&(S=$e(h,"prelu weights","fused matMul"));var N={a:D,b:T};null!=u&&(N.bias=k),null!=h&&(N.preluActivationWeights=S);var F=[D,T];return Bt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:D,b:T,transposeA:a,transposeB:s,bias:k,activation:l,preluActivationWeights:S});return e([D,T,n]),n}),N,(function(t,e){var n=e[0],r=e[1],o=e[2],i=fh(t,o,l),c={};return null!=u&&(c={bias:function(){return ph(k,i)}}),a||s?!a&&s?Object.assign({a:function(){return i.matMul(r,!1,!1)},b:function(){return i.matMul(n,!0,!1)}},c):a&&!s?Object.assign({a:function(){return r.matMul(i,!1,!0)},b:function(){return n.matMul(i,!1,!1)}},c):Object.assign({a:function(){return r.matMul(i,!0,!0)},b:function(){return i.matMul(n,!0,!0)}},c):Object.assign({a:function(){return i.matMul(r,!1,!0)},b:function(){return n.matMul(i,!0,!1)}},c)}),"_FusedMatMul",{transposeA:a,transposeB:s,activation:l},F,[!0]).reshape(A)}}),gh=cn({fusedConv2d_: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,c=t.dimRoundingMode,l=t.bias,h=t.activation,d=void 0===h?"linear":h,f=t.preluActivationWeights;if(d=d||"linear",!1===dh(Bt.state.gradientDepth,d)){var p=Cc(e,n,r,o,i,u,c);return null!=l&&(p=Ou(p,l)),vh(p,d,f)}var v=$e(e,"x","conv2d"),m=$e(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])),b(4===g.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),b(4===m.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."})),null!=c&&b(k(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."})),b(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]+"."})),b(ho(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),b("NHWC"===i,(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var x,w,C=ro(g.shape,m.shape,r,u,o,c);null!=l&&(x=Dt(x=$e(l,"bias","fused conv2d"),v)[0],to(C.outShape,x.shape)),null!=f&&(w=$e(f,"prelu weights","fused conv2d"));var E={x:g,filter:m};null!=l&&(E.bias=x),null!=f&&(E.preluActivationWeights=w);var R=[m,g],I=Bt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:g,filter:m,convInfo:C,bias:x,activation:d,preluActivationWeights:w});return e([m,g,n]),n}),E,(function(t,e){var n=e,a=n[0],i=n[1],s=n[2],c=fh(t,s,d);b(lo(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!=l&&(h={bias:function(){return ph(x,c)}}),Object.assign({x:function(){return Ic(i.shape,c,a,r,o)},filter:function(){return Rc(i,c,a.shape,r,o)}},h)}),"FusedConv2D",{convInfo:C,activation:d},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),yh=cn({fusedDepthwiseConv2d_: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,c=t.dimRoundingMode,l=t.bias,h=t.activation,d=void 0===h?"linear":h,f=t.preluActivationWeights;if(!1===dh(Bt.state.gradientDepth,d)){var p=kc(e,n,r,o,i,u,c);return null!=l&&(p=Ou(p,l)),vh(p,d,f)}var v=$e(e,"x","depthwiseConv2d"),m=$e(n,"filter","depthwiseConv2d"),g=v,y=!1;3===v.rank&&(y=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),b(4===g.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),b(4===m.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."})),b(g.shape[3]===m.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+m.shape[2]+"."})),null==u&&(u=[1,1]),b(ho(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=c&&b(k(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."}));var x,w,C=ro(g.shape,m.shape,r,u,o,c,!0);null!=l&&(x=Dt(x=$e(l,"bias","fused conv2d"),v)[0],to(C.outShape,x.shape)),null!=f&&(w=$e(f,"prelu weights","fused depthwiseConv2d"));var E={x:g,filter:m};null!=l&&(E.bias=x),null!=f&&(E.preluActivationWeights=w);var R=[m,g],I=Bt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:g,filter:m,convInfo:C,bias:x,activation:d,preluActivationWeights:w});return e([m,g,n]),n}),E,(function(t,e){b(lo(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],o=e[2],a=fh(t,o,d),i={};return null!=l&&(i={bias:function(){return ph(x,a)}}),Object.assign({x:function(){return Sc(r.shape,a,n,C)},filter:function(){return Ac(r,a,n.shape,C)}},i)}),"FusedDepthwiseConv2D",{convInfo:C,activation:d},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),xh=Object.freeze({matMul:mh,conv2d:gh,depthwiseConv2d:yh}),bh=Object.freeze({image:hh,linalg:nh,losses:Ql,spectral:Dl,fused:xh,signal:Wl,square:Ns,squaredDifference:_s,conv1d:wc,conv2d:Cc,conv3d:Ec,depthwiseConv2d:kc,separableConv2d:Dc,conv2dTranspose:Tc,conv3dTranspose:Nc,op:cn,batchNormalization2d:bu,batchNormalization3d:wu,batchNormalization4d:Cu,batchNormalization:Eu,batchNorm:Ru,batchNorm2d:Iu,batchNorm3d:ku,batchNorm4d:Su,booleanMaskAsync:gc,complex:ln,real:hn,imag:dn,concat:Tn,concat1d:Nn,concat2d:Fn,concat3d:_n,concat4d:On,split:Mn,matMul:Fc,dot:_c,outerProduct:Oc,reverse:Mc,reverse1d:Bc,reverse2d:Pc,reverse3d:Lc,reverse4d:Wc,maxPool:Vc,avgPool:Gc,pool:Hc,maxPool3d:qc,avgPool3d:Kc,slice:jc,slice1d:Xc,slice2d:Yc,slice3d:$c,slice4d:Qc,abs:Os,acos:Ms,acosh:Bs,asin:Ps,asinh:Ls,atan:Ws,atanh:Us,ceil:zs,clipByValue:Vs,cos:Gs,cosh:Hs,erf:qs,exp:Ks,expm1:js,floor:Xs,log:Ys,log1p:$s,logSigmoid:Qs,neg:Js,reciprocal:Zs,round:tu,rsqrt:eu,sigmoid:nu,sign:ru,isNaN:ou,isInf:au,isFinite:iu,sin:su,sinh:uu,softplus:cu,sqrt:lu,step:hu,tan:du,tanh:fu,all:Zc,any:tl,argMax:el,argMin:nl,logSumExp:rl,max:ol,mean:al,min:il,moments:sl,sum:ul,prod:cl,equal:ec,equalStrict:nc,greater:rc,greaterEqual:oc,greaterEqualStrict:ac,greaterStrict:ic,less:sc,lessEqual:uc,lessEqualStrict:cc,lessStrict:lc,notEqual:hc,notEqualStrict:dc,add:Ou,addN:Mu,addStrict:Bu,atan2:Pu,div:Lu,divNoNan:Wu,divStrict:Uu,floorDiv:zu,maximum:Vu,maximumStrict:Gu,minimum:Hu,minimumStrict:qu,mod:Ku,modStrict:ju,mul:Xu,mulStrict:Yu,pow:$u,powStrict:Qu,squaredDifferenceStrict:Ju,sub:Zu,subStrict:tc,elu:ll,leakyRelu:hl,prelu:dl,relu:fl,relu6:pl,selu:vl,logicalAnd:Au,logicalNot:Du,logicalOr:Tu,logicalXor:Nu,where:Fu,whereAsync:_u,buffer:Xn,print:Yn,batchToSpaceND:$n,broadcastTo:Qn,cast:Jn,clone:Zn,cumsum:tr,depthToSpace:er,expandDims:nr,eye:rr,multinomial:or,oneHot:ar,pad:ir,pad1d:sr,pad2d:ur,pad3d:cr,pad4d:lr,rand:hr,randomNormal:dr,randomGamma:fr,randomUniform:pr,reshape:vr,spaceToBatchND:mr,squeeze:gr,stack:yr,tile:xr,truncatedNormal:br,unstack:wr,setdiff1dAsync:Cr,fill:In,linspace:kn,ones:En,range:Sn,scalar:vn,tensor:fn,tensor1d:mn,tensor2d:gn,tensor3d:yn,tensor4d:xn,tensor5d:bn,tensor6d:wn,variable:Cn,zeros:Rn,onesLike:An,zerosLike:Dn,transpose:ml,softmax:jr,logSoftmax:Xr,localResponseNormalization:gl,norm:yl,gather:vc,unsortedSegmentSum:mc,basicLSTMCell:xl,multiRNNCell:bl,movingAverage:wl,stridedSlice:Cl,topk:El,scatterND:Rl,fft:Il,ifft:kl,rfft:Sl,irfft:Al,sparseToDense:Tl,gatherND:Nl,diag:Fl,dropout:_l,hannWindow:Ml,hammingWindow:Bl,frame:Pl,stft:Ll,inTopKAsync:zl});function wh(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&b("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function Ch(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("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var Eh=function(t){function e(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new Yr(e,Bt),e}return n(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,s().get("IS_NODE")&&je("\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============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},e.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},e.prototype.numDataIds=function(){return this.data.numDataIds()},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?yo(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 nt(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return Xn(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Bt.makeTensorFromDataId(r,e,n,this)},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=Z(),t(),[2,{kernelMs:Z()-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=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Bt.keep(t.clone()),imag:Bt.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.slice=function(t,e,n){if(wh(t,"slice"),zr(t.shape,e,n)){var r=Vr(e,t.strides),o=R(n);return fn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var a=Xn(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){wh(t,"stridedSlice");var o=Lr(e,n,r);if(o.some((function(t){return 0===t})))return fn([],o);for(var a=Xn(o,t.dtype),i=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];a.set.apply(a,[i.get.apply(i,c)].concat(u))}return a.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=Xn([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){wh(t,"reverse");for(var n=Xn(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 hn(t)})),o=t.map((function(t){return dn(t)}));return ln(this.concat(r,e),this.concat(o,e))}var a=t.map((function(t){var n=R(t.shape.slice(e));return t.as2D(-1,n)})),i=un(a.map((function(t){return t.shape})),1),s=Xn(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 c=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]+c,u=0;u<t.shape[1];++u)s[a+u]=e[r++];c+=t.shape[1]}))}var l=un(t.map((function(t){return t.shape})),e);return fn(s,l,t[0].dtype)},e.prototype.neg=function(t){return wh(t,"neg"),this.multiply(vn(-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,St(t.dtype,e.dtype),(function(t,e){return t+e}))},e.prototype.addN=function(t){var e=this;wh(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=Xn(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.softmax=function(t,e){var n=F([e],t.shape),r=this.max(t,n),o=en(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return this.realDivide(i,s)},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,St(t.dtype,e.dtype),(function(t,e){return t-e}))},e.prototype.pow=function(t,e){return wh([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){wh([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),c=this.readSync(e.dataId),l=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],h=l[0],d=l[1],f=l[2],p=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=p[0],m=p[1],g=p[2],y=a*i,x=Xn([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 R=0;R<i;R+=w)for(var I=0;I<o;I+=w)for(var k=Math.min(E+w,a),S=Math.min(R+w,i),A=Math.min(I+w,o),D=E;D<k;D++)for(var T=R;T<S;T++){for(var N=0,F=I;F<A;F++)N+=u[C*h+D*d+F*f]*c[F*v+T*m+C*g];b[C*y+(D*i+T)]+=N}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=Ch(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,St(t.dtype,e.dtype),(function(t,e){return t*e}))},e.prototype.realDivide=function(t,e){wh([t,e],"realDivide");return this.broadcastedBinaryOp(t,e,"float32",(function(t,e){return t/e}))},e.prototype.floorDiv=function(t,e){wh([t,e],"floorDiv");return this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},e.prototype.sum=function(t,e){wh(t,"sum"),nn("sum",e,t.rank);for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,St(t.dtype,"int32")),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=0,d=0;d<i;++d)h+=u[l+d];s[c]=h}return a},e.prototype.prod=function(t,e){wh(t,"sum");for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,St(t.dtype,"int32")),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=1,d=0;d<i;++d)h*=u[l+d];s[c]=h}return a},e.prototype.unsortedSegmentSum=function(t,e,n){wh(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=vn(a,"int32"),s=ec(i,e).asType("float32").mul(t).sum(0);r.push(s)}return yr(r)},e.prototype.argMin=function(t,e){wh(t,"argMin");var n=[e];nn("argMin",n,t.rank);for(var r=tn(t.shape,n),o=r[0],a=r[1],i=Rn(o,"int32"),s=R(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,d=c[h],f=0,p=0;p<s;++p){var v=c[h+p];v<d&&(d=v,f=p)}u[l]=f}return i},e.prototype.argMax=function(t,e){wh(t,"argMax");var n=[e];nn("argMax",n,t.rank);for(var r=tn(t.shape,n),o=r[0],a=r[1],i=Rn(o,"int32"),s=R(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,d=c[h],f=0,p=0;p<s;++p){var v=c[h+p];v>d&&(d=v,f=p)}u[l]=f}return i},e.prototype.cumsum=function(t,e,n,r){if(wh(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=St(t.dtype,"int32"),a=Rn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],c=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},l=0;l<s.length;l+=u)for(var h=0;h<u;h++){var d=c(l,h);if(0===h)i[d]=n?0:s[d];else{var f=c(l,h-1);i[d]=n?s[f]+i[f]:s[d]+i[f]}}return a},e.prototype.equal=function(t,e){return wh([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},e.prototype.notEqual=function(t,e){return wh([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},e.prototype.less=function(t,e){return wh([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},e.prototype.lessEqual=function(t,e){return wh([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},e.prototype.greater=function(t,e){return wh([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},e.prototype.greaterEqual=function(t,e){return wh([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},e.prototype.logicalNot=function(t){wh(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 this.makeOutput(n,t.shape,"bool")},e.prototype.logicalAnd=function(t,e){return wh([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},e.prototype.logicalOr=function(t,e){return wh([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},e.prototype.select=function(t,e,n){wh([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=Rn(e.shape,St(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:R(e.shape.slice(1)),l=0;l<r.length;l++)for(var h=0;h<c;h++)1===r[l]?s[u++]=o[l]:s[u++]=a[l];return i},e.prototype.where=function(t){wh([t],"where");var e=this.readSync(t.dataId);return _o(t.shape,e)},e.prototype.topk=function(t,e,n){return wh(t,"topk"),Fo(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){wh(t,"min"),nn("min",e,t.rank);for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],d=0;d<i;++d){var f=u[l+d];f<h&&(h=f)}s[c]=h}return a},e.prototype.minimum=function(t,e){return wh([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},e.prototype.mod=function(t,e){return wh([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){wh(t,"max"),nn("max",e,t.rank);for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],d=0;d<i;++d){var f=u[l+d];f>h&&(h=f)}s[c]=h}return a},e.prototype.maximum=function(t,e){return wh([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},e.prototype.all=function(t,e){wh(t,"all"),nn("all",e,t.rank);for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],d=0;d<i;++d){var f=u[l+d];h=h&&f}s[c]=h}return a},e.prototype.any=function(t,e){wh(t,"any"),nn("any",e,t.rank);for(var n=tn(t.shape,e),r=n[0],o=n[1],a=Rn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],d=0;d<i;++d){var f=u[l+d];h=h||f}s[c]=h}return a},e.prototype.squaredDifference=function(t,e){return wh([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},e.prototype.ceil=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.floor=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.sign=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){wh(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 this.makeOutput(n,t.shape,"bool")},e.prototype.isInf=function(t){wh(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 this.makeOutput(n,t.shape,"bool")},e.prototype.isFinite=function(t){wh(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 this.makeOutput(n,t.shape,"bool")},e.prototype.round=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.expm1=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.log=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.log1p=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.sqrt=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.rsqrt=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.reciprocal=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.linear=function(t){return t},e.prototype.relu=function(t){wh(t,"relu");for(var e=Rn(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.relu6=function(t){wh(t,"relu");for(var e=Rn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.min(Math.max(0,r[o]),6);return e},e.prototype.prelu=function(t,e){return wh([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},e.prototype.elu=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){wh([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 this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){wh(t,"selu");for(var e=Qi,n=Ji,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 this.makeOutput(r,t.shape,"float32")},e.prototype.clip=function(t,e,n){wh(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 this.makeOutput(r,t.shape,"float32")},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 this.makeOutput(e,t.shape,"float32")},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 this.makeOutput(e,t.shape,"float32")},e.prototype.int=function(t){wh(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 this.makeOutput(e,t.shape,"int32")},e.prototype.sigmoid=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.softplus=function(t){wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.sin=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.cos=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.tan=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.asin=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.acos=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.atan=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.atan2=function(t,e){return wh([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},e.prototype.sinh=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.cosh=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.tanh=function(t){wh(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=S(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asinh=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.acosh=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.atanh=function(t){wh(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 this.makeOutput(e,t.shape,"float32")},e.prototype.erf=function(t){wh(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=Math.sign(n[r]),a=Math.abs(n[r]),i=1/(1+.3275911*a);e[r]=o*(1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-a*a))}return this.makeOutput(e,t.shape,"float32")},e.prototype.step=function(t,e){void 0===e&&(e=0),wh(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 this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),a&&(s=Ch(this,s,a,i)),s},e.prototype.conv2d=function(t,e,n){wh([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,c="channelsLast"===n.dataFormat,l=Xn(n.outShape,t.dtype),h=t.strides[0],d=c?t.strides[1]:t.strides[2],f=c?t.strides[2]:1,p=c?1:t.strides[1],v=l.strides[0],m=c?l.strides[1]:l.strides[2],g=c?l.strides[2]:1,y=c?1:l.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=l.values,C=0;C<n.batchSize;++C)for(var E=C*h,R=C*v,I=0;I<n.outHeight;++I)for(var k=R+I*m,S=I*n.strideHeight-u,A=0;A<r;A++){var D=S+A*a;if(!(D<0||D>=n.inHeight))for(var T=A*e.strides[0],N=E+D*d,F=0;F<n.outWidth;++F)for(var _=k+F*g,O=F*n.strideWidth-s,M=0;M<o;M++){var B=O+M*i;if(!(B<0||B>=n.inWidth))for(var P=N+B*f,L=T+M*e.strides[1],W=0;W<n.inChannels;++W){for(var U=x[P+W*p],z=0;z<n.outChannels;++z)w[_+z*y]+=U*b[L+z];L+=n.outChannels}}}return l.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,c=n.padInfo.front,l=n.padInfo.left,h=n.padInfo.top,d=Xn(n.outShape,t.dtype),f=this.readSync(t.dataId),p=this.readSync(e.dataId),v=d.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],y=m*d.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*d.strides[1],w=x*n.strideDepth-c,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],k=0;k<n.outHeight;++k)for(var S=b+k*d.strides[2],A=k*n.strideHeight-h,D=0;D<o;D++){var T=A+D*s;if(!(T<0||T>=n.inHeight))for(var N=R+D*e.strides[1],F=I+T*t.strides[2],_=0;_<n.outWidth;++_)for(var O=S+_*n.outChannels,M=_*n.strideWidth-l,B=0;B<a;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=N+B*e.strides[2],W=F+P*n.inChannels,U=L,z=0;z<n.inChannels;++z){for(var V=f[W+z],G=0;G<n.outChannels;++G)v[O+G]+=V*p[U+G];U+=n.outChannels}}}}return d.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){wh([t,e],"conv2dDerInput");for(var r=Xn(n.inShape,"float32"),o=r.values,a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],h=n.batchSize,d=n.filterHeight,f=n.filterWidth,p=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=d-1-n.padInfo.top,R=f-1-n.padInfo.left,I="channelsLast"===C,k=r.strides[0],S=I?r.strides[1]:r.strides[2],A=I?r.strides[2]:1,D=I?1:r.strides[1],T=t.strides[0],N=I?t.strides[1]:t.strides[2],F=I?t.strides[2]:1,_=I?1:t.strides[1],O=0;O<h;++O)for(var M=0;M<p;++M)for(var B=0;B<v;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),W=Math.min(y,(d+P)/b),U=0;U<m;++U){for(var z=U-R,V=Math.max(0,Math.ceil(z/w)),G=Math.min(x,(f+z)/w),H=0,q=L;q<W;++q)for(var K=q*b-P,j=V;j<G;++j)for(var X=T*O+N*q+F*j,Y=u*(d-1-K)+c*(f-1-(j*w-z))+l*M,$=0;$<g;++$){H+=a[X+_*$]*i[Y+$]}o[k*O+S*B+A*U+D*M]=H}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=Xn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=a[3],l=this.readSync(t.dataId),h=t.strides,d=h[0],f=h[1],p=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,R=n.filterHeight,I=n.filterWidth,k=n.inChannels,S=n.inDepth,A=n.inHeight,D=n.inWidth,T=n.outChannels,N=n.outDepth,F=n.outHeight,_=n.outWidth,O=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=R-1-n.padInfo.top,W=I-1-n.padInfo.left,U=0;U<C;++U)for(var z=0;z<k;++z)for(var V=0;V<S;++V)for(var G=V-P,H=Math.max(0,Math.ceil(G/O)),q=Math.min(N,(E+G)/O),K=0;K<A;++K)for(var j=K-L,X=Math.max(0,Math.ceil(j/M)),Y=Math.min(F,(R+j)/M),$=0;$<D;++$){for(var Q=$-W,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(_,(I+Q)/B),tt=0,et=H;et<q;++et)for(var nt=et*O-G,rt=X;rt<Y;++rt)for(var ot=rt*M-j,at=J;at<Z;++at)for(var it=d*U+f*et+p*rt+v*at,st=y*(E-1-nt)+x*(R-1-ot)+b*(I-1-(at*B-Q))+w*z,ut=0;ut<T;++ut){tt+=l[it+ut]*m[st+ut]}o[i*U+s*V+u*K+c*$+z]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){wh([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=Xn(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,h=this.bufferSync(t),d=this.bufferSync(e),f=0;f<a;++f)for(var p=Math.max(0,Math.ceil((l-f)/r)),v=Math.min(n.outHeight,(n.inHeight+l-f)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((c-m)/o)),y=Math.min(n.outWidth,(n.inWidth+c-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=p;E<v;++E)for(var R=f+E*r-l,I=g;I<y;++I){var k=m+I*o-c;w+=s?h.get(C,R,k,x)*d.get(C,E,I,b):h.get(C,x,R,k)*d.get(C,b,E,I)}u.set(w,f,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,c=Xn(n.filterShape,"float32"),l=c.values,h=c.strides,d=h[0],f=h[1],p=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,R=E[0],I=E[1],k=E[2],S=E[3],A=n.padInfo.front,D=n.padInfo.left,T=n.padInfo.top,N=0;N<i;++N)for(var F=Math.max(0,Math.ceil((A-N)/r)),_=Math.min(n.outDepth,(n.inDepth+A-N)/r),O=N*d,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*f+O,W=0;W<u;++W)for(var U=Math.max(0,Math.ceil((D-W)/a)),z=Math.min(n.outWidth,(n.inWidth+D-W)/a),V=W*p+L,G=0;G<n.inChannels;++G)for(var H=G*v+V,q=0;q<n.outChannels;++q){for(var K=0,j=0;j<n.batchSize;++j)for(var X=j*R,Y=j*y,$=F;$<_;++$)for(var Q=(N+$*r-A)*I+X,J=$*x+Y,Z=B;Z<P;++Z)for(var tt=(M+Z*o-T)*k+Q,et=Z*b+J,nt=U;nt<z;++nt){var rt=nt*w+et;K+=C[(W+nt*a-D)*S+tt+G]*m[rt+q]}l[H+q]=K}return c.toTensor()},e.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return o&&(s=this.add(s,o)),a&&(s=Ch(this,s,a,i)),s},e.prototype.depthwiseConv2D=function(t,e,n){wh([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,c=n.outChannels/n.inChannels,l=Xn(n.outShape,t.dtype),h=this.readSync(t.dataId),d=this.readSync(e.dataId),f=l.values,p=0;p<n.batchSize;++p)for(var v=p*t.strides[0],m=p*l.strides[0],g=0;g<n.outHeight;++g)for(var y=m+g*l.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],R=0;R<n.outWidth;++R)for(var I=y+R*l.strides[2],k=R*n.strideWidth-u,S=0;S<o;++S){var A=k+S*i;if(!(A<0||A>=n.inWidth))for(var D=C+S*e.strides[1],T=E+A*n.inChannels,N=I,F=D,_=0;_<n.inChannels;++_){for(var O=h[T+_],M=0;M<c;++M)f[N+M]+=O*d[F+M];N+=c,F+=c}}}return l.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){wh([t,e],"depthwiseConv2DDerInput");for(var r=Xn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=this.readSync(t.dataId),l=t.strides,h=l[0],d=l[1],f=l[2],p=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,R=n.inWidth,I=n.outChannels,k=n.outHeight,S=n.outWidth,A=n.strideHeight,D=n.strideWidth,T=b-1-n.padInfo.top,N=w-1-n.padInfo.left,F=I/C,_=0;_<x;++_)for(var O=0;O<C;++O)for(var M=0;M<E;++M)for(var B=M-T,P=Math.max(0,Math.ceil(B/A)),L=Math.min(k,(b+B)/A),W=0;W<R;++W){for(var U=W-N,z=Math.max(0,Math.ceil(U/D)),V=Math.min(S,(w+U)/D),G=0,H=P;H<L;++H)for(var q=H*A-B,K=z;K<V;++K)for(var j=h*_+d*H+f*K,X=m*(b-1-q)+g*(w-1-(K*D-U))+y*O,Y=0;Y<F;++Y){G+=c[j+(O*F+Y)]*p[X+Y]}o[i*_+s*M+u*W+O]=G}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){wh([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=Xn(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,h=this.bufferSync(t),d=this.bufferSync(e),f=0;f<a;++f)for(var p=Math.max(0,Math.ceil((c-f)/r)),v=Math.min(n.outHeight,(n.inHeight+c-f)/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/l),w=x%l,C=0,E=0;E<n.batchSize;++E)for(var R=p;R<v;++R)for(var I=f+R*r-c,k=g;k<y;++k){var S=m+k*o-u;C+=h.get(E,I,S,b)*d.get(E,R,k,x)}s.set(C,f,m,b,w)}return s.toTensor()},e.prototype.tile=function(t,e){return wh(t,"tile"),No(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){wh(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=Xn(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),c=u.map((function(t,e){return t+o[e]}));i.set.apply(i,[a.get.apply(a,u)].concat(c))}return i.toTensor()},e.prototype.transpose=function(t,e){wh(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=Xn(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),c=0;c<u.length;c++)u[c]=s[e[c]];var l=a.locToIndex(u);a.values[l]=o[r]}return a.toTensor()},e.prototype.gather=function(t,e,n){wh([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=Xn(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),c=u.slice();c[n]=o[u[n]];var l=i.locToIndex(c);a.values[s]=i.values[l]}return a.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){wh([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),o=Er(t.shape,e,r),a=Rr(o.length,e.length),i=Ir(t.shape,e,r),s=kr(n,e.length),u=Sr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){wh([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=Er(i.shape,e,r,!1),u=Rr(s.length,e.length,!1),c=Ir(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.pool=function(t,e,n){wh(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,d=this.readSync(t.dataId),f=Xn(e.outShape,t.dtype),p=f.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-c,R=Math.max(0,E),I=Math.min(e.inHeight,s+E),k=x+C*m,S=0;S<e.outWidth;++S){for(var A=S*o-l,D=Math.max(0,A),T=Math.min(e.inWidth,u+A),N=h,F=0,_=0,O=R;O<I;O+=a){for(var M=b+O*t.strides[1],B=D;B<T;B+=i){var P=d[M+B*t.strides[2]+w];"max"===n&&P>N?N=P:"avg"===n&&(F+=P,_++)}if(isNaN(N))break}p[k+S*g+w]="avg"===n?F/_:N}return f.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=Xn(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h=this.bufferSync(t),d=0;d<e.batchSize;++d)for(var f=0;f<e.inChannels;++f)for(var p=0;p<e.outHeight;++p){for(var v=p*r-c,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-l,b=x;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,R=m;R<g;R+=a)for(var I=R-v,k=b;k<w;k+=i){var S=k-x,A=h.get(d,R,k,f);A>C&&(C=A,E=I*u+S)}n.set(E,d,p,y,f)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){wh([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,h=l-1-r.padInfo.left,d=c-1-r.padInfo.top,f=Xn(e.shape,"float32"),p=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-d,w=x-h,C=0,E=0;E<c;E+=s){var R=(b+E)/a;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/i;if(!(k<0||k>=r.outWidth||Math.floor(k)!==k)){var S=c*l-1-p.get(m,R,k,g)===E*l+I?1:0;if(0!==S)C+=v.get(m,R,k,g)*S}}}f.set(C,m,y,x,g)}return f.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){wh([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,d=c-1-n.padInfo.top,f=Xn(e.shape,"float32"),p=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-d,w=x-h,C=0,E=0;E<c;E+=s){var R=(b+E)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/o;if(!(k<0||k>=n.outWidth||Math.floor(k)!==k))C+=v.get(m,R,k,g)}}f.set(C*p,m,y,x,g)}return f.toTensor()},e.prototype.pool3d=function(t,e,n){wh(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.front,f=e.padInfo.top,p=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=Xn(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 R=E*x,I=E*t.strides[0],k=0;k<e.inChannels;++k)for(var S=0;S<e.outDepth;++S){for(var A=S*r-d,D=A;D<0;)D+=i;for(var T=Math.min(e.inDepth,c+A),N=R+S*b,F=0;F<e.outHeight;++F){for(var _=F*o-f,O=_;O<0;)O+=s;for(var M=Math.min(e.inHeight,l+_),B=N+F*w,P=0;P<e.outWidth;++P){for(var L=P*a-p,W=L;W<0;)W+=u;for(var U=Math.min(e.inWidth,h+L),z=B+P*C,V=v,G=0,H=0,q=D;q<T;q+=i){for(var K=I+q*t.strides[1],j=O;j<M;j+=s){for(var X=K+j*t.strides[2],Y=W;Y<U;Y+=u){var $=m[X+Y*t.strides[3]+k];if("max"===n&&$>V?V=$:"avg"===n&&(G+=$,H++),isNaN(V))break}if(isNaN(V))break}if(isNaN(V))break}y[z+k]="avg"===n?G/H:V}}}return g.toTensor()},e.prototype.avgPool3d=function(t,e){return wh(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){wh([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,h=n.dilationWidth,d=n.effectiveFilterDepth,f=n.effectiveFilterHeight,p=n.effectiveFilterWidth,v=d-1-n.padInfo.front,m=p-1-n.padInfo.left,g=f-1-n.padInfo.top,y=Xn(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 R=0;R<n.inHeight;++R)for(var I=0;I<n.inWidth;++I){for(var k=E-v,S=R-g,A=I-m,D=0,T=0;T<d;T+=c){var N=(k+T)/r;if(!(N<0||N>=n.outDepth||Math.floor(N)!==N))for(var F=0;F<f;F+=l){var _=(S+F)/o;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var O=0;O<p;O+=h){var M=(A+O)/a;if(!(M<0||M>=n.outWidth||Math.floor(M)!==M))D+=b.get(w,N,_,M,C)}}}y.set(D*x,w,E,R,I,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return wh(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Xn(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.front,f=e.padInfo.top,p=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-d,b=x;b<0;)b+=i;for(var w=Math.min(e.inDepth,c+x),C=0;C<e.outHeight;++C){for(var E=C*o-f,R=E;R<0;)R+=s;for(var I=Math.min(e.inHeight,l+E),k=0;k<e.outWidth;++k){for(var S=k*a-p,A=S;A<0;)A+=u;for(var D=Math.min(e.inWidth,h+S),T=Number.NEGATIVE_INFINITY,N=-1,F=b;F<w;F+=i)for(var _=F-x,O=R;O<I;O+=s)for(var M=O-E,B=A;B<D;B+=u){var P=B-S,L=v.get(m,F,O,B,g);L>=T&&(T=L,N=_*l*h+M*l+P)}n.set(N,m,y,C,k,g)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){wh([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,h=r.effectiveFilterDepth,d=r.effectiveFilterHeight,f=r.effectiveFilterWidth,p=h-1-r.padInfo.front,v=f-1-r.padInfo.left,m=d-1-r.padInfo.top,g=Xn(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 R=0;R<r.inWidth;++R){for(var I=C-p,k=E-m,S=R-v,A=0,D=0;D<h;D+=u){var T=(I+D)/a;if(!(T<0||T>=r.outDepth||Math.floor(T)!==T))for(var N=0;N<d;N+=c){var F=(k+N)/i;if(!(F<0||F>=r.outHeight||Math.floor(F)!==F))for(var _=0;_<f;_+=l){var O=(S+_)/s;if(!(O<0||O>=r.outWidth||Math.floor(O)!==O)){var M=h*d*f-1-y.get(b,T,F,O,w)===D*d*f+N*f+_?1:0;if(0!==M)A+=x.get(b,T,F,O,w)*M}}}}g.set(A,b,C,E,R,w)}return g.toTensor()},e.prototype.cast=function(t,e){return po(t,e,this)},e.prototype.reshape=function(t,e){return vo(t,e)},e.prototype.avgPool=function(t,e){return wh(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){wh(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(R([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],d=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,p=h[0]/d[0],v=h[1]/d[1],m=0;m<a;m++)for(var g=0;g<e;g++)for(var y=p*g,x=Math.floor(y),b=y-x,w=Math.min(i-1,Math.ceil(y)),C=m*t.strides[0]+x*t.strides[1],E=m*t.strides[0]+w*t.strides[1],I=0;I<n;I++)for(var k=v*I,S=Math.floor(k),A=k-S,D=Math.min(s-1,Math.ceil(k)),T=C+S*t.strides[2],N=E+S*t.strides[2],F=C+D*t.strides[2],_=E+D*t.strides[2],O=0;O<u;O++){var M=c[T+O],B=c[N+O],P=M+(c[F+O]-M)*A,L=P+(B+(c[_+O]-B)*A-P)*b;l[f++]=L}return fn(l,[a,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){wh([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),d=[n&&c>1?a-1:a,n&&l>1?i-1:i],f=[n&&c>1?c-1:c,n&&l>1?l-1:l],p=d[0]/f[0],v=d[1]/f[1],m=this.readSync(t.dataId),g=0,y=0;y<o;y++)for(var x=y*e.strides[0],b=0;b<c;b++)for(var w=b*p,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),R=x+C*e.strides[1],I=x+E*e.strides[1],k=w-C,S=1-k,A=0;A<l;A++)for(var D=A*v,T=Math.floor(D),N=Math.min(Math.ceil(D),i-1),F=D-T,_=1-F,O=R+T*e.strides[2],M=R+N*e.strides[2],B=I+T*e.strides[2],P=I+N*e.strides[2],L=S*_,W=S*F,U=k*_,z=k*F,V=0;V<s;V++){var G=m[g++];h[O+V]+=G*L,h[M+V]+=G*W,h[B+V]+=G*U,h[P+V]+=G*z}return xn(h,[o,i,a,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){wh(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(a*e*n*u),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],d=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=h[0]/d[0],p=h[1]/d[1],v=0,m=0;m<a;m++)for(var g=m*t.strides[0],y=0;y<e;y++)for(var x=f*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=p*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],R=0;R<u;R++){var I=c[E+R];l[v++]=I}return fn(l,[a,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){wh([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),d=this.readSync(t.dataId),f=[n&&c>1?a-1:a,n&&l>1?i-1:i],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=f[0]/p[0],m=f[1]/p[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 R=C+E*e.strides[1],I=Math.floor(E*g),k=Math.floor(I-x/2),S=0;S<i;S++)for(var A=R+S*e.strides[2],D=Math.floor(S*y),T=Math.floor(D-b/2),N=0;N<s;N++){for(var F=0,_=0;_<x;_++){var O=_+k;if(!(O<0||O>=c)){var M=C+O*t.strides[1],B=O*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>=l)){var W=M+L*t.strides[2],U=L*m;S===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(F+=d[W+N])}}}}h[A+N]=F}return xn(h,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,a){wh([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),d=l.length,f=c.length,p=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b<i.length;++b)h[b]=l[m++]+(i[b]-s[g++])*c[y++]/Math.sqrt(u[x++]+r),m>=d&&(m=0),g>=v&&(g=0),y>=f&&(y=0),x>=p&&(x=0);return xn(h,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){wh(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(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 c=s[r];u+=c*c}return u}for(var h=0;h<u;h++){var d=l(h),f=s[h]*Math.pow(n+r*d,-o);c[h]=f}return xn(c,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){wh(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=this.readSync(n.dataId),h=new Float32Array(t.size),d=t.size,f=0;f<d;f++){for(var p=f%s,v=f-p+Math.max(0,p-r),m=f-p+Math.min(s,p+r+1),g=0,y=v;y<m;y++)g+=Math.pow(c[y],2);g=a*g+o;for(y=v;y<m;y++){var x=-2*a*i*c[y]*l[f]/g;f===y&&(x+=Math.pow(g,-i)),x*=u[f],h[y]+=x}}return xn(h,t.shape)},e.prototype.multinomial=function(t,e,n,r){wh(t,"multinomial");for(var o=e?t:jr(t),a=o.shape[0],i=o.shape[1],s=Rn([a,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(o.dataId),l=0;l<a;++l){var h=l*i,d=new Float32Array(i-1);d[0]=c[h];for(var f=1;f<d.length;++f)d[f]=d[f-1]+c[h+f];for(var p=Hn(r.toString()),v=l*n,m=0;m<n;++m){var g=p();u[v+m]=d.length;for(var y=0;y<d.length;y++)if(g<d[y]){u[v+m]=y;break}}}return s},e.prototype.oneHot=function(t,e,n,r){wh(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 gn(o,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return wh(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=Xn(t.shape,"float32"),a=Xn(t.shape,"float32"),i=hn(t).as2D(n,r),s=dn(t).as2D(n,r),u=0;u<n;u++)for(var c=i.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),h=ln(c,l),d=this.readSync(this.fftImpl(h,e).dataId),f=0;f<r;f++){var p=xo(d,f);o.values[u*r+f]=p.real,a.values[u*r+f]=p.imag}return ln(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=ln(hn(o).div(vn(r)),dn(o).div(vn(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 ln(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=ln(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=ln(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var c=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),l=ln(c.real,c.imag).mul(u),h=i.add(l),d=i.sub(l),f=hn(h).concat(hn(d)),p=dn(h).concat(dn(d));return ln(f,p).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=wo(o*s,e,n),c=xo(t,s);a+=c.real*u.real-c.imag*u.imag,i+=c.real*u.imag+c.imag*u.real}n&&(a/=e,i/=e),bo(r,a,i,o)}return r},e.prototype.depthToSpace=function(t,e,n){b("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),b(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,c=i/(e*e),l=this.readSync(t.dataId),h=new Float32Array(r*s*u*c),d=0,f=0;f<r;++f)for(var p=0;p<s;++p)for(var v=Math.floor(p/e),m=p%e,g=0;g<u;++g)for(var y=Math.floor(g/e),x=(m*e+g%e)*c,w=0;w<c;++w){var C=w+x+i*(y+a*(v+o*f));h[d++]=l[C]}return xn(h,[r,s,u,c])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=to(t.shape,e.shape),a=Xn(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Jr(t.shape,o),c=Jr(e.shape,o),l=a.values;if(u.length+c.length===0)for(var h=0;h<l.length;++h)l[h]=r(i[h%i.length],s[h%s.length]);else{var d=this.bufferSync(t),f=this.bufferSync(e),p=function(n){var o=a.indexToLoc(n),h=o.slice(-t.rank);u.forEach((function(t){return h[t]=0}));var p=d.locToIndex(h),v=o.slice(-e.rank);c.forEach((function(t){return v[t]=0}));var m=f.locToIndex(v);l[n]=r(i[p],s[m])};for(h=0;h<l.length;++h)p(h)}return a.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=to(t.shape,e.shape),o=Xn(r,"float32"),a=Xn(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Jr(t.shape,r),c=Jr(e.shape,r),l=o.values,h=a.values;if(u.length+c.length===0)for(var d=0;d<l.length;d++){var f=d%i.length,p=d%s.length,v=n(i[2*f],i[2*f+1],s[2*p],s[2*p+1]);l[d]=v.real,h[d]=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),d=a.slice(-t.rank);u.forEach((function(t){return d[t]=0}));var f=m.locToIndex(d),p=a.slice(-e.rank);c.forEach((function(t){return p[t]=0}));var v=g.locToIndex(p),y=n(i[2*f],i[2*f+1],s[2*v],s[2*v+1]);l[r]=y.real,h[r]=y.imag};for(d=0;d<l.length;d++)y(d)}return this.complex(o.toTensor(),a.toTensor())},e.prototype.split=function(t,e,n){return To(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],c=i[2],l=i[3],h=e.shape[0],d=r[0],f=r[1],p=Xn([h,d,f,l],"float32"),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=p.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],R=v[w+2],I=v[w+3],k=m[b];if(!(k>=s))for(var S=d>1?(R-C)*(u-1)/(d-1):0,A=f>1?(I-E)*(c-1)/(f-1):0,D=0;D<d;D++){var T=d>1?C*(u-1)+D*S:.5*(C+R)*(u-1);if(T<0||T>u-1)for(var N=0;N<f;N++)for(var F=0;F<l;F++){var _=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else if("bilinear"===o){var O=Math.floor(T),M=Math.ceil(T),B=T-O;for(N=0;N<f;N++){if((q=f>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else{var P=Math.floor(q),L=Math.ceil(q),W=q-P;for(F=0;F<l;F++){var U=g[_=F+P*y[2]+O*y[1]+k*y[0]],z=g[_=F+L*y[2]+O*y[1]+k*y[0]],V=g[_=F+P*y[2]+M*y[1]+k*y[0]],G=U+(z-U)*W,H=V+(g[_=F+L*y[2]+M*y[1]+k*y[0]]-V)*W;_=F+N*x[2]+D*x[1]+b*x[0],p.values[_]=G+(H-G)*B}}}}else for(N=0;N<f;++N){var q;if((q=f>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else{var K=Math.round(q),j=Math.round(T);for(F=0;F<l;F++){var X=F+K*y[2]+j*y[1]+k*y[0],Y=F+N*x[2]+D*x[1]+b*x[0];p.values[Y]=g[X]}}}}}return p.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var o=Or(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,c=o.outputSize;return this.scatter(t,e,n,c,s,i,a,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Ar(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return fn([],a,t.dtype);for(var c=new vt([i,s],t.dtype),l=this.readSync(e.dataId),h=this.readSync(t.dataId),d=0;d<i;d++){for(var f=[],p=0,v=0;v<r;v++){var m=l[d*r+v];p+=m*u[v],f.push(m)}if(p<0||p>=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var g=0;g<s;g++)c.values[d*s+g]=h[p*s+g]}return c.toTensor().reshape(a)},e.prototype.scatterND=function(t,e,n){var r=Or(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=vn(0);return this.scatter(t,e,n,u,i,a,o,s,c,!0)},e.prototype.fill=function(t,e,n){var r=M(n=n||q(e),R(t));return r.fill(e),Bt.makeTensor(r,t,n,this)},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=M(t.dtype,R(t.shape));return this.makeOutput(e,t.shape,t.dtype)},e.prototype.linspace=function(t,e,n){return mo(t,e,n)},e.prototype.scatter=function(t,e,n,r,o,a,i,s,u,c){var l=[r/o,o],h=this.readSync(t.dataId),d=this.readSync(e.dataId);if(0===r)return fn([],n,e.dtype);var f=new vt(l,e.dtype);f.values.fill(this.readSync(u.dataId)[0]);for(var p=0;p<a;p++){for(var v=[],m=0,g=0;g<i;g++){var y=h[p*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++)c?f.values[m*o+x]+=d[p*o+x]:f.values[m*o+x]=0===e.rank?d[0]:d[p*o+x]}return f.toTensor().reshape(n)},e}($r);Bt.registerBackend("cpu",(function(){return new Eh}),1);for(var Rh=0,Ih=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,d=n;wh(a,"NonMaxSuppressionWithScore");var f=Io(d.data.get(a.dataId).values,d.data.get(i.dataId).values,u,c,l,h);return[f.selectedIndices,f.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n;wh(r,"square");for(var a=o.data.get(r.dataId).values,i=new Float32Array(a.length),s=0;s<a.length;++s){var u=a[s];i[s]=u*u}return{dataId:o.write(i,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:Fs,backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,a=r.b,i=n;wh([o,a],Fs);var s=i.data.get(o.dataId).values,u=i.data.get(a.dataId).values,c=function(t,e,n,r,o,a){var i=to(t,e),s=i.length,u=X(i),c=O(o,R(i)),l=t.length,h=e.length,d=X(t),f=X(e),p=Jr(t,i),v=Jr(e,i);if(p.length+v.length===0)for(var m=0;m<c.length;++m)c[m]=a(n[m%n.length],r[m%r.length]);else{var g=function(t){var e=ot(t,s,u),o=e.slice(-l);p.forEach((function(t){return o[t]=0}));var i=rt(o,l,d),m=e.slice(-h);v.forEach((function(t){return m[t]=0}));var g=rt(m,h,f);c[t]=a(n[i],r[g])};for(m=0;m<c.length;++m)g(m)}return[c,i]}(o.shape,a.shape,s,u,o.dtype,(function(t,e){var n=t-e;return n*n})),l=c[0],h=c[1];return{dataId:i.write(l,h,o.dtype),shape:h,dtype:o.dtype}}}];Rh<Ih.length;Rh++){f(Ih[Rh])}var kh,Sh=function(t){this.variableNames=["A"];var e=Wo(),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    "},Ah=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Wo(),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) /\n                       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    "};for(var Dh=0,Th=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e.pixels,a=r.numChannels,i="undefined"!=typeof HTMLVideoElement&&o instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&o instanceof HTMLImageElement,c=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],l=c[0],h=c[1],d=[h,l],f=[h,l,a];(u||i)&&(null==kh&&(kh=document.createElement("canvas").getContext("2d")),kh.canvas.width=l,kh.canvas.height=h,kh.drawImage(o,0,0,l,h),o=kh.canvas);var p=n.makeTensorInfo(d,"int32");n.texData.get(p.dataId).usage=Ut.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),o);var v=s().getBool("WEBGL_PACK")?new Ah(f):new Sh(f),m=n.runWebGLProgram(v,[p],"int32");return n.disposeData(p.dataId),m}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,d=n,f=Io(d.readSync(a.dataId),d.readSync(i.dataId),u,c,l,h);return[f.selectedIndices,f.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n,a=new Zi(r.shape,"return x * x;");return o.runWebGLProgram(a,[r],r.dtype)}},{kernelName:Fs,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,a=r.b,i=n,u=s().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new va("return (a - b) * (a - b);",o.shape,a.shape):new fa("return (a - b) * (a - b);",o.shape,a.shape);return i.compileAndRun(u,[o,a])}}];Dh<Th.length;Dh++){f(Th[Dh])}for(var Nh=0,Fh=[{kernelName:"Square",gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}},{kernelName:Fs,gradFunc:function(t,e){var n=e[0],r=e[1],o=vn(2);return{a:function(){return Xu(t,Xu(o,Zu(n,r)))},b:function(){return Xu(t,Xu(o,Zu(r,n)))}}}}];Nh<Fh.length;Nh++){p(Fh[Nh])}var _h=function(){function t(){}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 null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();s().get("IS_BROWSER")&&s().setPlatform("browser",new _h);var Oh,Mh=function(){return require("node-fetch")},Bh=function(){function t(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=s().global.fetch?s().global.fetch(t,e):(null==Oh&&(Oh=Mh()),Oh(t,e))},t.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},t.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)},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},t}();s().get("IS_NODE")&&s().setPlatform("node",new Bh);var Ph={float32:4,int32:4,uint16:2,uint8:1,bool:1},Lh=4;function Wh(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=R(i),u=void 0;if("quantization"in e){var c=e.quantization;if("uint8"!==c.dtype&&"uint16"!==c.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+c.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=Ph[c.dtype],h=t.slice(r,r+s*l),d="uint8"===c.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===a)u=Float32Array.from(d,(function(t){return t*c.scale+c.min}));else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(d,(function(t){return Math.round(t*c.scale+c.min)}))}r+=s*l}else if("string"===a){var f=R(e.shape);u=[];for(var p=0;p<f;p++){var v=new Uint32Array(t.slice(r,r+Lh))[0];r+=Lh;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v}}else{var g=Ph[a];h=t.slice(r,r+s*g);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*g}n[o]=fn(u,i,a)},a=0,i=e;a<i.length;a++){o(i[a])}return n}function Uh(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 zh="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Vh(t){return zh?Buffer.byteLength(t):new Blob([t]).size}function Gh(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 Hh(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function qh(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:Vh(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:Vh(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var Kh=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}(),jh="://",Xh=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){b(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(jh)&&(e=e.slice(0,e.indexOf(jh))),b(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();b(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 Yh(t){if(-1===t.indexOf(jh))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Xh.getSchemes().join(","));return{scheme:t.split(jh)[0],path:t.split(jh)[1]}}function $h(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,(function(){var r,a,i,s,u,c,l,h,d;return o(this,(function(o){switch(o.label){case 0:return b(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),b((r=Kh.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),b(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."})),a=r[0],b((i=Kh.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),b(i.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."})),s=i[0],u=Yh(t).scheme,c=Yh(t).path,l=u===Yh(t).scheme,[4,a.load()];case 1:return h=o.sent(),n&&l?[4,Xh.getManager(u).removeModel(c)]:[3,3];case 2:o.sent(),o.label=3;case 3:return[4,s.save(h)];case 4:return d=o.sent(),!n||l?[3,6]:[4,Xh.getManager(u).removeModel(c)];case 5:o.sent(),o.label=6;case 6:return[2,d.modelArtifactsInfo]}}))}))}var Qh="models_store",Jh="model_info_store";function Zh(){if(!s().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function td(t){var e=t.result;e.createObjectStore(Qh,{keyPath:"modelPath"}),e.createObjectStore(Jh,{keyPath:"modelPath"})}var ed=function(){function t(t){if(this.indexedDB=Zh(),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 td(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(Qh,"readonly"),s=i.objectStore(Qh).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,c=qh(e),l=a.transaction(Jh,"readwrite"),h=l.objectStore(Jh),d=h.put({modelPath:n.modelPath,modelArtifactsInfo:c});d.onsuccess=function(){var o=(u=a.transaction(Qh,"readwrite")).objectStore(Qh).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(h=l.objectStore(Jh)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},d.onerror=function(t){return a.close(),r(d.error)},l.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}(),nd=function(t){return s().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(ed.URL_SCHEME)?(e=t.slice(ed.URL_SCHEME.length),new ed(e)):null;var e};Kh.registerSaveRouter(nd),Kh.registerLoadRouter(nd);var rd=function(){function t(){this.indexedDB=Zh()}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 td(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(Jh,"readonly"),a=o.objectStore(Jh).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(ed.URL_SCHEME)?r.slice(ed.URL_SCHEME.length):r,[2,new Promise((function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return td(o)},o.onsuccess=function(){var e,a=o.result,i=a.transaction(Jh,"readwrite"),s=i.objectStore(Jh),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(Qh,"readwrite")).objectStore(Qh).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(s().getBool("IS_BROWSER"))try{Xh.registerManager(ed.URL_SCHEME,new rd)}catch(t){}var od="/",ad="tensorflowjs_models",id="info",sd="model_topology",ud="weight_specs",cd="weight_data",ld="model_metadata";function hd(t){return{info:[ad,t,id].join(od),topology:[ad,t,sd].join(od),weightSpecs:[ad,t,ud].join(od),weightData:[ad,t,cd].join(od),modelMetadata:[ad,t,ld].join(od)}}function dd(t){var e=t.split(od);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(od)}var fd=function(){function t(t){if(!s().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=hd(this.modelPath)}return t.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=qh(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,function(t){if(zh)return Buffer.from(t).toString("base64");for(var e=new Uint8Array(t),n="",r=0,o=e.length;r<o;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[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+".")}return[2]}))}))},t.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,e.userDefinedMetadata=i.userDefinedMetadata),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(zh){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]}))}))},t.URL_SCHEME="localstorage://",t}(),pd=function(t){return s().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(fd.URL_SCHEME)?(e=t.slice(fd.URL_SCHEME.length),new fd(e)):null;var e};Kh.registerSaveRouter(pd),Kh.registerLoadRouter(pd);var vd=function(){function t(){b(s().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),b("undefined"==typeof window||void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return t.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=ad+od,n=od+id,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(i=dd(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]}))}))},t.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(fd.URL_SCHEME)?o.slice(fd.URL_SCHEME.length):o,e=hd(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]}))}))},t}();if(s().getBool("IS_BROWSER"))try{Xh.registerManager(fd.URL_SCHEME,new vd)}catch(t){}var md="model",gd=".json",yd=".weights.bin";function xd(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var bd=function(){function t(e){if(!s().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e=md),this.modelTopologyFileName=e+gd,this.weightDataFileName=e+yd}return t.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,xd((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,xd((function(){return s.dispatchEvent(new MouseEvent("click"))}))]);case 3:o.sent(),o.label=4;case 4:return[2,{modelArtifactsInfo:qh(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),wd=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 c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var l=[],h=[],d=[];u.forEach((function(t){t.paths.forEach((function(t){h.push(t),d.push(null)})),l.push.apply(l,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);d[o]=n,-1===d.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:Gh(d),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy,userDefinedMetadata:i.userDefinedMetadata})},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(c[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 Hh(t.name)})),o={},a=0,i=t;a<i.length;a++){i[a].paths.forEach((function(t){var a=Hh(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 Cd(t,e,n,r){!function(t){b(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){b(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),b(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),b(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 Ed(t,e){return r(this,void 0,void 0,(function(){var n,r,a,i,u,c,l,h,d;return o(this,(function(o){switch(o.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?s().platform.fetch:e.fetchFunc,r=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return u=o.sent(),[3,4];case 2:return[4,Cd(r,e.onProgress,a,i)];case 3:u=o.sent(),o.label=4;case 4:return c=u.map((function(t){return t.arrayBuffer()})),l=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(c)];case 5:return d=o.sent(),[3,8];case 6:return[4,Cd(c,e.onProgress,l,h)];case 7:d=o.sent(),o.label=8;case 8:return[2,d]}}))}))}function Rd(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,c,l,h,d,f,p;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,c=Ph[a]*R(t.shape),l=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:o,sizeBytes:c})};null!=i?i.forEach((function(e,n){e===t.name&&(l(),s[n]=!0)})):l(),u.push(t.name),o+=c}))})),!s.every((function(t){return t})))throw c=i.filter((function(t,e){return!s[e]})),new Error("Could not find weights in manifest with names: "+c.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return l=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),h=[],l.forEach((function(t){n[t].paths.forEach((function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e)}))})),[4,t(h)];case 1:return d=o.sent(),f={},p=0,l.forEach((function(t){for(var e=n[t].paths.length,o=0,a=0;a<e;a++)o+=d[p+a].byteLength;for(var i=new ArrayBuffer(o),s=new Uint8Array(i),u=0,c=0;c<e;c++){var l=new Uint8Array(d[p+c]);s.set(l,u),u+=l.byteLength}r[t].forEach((function(t){var e=Wh(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)f[n]=e[n]})),p+=e})),[2,f]}}))}))}}Kh.registerSaveRouter((function(t){return s().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(bd.URL_SCHEME)?function(t){void 0===t&&(t="model");return new bd(t)}(t.slice(bd.URL_SCHEME.length)):null}));var Id=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(b("function"==typeof e.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=e.fetchFunc):this.fetch=s().platform.fetch,b(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&b(2===t.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."})),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return 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,userDefinedMetadata:t.userDefinedMetadata,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:qh(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return r(this,void 0,void 0,(function(){var t,e,n,r,a,i,s,u,c,l,h,d;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,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,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:d=o.sent(),l=d[0],h=d[1],o.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:h,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}}))}))},t.prototype.loadWeights=function(t){return r(this,void 0,void 0,(function(){var e,n,r,a,i,s,u,c,l,h,d;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,c=t;u<c.length;u++)l=c[u],s.push.apply(s,l.weights);return h=[],t.forEach((function(t){t.paths.forEach((function(t){h.push(i+t+a)}))})),[4,Ed(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return d=o.sent(),[2,[s,Gh(d)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function kd(t){return null!=t.match(Id.URL_SCHEME_REGEX)}var Sd=function(t,e){if("undefined"==typeof fetch)return null;return(Array.isArray(t)?t.every((function(t){return kd(t)})):kd(t))?Ad(t,{onProgress:e}):null};function Ad(t,e){return new Id(t,e)}Kh.registerSaveRouter(Sd),Kh.registerLoadRouter(Sd);var Dd=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}(),Td=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 Nd=Object.freeze({browserFiles:function(t){return new wd(t)},browserHTTPRequest:function(t,e){return Ad(t,e)},concatenateArrayBuffers:Gh,decodeWeights:Wh,encodeWeights:function(t,e){return r(this,void 0,void 0,(function(){var n,a,i,s,u,c=this;return o(this,(function(l){switch(l.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],l=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+l.dtype);var h={name:u,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var d=new Promise((function(t){return r(c,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,l.bytes()];case 1:for(e=o.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+Lh*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+=Lh,r.set(s,a),a+=s.length;return t(r),[2]}}))}))}));a.push(d)}else a.push(l.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:Uh(l.sent()),specs:n}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Dd(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 Dd({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 Dd({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return Kh.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:qh,getSaveHandlers:function(t){return Kh.getSaveHandlers(t)},http:Ad,isHTTPScheme:kd,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,Rd((function(t){return Ed(t,{requestInit:a})}))(t,e,n)]}))}))},registerLoadRouter:function(t){return Kh.registerLoadRouter(t)},registerSaveRouter:function(t){return Kh.registerSaveRouter(t)},weightsLoaderFactory:Rd,withSaveHandler:function(t){return new Td(t)},copyModel:function(t,e){return r(this,void 0,void 0,(function(){return o(this,(function(n){return!1,[2,$h(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=Xh.getSchemes(),e={},n=0,r=t,o.label=1;case 1:return n<r.length?(a=r[n],[4,Xh.getManager(a).listModels()]):[3,4];case 2:for(s in i=o.sent())e[a+jh+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!0,[2,$h(t,e,!0)]}))}))},removeModel:function(t){return r(this,void 0,void 0,(function(){var e;return o(this,(function(n){return e=Yh(t),[2,Xh.getManager(e.scheme).removeModel(e.path)]}))}))}});var Fd,_d=cn({confusionMatrix_:function(t,e,n){var r=$e(t,"labels","confusionMatrix"),o=$e(e,"predictions","confusionMatrix");b(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),b(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),b(1===o.rank,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),b(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."})),b(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var a=ar(r.asType("int32"),n),i=ar(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),Od=Object.freeze({confusionMatrix:_d});var Md=cn({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.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,o=!1,a=!1,i=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)o=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)a=!0;else{if(null==t.getContext)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 "+t.constructor.name);i=!0}if(o){if(o&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(null!=l("FromPixels",Bt.backendName))return Bt.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,c=o?[t.videoWidth,t.videoHeight]:[t.width,t.height],h=c[0],d=c[1];if(i?s=t.getContext("2d").getImageData(0,0,h,d).data:r||n?s=t.data:(a||o)&&(null==Fd&&(Fd=document.createElement("canvas").getContext("2d")),Fd.canvas.width=h,Fd.canvas.height=d,Fd.drawImage(t,0,0,h,d),s=Fd.getImageData(0,0,h,d).data),4===e)u=new Int32Array(s);else{var f=h*d;u=new Int32Array(f*e);for(var p=0;p<f;p++)for(var v=0;v<e;++v)u[p*e+v]=s[4*p+v]}return yn(u,[d,h,e],"int32")}}),Bd=Object.freeze({toPixels:function(t,e){return r(this,void 0,void 0,(function(){var n,r,a,i,s,u,c,l,h,d,f,p,v,m,g,y,x,b,w,C,E,R,I;return o(this,(function(o){switch(o.label){case 0:if(n=$e(t,"img","toPixels"),t instanceof xt||(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(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(h=o.sent(),d=h[0],f=h[1],p=d[0],v=f[0],c.dispose(),l.dispose(),"float32"===n.dtype){if(p<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+p+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(p<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+p+" - "+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[(E=4*y)+0]=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,R=e.getContext("2d"),I=new ImageData(g,i,a),R.putImageData(I,0,0)),n!==t&&n.dispose(),[2,g]}}))}))},fromPixels:Md}),Pd=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Ld=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 Wd(t){b(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),b("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),b(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),Ld.register(t)}var Ud=Object.freeze({Serializable:Pd,SerializationMap:Ld,registerClass:Wd}),zd=.001,Vd=.1;function Gd(){return 32===Bt.backend.floatPrecision()?zd:Vd}function Hd(t,e,n){var r=!0;if((W(t)||W(e))&&(r=!1),W(t)&&W(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=Xe(t),s=Xe(e);if(!I(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=W(t)?t:E(t),c=W(e)?e:E(e);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+".\nActual:   "+u+".\nExpected: "+c+".");for(var l=0;l<c.length;++l){var h=u[l],d=c[l];if(!n(h,d))throw new Error("Arrays differ: actual["+l+"] = "+h+", expected["+l+"] = "+d+".\nActual:   "+u+".\nExpected: "+c+".")}}function qd(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var Kd=Object.freeze({TEST_EPSILON_FLOAT16:Vd,expectArraysClose:function(t,e,n){return null==n&&(n=Gd()),Hd(t,e,(function(t,e){return qd(t,e,n)}))},testEpsilon:Gd,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 V(t)||V(t[0])||V(e)||V(e[0])?Hd(t,n,(function(t,e){return t==e})):Hd(t,e,(function(t,e){return qd(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=Gd()),!qd(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 jd=Object.freeze({gpgpu_util:di,webgl_util:ze,forceHalfFloat:function(){s().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Ts,setWebGLContext:Ht,GPGPUContext:fi}),Xd=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 qe(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 Hr(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&qe(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:vn(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}(Pd);Object.defineProperty(Xd,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Yd=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=Bt.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=Bt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:He((function(){return Dn(o).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:He((function(){return Dn(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;He((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&&(qe(this.accumulatedGrads.map((function(t){return t.variable}))),qe(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}(Xd);Wd(Yd);var $d=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=Bt.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:He((function(){return In(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;He((function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(Bt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&qe(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}(Xd);Wd($d);var Qd=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=[],He((function(){a.accBeta1=vn(n).variable(),a.accBeta2=vn(r).variable()})),null==o&&(a.epsilon=Bt.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);He((function(){var r=Zu(1,e.accBeta1),o=Zu(1,e.accBeta2);n.forEach((function(n,a){var i=Bt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:He((function(){return Dn(i).variable(!1)}))}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:He((function(){return Dn(i).variable(!1)}))});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedSecondMoment[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),d=l.div(r),f=h.div(o);u.assign(l),c.assign(h);var p=d.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(p)}})),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&&qe(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&qe(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(),He((function(){n.accBeta1.assign($u(n.beta1,n.iterations_+1)),n.accBeta2.assign($u(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}(Xd);Wd(Qd);var Jd=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=[],He((function(){i.iteration=vn(0).variable(),i.accBeta1=vn(n).variable()})),null==o&&(i.epsilon=Bt.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);He((function(){var r=Zu(1,e.accBeta1),o=Lu(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,a){var i=Bt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Dn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:Dn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedWeightedInfNorm[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2),d=s.abs(),f=h.maximum(d);u.assign(l),c.assign(f);var p=o.div(r).mul(l.div(f.add(e.epsilon))).add(i);i.assign(p)}})),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&&qe(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&qe(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}(Xd);Wd(Jd);var Zd=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=Bt.registeredVariables[n];He((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=Ke(vn(-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}(Xd);Wd(Zd);var tf=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=vn(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=Bt.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:He((function(){return Dn(o).variable(!1)}))}}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&He((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&&qe(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}(Zd);Wd(tf);var ef=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;if(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=Bt.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.");return 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=Bt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:He((function(){return Dn(o).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:He((function(){return Dn(o).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:He((function(){return Dn(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;He((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)),c=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(c);var l=o.sub(c);o.assign(l)}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));c=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(c);l=o.sub(c);o.assign(l)}}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&qe(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&qe(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&qe(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}(Xd);Wd(ef);var nf=function(){function t(){}return t.sgd=function(t){return new Zd(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new tf(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 ef(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 Qd(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 Yd(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 Jd(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new $d(t,e)},t}(),rf={sgd:nf.sgd,momentum:nf.momentum,adadelta:nf.adadelta,adagrad:nf.adagrad,rmsprop:nf.rmsprop,adamax:nf.adamax,adam:nf.adam},of="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};xt.prototype.squaredDifference=function(t){return _s(this,t)},gt=bh,t.AdadeltaOptimizer=Yd,t.AdagradOptimizer=$d,t.AdamOptimizer=Qd,t.AdamaxOptimizer=Jd,t.DataStorage=Yr,t.Environment=a,t.KernelBackend=$r,t.MomentumOptimizer=tf,t.Optimizer=Xd,t.RMSPropOptimizer=ef,t.SGDOptimizer=Zd,t.Tensor=xt,t.TensorBuffer=vt,t.Variable=It,t.abs=Os,t.acos=Ms,t.acosh=Bs,t.add=Ou,t.addN=Mu,t.addStrict=Bu,t.all=Zc,t.any=tl,t.argMax=el,t.argMin=nl,t.asin=Ps,t.asinh=Ls,t.atan=Ws,t.atan2=Pu,t.atanh=Us,t.avgPool=Gc,t.avgPool3d=Kc,t.backend=function(){return Bt.backend},t.backend_util=go,t.basicLSTMCell=xl,t.batchNorm=Ru,t.batchNorm2d=Iu,t.batchNorm3d=ku,t.batchNorm4d=Su,t.batchNormalization=Eu,t.batchNormalization2d=bu,t.batchNormalization3d=wu,t.batchNormalization4d=Cu,t.batchToSpaceND=$n,t.booleanMaskAsync=gc,t.broadcastTo=Qn,t.browser=Bd,t.buffer=Xn,t.cast=Jn,t.ceil=zs,t.clipByValue=Vs,t.clone=Zn,t.complex=ln,t.concat=Tn,t.concat1d=Nn,t.concat2d=Fn,t.concat3d=_n,t.concat4d=On,t.conv1d=wc,t.conv2d=Cc,t.conv2dTranspose=Tc,t.conv3d=Ec,t.conv3dTranspose=Nc,t.cos=Gs,t.cosh=Hs,t.cumsum=tr,t.customGrad=qr,t.deprecationWarn=Ge,t.depthToSpace=er,t.depthwiseConv2d=kc,t.diag=Fl,t.disableDeprecationWarnings=function(){s().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},t.dispose=qe,t.disposeVariables=function(){Bt.disposeVariables()},t.div=Lu,t.divNoNan=Wu,t.divStrict=Uu,t.dot=_c,t.dropout=_l,t.elu=ll,t.enableDebugMode=function(){s().set("DEBUG",!0)},t.enableProdMode=function(){s().set("PROD",!0)},t.engine=function(){return Bt},t.env=s,t.equal=ec,t.equalStrict=nc,t.erf=qs,t.exp=Ks,t.expandDims=nr,t.expm1=js,t.eye=rr,t.fft=Il,t.fill=In,t.findBackend=function(t){return Bt.findBackend(t)},t.findBackendFactory=function(t){return Bt.findBackendFactory(t)},t.floor=Xs,t.floorDiv=zu,t.frame=Pl,t.fused=xh,t.gather=vc,t.gatherND=Nl,t.gather_util=Dr,t.getBackend=function(){return Bt.backendName},t.getGradient=h,t.getKernel=l,t.getKernelsForBackend=d,t.grad=function(t){return b(K(t),(function(){return"The f passed in grad(f) must be a function"})),function(e,n){var r=$e(e,"x","tf.grad",null),o=null!=n?$e(n,"dy","tf.grad"):null;return Bt.tidy((function(){var e=Bt.gradients((function(){return t(r)}),[r],o),n=e.value,a=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Kr(a),a[0]}))}},t.grads=function(t){return b(K(t),(function(){return"The f passed in grads(f) must be a function"})),function(e,n){b(Array.isArray(e),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=Qe(e,"args","tf.grads",null),o=null!=n?$e(n,"dy","tf.grads"):null;return Bt.tidy((function(){var e=Bt.gradients((function(){return t.apply(void 0,r)}),r,o),n=e.value,a=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Kr(a),a}))}},t.greater=rc,t.greaterEqual=oc,t.greaterEqualStrict=ac,t.greaterStrict=ic,t.hammingWindow=Bl,t.hannWindow=Ml,t.ifft=kl,t.imag=dn,t.image=hh,t.inTopKAsync=zl,t.io=Nd,t.irfft=Al,t.isFinite=iu,t.isInf=au,t.isNaN=ou,t.keep=Ke,t.leakyRelu=hl,t.less=sc,t.lessEqual=uc,t.lessEqualStrict=cc,t.lessStrict=lc,t.linalg=nh,t.linspace=kn,t.localResponseNormalization=gl,t.log=Ys,t.log1p=$s,t.logSigmoid=Qs,t.logSoftmax=Xr,t.logSumExp=rl,t.logicalAnd=Au,t.logicalNot=Du,t.logicalOr=Tu,t.logicalXor=Nu,t.losses=Ql,t.matMul=Fc,t.math=Od,t.max=ol,t.maxPool=Vc,t.maxPool3d=qc,t.maximum=Vu,t.maximumStrict=Gu,t.mean=al,t.memory=function(){return Bt.memory()},t.min=il,t.minimum=Hu,t.minimumStrict=qu,t.mod=Ku,t.modStrict=ju,t.moments=sl,t.movingAverage=wl,t.mul=Xu,t.mulStrict=Yu,t.multiRNNCell=bl,t.multinomial=or,t.neg=Js,t.nextFrame=function(){return new Promise((function(t){return of((function(){return t()}))}))},t.norm=yl,t.notEqual=hc,t.notEqualStrict=dc,t.oneHot=ar,t.ones=En,t.onesLike=An,t.op=cn,t.outerProduct=Oc,t.pad=ir,t.pad1d=sr,t.pad2d=ur,t.pad3d=cr,t.pad4d=lr,t.pool=Hc,t.pow=$u,t.powStrict=Qu,t.prelu=dl,t.print=Yn,t.prod=cl,t.profile=function(t){return Bt.profile(t)},t.rand=hr,t.randomGamma=fr,t.randomNormal=dr,t.randomUniform=pr,t.range=Sn,t.ready=function(){return Bt.ready()},t.real=hn,t.reciprocal=Zs,t.registerBackend=function(t,e,n){return void 0===n&&(n=1),Bt.registerBackend(t,e,n)},t.registerGradient=p,t.registerKernel=f,t.relu=fl,t.relu6=pl,t.removeBackend=function(t){Bt.removeBackend(t)},t.reshape=vr,t.reverse=Mc,t.reverse1d=Bc,t.reverse2d=Pc,t.reverse3d=Lc,t.reverse4d=Wc,t.rfft=Sl,t.round=tu,t.rsqrt=eu,t.scalar=vn,t.scatterND=Rl,t.scatter_util=Mr,t.selu=vl,t.separableConv2d=Dc,t.serialization=Ud,t.setBackend=function(t){return Bt.setBackend(t)},t.setPlatform=function(t,e){s().setPlatform(t,e)},t.setdiff1dAsync=Cr,t.sigmoid=nu,t.sign=ru,t.signal=Wl,t.sin=su,t.sinh=uu,t.slice=jc,t.slice1d=Xc,t.slice2d=Yc,t.slice3d=$c,t.slice4d=Qc,t.slice_util=Gr,t.softmax=jr,t.softplus=cu,t.spaceToBatchND=mr,t.sparseToDense=Tl,t.spectral=Dl,t.split=Mn,t.sqrt=lu,t.square=Ns,t.squaredDifference=_s,t.squaredDifferenceStrict=Ju,t.squeeze=gr,t.stack=yr,t.step=hu,t.stft=Ll,t.stridedSlice=Cl,t.sub=Zu,t.subStrict=tc,t.sum=ul,t.sumOutType=At,t.tan=du,t.tanh=fu,t.tensor=fn,t.tensor1d=mn,t.tensor2d=gn,t.tensor3d=yn,t.tensor4d=xn,t.tensor5d=bn,t.tensor6d=wn,t.tensor_util=_t,t.test_util=Kd,t.tidy=He,t.tile=xr,t.time=function(t){return Bt.time(t)},t.topk=El,t.train=rf,t.transpose=ml,t.truncatedNormal=br,t.unregisterGradient=function(t){if(!c.has(t))throw new Error("The gradient '"+t+"' for backend is not registered");c.delete(t)},t.unregisterKernel=function(t,e){var n=v(t,e);if(!u.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");u.delete(n)},t.unsortedSegmentSum=mc,t.unstack=wr,t.util=at,t.valueAndGrad=function(t){return b(K(t),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(e,n){b(e instanceof xt,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),b(null==n||n instanceof xt,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=Bt.gradients((function(){return t(e)}),[e],n),o=r.grads,a=r.value;return Kr(o),{grad:o[0],value:a}}},t.valueAndGrads=function(t){return b(K(t),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(e,n){b(Array.isArray(e)&&e.every((function(t){return t instanceof xt})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),b(null==n||n instanceof xt,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=Bt.gradients((function(){return t.apply(void 0,e)}),e,n);return null!=n&&w(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Kr(r.grads),r}},t.variable=Cn,t.variableGrads=Hr,t.version_core="1.7.0",t.webgl=jd,t.where=Fu,t.whereAsync=_u,t.zeros=Rn,t.zerosLike=Dn,Object.defineProperty(t,"__esModule",{value:!0})}));
//# sourceMappingURL=tf-core.min.js.map
