You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1 line
643 KiB
1 line
643 KiB
"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[23872],{75742:function(t,e,n){n.d(e,{Z:function(){return u}});var r=n(82871),o=n(59301),i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"}}]},name:"check",theme:"outlined"},a=n(68475),s=function(t,e){return o.createElement(a.Z,(0,r.Z)({},t,{ref:e,icon:i}))};var u=o.forwardRef(s)},89136:function(t,e,n){n.d(e,{Z:function(){return u}});var r=n(82871),o=n(59301),i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M942.2 486.2C847.4 286.5 704.1 186 512 186c-192.2 0-335.4 100.5-430.2 300.3a60.3 60.3 0 000 51.5C176.6 737.5 319.9 838 512 838c192.2 0 335.4-100.5 430.2-300.3 7.7-16.2 7.7-35 0-51.5zM512 766c-161.3 0-279.4-81.8-362.7-254C232.6 339.8 350.7 258 512 258c161.3 0 279.4 81.8 362.7 254C791.5 684.2 673.4 766 512 766zm-4-430c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm0 288c-61.9 0-112-50.1-112-112s50.1-112 112-112 112 50.1 112 112-50.1 112-112 112z"}}]},name:"eye",theme:"outlined"},a=n(68475),s=function(t,e){return o.createElement(a.Z,(0,r.Z)({},t,{ref:e,icon:i}))};var u=o.forwardRef(s)},56762:function(t,e,n){n.d(e,{Z:function(){return o}});var r=n(59301);function o(){const[,t]=r.useReducer((t=>t+1),0);return t}},8628:function(t,e,n){var r=n(59301),o=n(36241),i=n(56762),a=n(69507);e.Z=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];const e=(0,r.useRef)({}),n=(0,i.Z)(),s=(0,a.ZP)();return(0,o.Z)((()=>{const r=s.subscribe((r=>{e.current=r,t&&n()}));return()=>s.unsubscribe(r)}),[]),e.current}},8378:function(t,e){e.Z=t=>({[t.componentCls]:{[`${t.antCls}-motion-collapse-legacy`]:{overflow:"hidden","&-active":{transition:`height ${t.motionDurationMid} ${t.motionEaseInOut},\n opacity ${t.motionDurationMid} ${t.motionEaseInOut} !important`}},[`${t.antCls}-motion-collapse`]:{overflow:"hidden",transition:`height ${t.motionDurationMid} ${t.motionEaseInOut},\n opacity ${t.motionDurationMid} ${t.motionEaseInOut} !important`}}})},2668:function(t,e,n){n.d(e,{zi:function(){return Hv},aK:function(){return Zd},bd:function(){return Gv},ii:function(){return r},yW:function(){return bp},W6:function(){return wv},Qk:function(){return Cv},z2:function(){return bv},qB:function(){return xv},_C:function(){return qv}});var r={};n.r(r),n.d(r,{AnchorPosition:function(){return lp},DrawBox:function(){return gp},DrawBoxOptions:function(){return mp},DrawFaceLandmarks:function(){return sd},DrawFaceLandmarksOptions:function(){return ad},DrawTextField:function(){return vp},DrawTextFieldOptions:function(){return dp},drawContour:function(){return xf},drawDetections:function(){return yp},drawFaceExpressions:function(){return rd},drawFaceLandmarks:function(){return ud}});var o=n(97671),i=n(19208).lW,a=function(t,e){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function s(t,e){function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function u(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?o(t.value):new n((function(e){e(t.value)})).then(a,s)}u((r=r.apply(t,e||[])).next())}))}function c(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=e.call(t,a)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}var l=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.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 h(n,e[0],e[1]),e.join("=")})),n);"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 h(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function f(){return p}var p=null,d=new Map,v=new Map;function m(t,e){var n=b(t,e);return d.get(n)}function g(t){for(var e=d.entries(),n=[];;){var r=e.next(),o=r.done,i=r.value;if(o)break;var a=i[0],s=i[1];a.split("_")[0]===t&&n.push(s)}return n}function y(t){var e=t.kernelName,n=t.backendName,r=b(e,n);if(d.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");d.set(r,t)}function x(t){var e=t.kernelName;v.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),v.set(e,t)}function b(t,e){return e+"_"+t}function w(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function C(t,e,n){return Math.max(t,Math.min(e,n))}function E(t){return t%2==0?t:t+1}function _(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function I(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function R(t,e,n){void 0===n&&(n=""),I(A(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function S(t){I(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function k(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||H(t)&&!n)for(var r=0;r<t.length;++r)k(t[r],e,n);else e.push(t);return e}function D(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function A(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 T(t){return t%1==0}function N(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 F(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function M(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function O(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise((function(r,o){var i=0,a=function(){if(t())r();else{i++;var s=e(i);null!=n&&i>=n?o():setTimeout(a,s)}};a()}))}function P(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 i=t.slice();return i[r]=e/n,i}function B(t,e){var n=e.length;return I((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})),I(t.every((function(t){return T(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 L(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,i=null==e||o?null:B(e,t).sort(),a=0,s=0;s<t.length;++s){if(null!=i){if(i[a]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==i[a]||i[a]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),i[a]<=s&&a++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function W(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 z(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 U(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 V(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function G(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function H(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function q(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 j(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function K(t){return"string"==typeof t||t instanceof String}function X(t){return"boolean"==typeof t}function Y(t){return"number"==typeof t}function $(t){return Array.isArray(t)?$(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":Y(t)?"float32":K(t)?"string":X(t)?"bool":"float32"}function J(t){return!!(t&&t.constructor&&t.call&&t.apply)}function Q(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function Z(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 tt(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=k(t)),n&&U(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)}function et(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 i=n[0],a=0;a<i;a++)o[a]=r[e+a];else{i=n[0];var s=n.slice(1),u=s.reduce((function(t,e){return t*e}));for(a=0;a<i;a++)o[a]=t(e+a*u,s,r)}return o}(0,t,e)}function nt(t,e){for(var n=rt(t,e),r=0;r<n.length;r++)n[r]=1;return n}function rt(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 ot(){return f().platform.now()}function it(t){t.forEach((function(e){I(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function at(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",f().platform.encode(t,e)}function st(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",f().platform.decode(t,e)}function ut(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 ct(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}Object.freeze({shuffle:w,clamp:C,nearestLargerEven:E,sum:_,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:I,assertShapesMatch:R,assertNonNull:S,flatten:k,sizeFromShape:D,isScalarShape:function(t){return 0===t.length},arraysEqual:A,isInt:T,tanh:N,sizeToSquarishShape:F,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return w(e),e},rightPad:M,repeatedTry:O,inferFromImplicitShape:P,parseAxisParam:B,squeezeShape:L,getTypedArrayFromDType:W,getArrayFromDType:z,checkConversionForErrors:U,isValidDtype:V,hasEncodingLoss:G,isTypedArray:H,bytesPerElement:q,bytesFromStringArray:j,isString:K,isBoolean:X,isNumber:Y,inferDtype:$,isFunction:J,nearestDivisor:Q,computeStrides:Z,toTypedArray:tt,toNestedArray:et,makeOnesTypedArray:nt,makeZerosTypedArray:rt,now:ot,assertNonNegativeIntegerDimensions:it,fetch:function(t,e){return f().platform.fetch(t,e)},encodeString:at,decodeString:st,locToIndex:ut,indexToLoc:ct});var lt=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new ht)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,i=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),i.then((function(i){var a="";null!=i.getExtraProfileInfo&&(a=i.getExtraProfileInfo()),o.logger.logKernelProfile(t,n,r,i.kernelMs,e,a)}))}))})),r},t}(),ht=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,i){var a="number"==typeof r?M(r+"ms",9):r.error,s=M(t,25),u=e.rank,c=e.size,l=M(e.shape.toString(),14),h="";for(var f in o){var p=o[f].shape||e.shape,d=p.length;h+=f+": "+d+"D "+(d>0?p:"")+" "}console.log("%c"+s+"\t%c"+a+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+h+"\t%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();function ft(t,e,n){return M(Array.isArray(t)?parseFloat(t[0].toFixed(7))+" + "+parseFloat(t[1].toFixed(7))+"j":K(t)?"'"+t+"'":"bool"===n?pt(t):parseFloat(t.toFixed(7)).toString(),e)}function pt(t){return 0===t?"false":"true"}function dt(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=D(t),null!=n){var o=n.length;I(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||z(e,this.size),this.strides=Z(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]),I(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 i=o[r];if(i<0||i>=this.shape[n]){var a="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(a)}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,xt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=D(t),this.strides=Z(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(),I(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 u(this,void 0,void 0,(function(){var t;return c(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 u(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,et(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return et(this.shape,this.dataSync())},t.prototype.data=function(){return u(this,void 0,void 0,(function(){var t,e;return c(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 st(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 st(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 u(this,void 0,void 0,(function(){var t;return c(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),function(t,e,n,r){var o=Z(e),i=function(t,e,n,r){var o=D(e),i=r[r.length-1],a=new Array(i).fill(0),s=e.length,u="complex64"===n?dt(t):t;if(s>1)for(var c=0;c<o/i;c++)for(var l=c*i,h=0;h<i;h++)a[h]=Math.max(a[h],ft(u[l+h],0,n).length);return a}(t,e,n,o),a=e.length,s=function t(e,n,r,o,i,a){void 0===a&&(a=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c)return"complex64"===r?[ft(dt(e)[0],0,r)]:"bool"===r?[pt(e[0])]:[e[0].toString()];if(1===c){if(u>20){var l=3*s,h=Array.from(e.slice(0,l)),f=Array.from(e.slice((u-3)*s,u*s));return"complex64"===r&&(h=dt(h),f=dt(f)),["["+h.map((function(t,e){return ft(t,i[e],r)})).join(", ")+", ..., "+f.map((function(t,e){return ft(t,i[u-3+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?dt(e):Array.from(e)).map((function(t,e){return ft(t,i[e],r)})).join(", ")+"]"]}var p=n.slice(1),d=o.slice(1),v=o[0]*s,m=[];if(u>20){for(var g=0;g<3;g++){var y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),p,r,d,i,!1))}for(m.push("..."),g=u-3;g<u;g++)y=(x=g*v)+v,m.push.apply(m,t(e.slice(x,y),p,r,d,i,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),p,r,d,i,g===u-1))}var b=2===c?",":"";for(m[0]="["+m[0]+b,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]+"]"+(a?"":w),m}(t,e,n,o,i),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+a),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map((function(t){return" "+t})).join("\n")),u.join("\n")}(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,i){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),gt.conv1d(this,t,e,n,r,o,i)},t.prototype.conv2d=function(t,e,n,r,o,i){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),gt.conv2d(this,t,e,n,r,o,i)},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,i){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),gt.depthwiseConv2d(this,t,e,n,r,o,i)},t.prototype.separableConv2d=function(t,e,n,r,o,i){return void 0===o&&(o=[1,1]),void 0===i&&(i="NHWC"),this.throwIfDisposed(),gt.separableConv2d(this,t,e,n,r,o,i)},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,i,a,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===a&&(a=0),void 0===s&&(s=0),this.throwIfDisposed(),gt.stridedSlice(this,t,e,n,r,o,i,a,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,_t,It=function(t){function e(e,n,r,o){var i=t.call(this,e.shape,e.dtype,e.dataId,o)||this;return i.trainable=n,i.name=r,i}return s(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(!A(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}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(bt||(bt={})),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"}(_t||(_t={}));var Rt={float32:Et,int32:wt,bool:Ct,complex64:_t};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 Rt[t][e]}function kt(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 At(t,e){I(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function Tt(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof xt)n.push(e);else if(o=e,Array.isArray(o)||"object"==typeof o){var o,i=e;for(var a in i){var s=i[a];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}Object.freeze({makeTypesMatch:Dt,assertTypesMatch:At,isTensorInList:function(t,e){return e.some((function(e){return e.id===t.id}))},getTensorsInContainer:Tt});var Nt,Ft=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 Ft}return t.prototype.ready=function(){return u(this,void 0,void 0,(function(){var t,e,n;return c(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 u(this,void 0,void 0,(function(){var e,n,r;return c(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 lt(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;g(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;g(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,i=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=i,{success:i,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,i=r.asyncInit;if(i||o)return{name:n,asyncInit:i}}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 i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-e-o-i;if(a>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+a+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,o,i,a){var s,u=this;void 0===i&&(i=[]),void 0===a&&(a=[]);var c=[],l=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var h,f=function(t){l&&(c=t.map((function(t){return u.keep(u.clone(t))})))},p=this.state.numBytes,d=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var v,g=m(r,this.backendName);return h=null!=g?function(){var t=u.backend.numDataIds();v=g.kernelFunc({inputs:e,attrs:o,backend:u.backend});var n=Array.isArray(v)?v:[v];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 a[e]}));return f((i||[]).slice().concat(c)),s}:function(){var e=u.backend.numDataIds();v=u.tidy((function(){return t(u.backend,f)}));var n=Array.isArray(v)?v:[v];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 h()})):h()})),l&&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-d,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(v)?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&&K(t[0])&&(o=t.map((function(t){return at(t)})));var i=r.write(o,e,n),a=new xt(e,n,i,this.nextTensorId());if(this.incRef(a,r),"string"===n){var s=this.state.tensorInfo.get(i),u=j(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return a},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*q(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 u(this,void 0,void 0,(function(){var e,n;return c(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 i=this,a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:o},s=function(t){return v.get(t)}(t);null!=s&&(r=s.gradFunc),null!=r&&(a.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],o=rt(r.size,r.dtype);return i.makeTensor(o,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],o)}),this.state.activeTape.push(a)},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=Tt(t),r=new Set(n.map((function(t){return t.id}))),o=0;o<this.state.activeScope.track.length;o++){var i=this.state.activeScope.track[o];i.kept||r.has(i.id)||i.dispose()}var a=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!==a.id||e.track(t)}))},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),I(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 i=this.scopedRun((function(){return o.startTape()}),(function(){return o.endTape()}),(function(){return o.tidy("forward",t)}));I(i instanceof xt,(function(){return"The result y returned by f() must be a tensor."}));var a=function(t,e,n){for(var r={},o={},i=0;i<e.length;i++)r[e[i].id]=!0;for(i=0;i<t.length;i++){var a=(d=t[i]).inputs;for(var s in a){for(var u=a[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){d.outputs.forEach((function(t){return r[t.id]=!0})),c=!0,o[d.id]=!0;break}if(c)break}}var h={};h[n.id]=!0;var f={};for(i=t.length-1;i>=0;i--)for(a=(d=t[i]).inputs,l=0;l<d.outputs.length;l++)if(h[d.outputs[l].id]){for(var s in a)h[a[s].id]=!0,f[d.id]=!0;break}var p=[];for(i=0;i<t.length;i++){var d;if(o[(d=t[i]).id]&&f[d.id]){var v={};for(var s in d.inputs){var m=d.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},d);g.inputs=v,g.outputs=d.outputs,p.push(g)}}return p}(this.state.activeTape,e,i);if(!r&&0===a.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[i.id]=null==n?(r=nt(D(t=i.shape),"float32"),Ot.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var o=e[r],i=[];if(o.outputs.forEach((function(e){var n=t[e.id];null!=n?i.push(n):i.push(null)})),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");var a=o.gradient(i),s=function(e){if(!(e in a))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(a)+".");var r=n((function(){return a[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 i=o.inputs[e];if(!A(r.shape,i.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 '"+i.shape+"'");if(null==t[i.id])t[i.id]=r;else{var s=t[i.id];t[i.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,a,(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:i,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return I(J(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];I(r.every((function(t){return t instanceof xt})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var i={};return r.forEach((function(t,e){i[e]=t})),e.runKernelFunc((function(e,o){return I((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"})),I(J(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),i,(function(t,e){var o=n.gradFunc(t,e),i=Array.isArray(o)?o:[o];I(i.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(...)."})),I(i.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 a={};return i.forEach((function(t,e){a[e]=function(){return t}})),a}))}},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 u(this,void 0,void 0,(function(){var e,n;return c(this,(function(r){switch(r.label){case 0:return e=ot(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=ot()-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 Ft,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}(),Ot=function(){var t=function(){if(null==Nt){var t=void 0;if("undefined"!=typeof window)t=window;else if(void 0!==n.g)t=n.g;else if(void 0!==o)t=o;else{if("undefined"==typeof self)throw new Error("Could not find a global object");o=self}Nt=t}return Nt}();if(null==t._tfengine){var e=new l(t);t._tfengine=new Mt(e)}return function(t){p=t}(t._tfengine.ENV),mt=function(){return t._tfengine},t._tfengine}();function Pt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Bt=f();Bt.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.")})),Bt.registerFlag("IS_BROWSER",(function(){return Pt()})),Bt.registerFlag("IS_NODE",(function(){return void 0!==o&&void 0!==o.versions&&void 0!==o.versions.node})),Bt.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Bt.registerFlag("PROD",(function(){return!1})),Bt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Bt.getBool("DEBUG")})),Bt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Bt.registerFlag("IS_TEST",(function(){return!1}));var Lt,Wt,zt,Ut={},Vt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Gt(t,e){Ut[t]=e}function Ht(t){t in Ut||(Ut[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);return e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Ut[t]}),!1),1===t?e.getContext("webgl",Vt)||e.getContext("experimental-webgl",Vt):e.getContext("webgl2",Vt)}(t));var e=Ut[t];return e.isContextLost()?(delete Ut[t],Ht(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),Ut[t])}function qt(t,e){return[e,t]}function jt(t){var e=D(t);return F(Math.ceil(e/4))}function Kt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Xt(t,e){var n,r,o,i,a,s,u,c,l,h=t;return 2===f().getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,o=h.RGBA16F,i=h.RGBA32F,a=h.RED,s=4,u=1,c=h.HALF_FLOAT,l=h.FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,i=h.RGBA,a=t.RGBA,s=4,u=4,c=null!=e?e.HALF_FLOAT_OES:null,l=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c,textureTypeFloat:l}}function Yt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+Jt(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Lt||(Lt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Wt||(Wt={})),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={}));function $t(t){return!!(f().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||5.96e-8<Math.abs(t)&&Math.abs(t)<65504)}function Jt(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 Qt(t,e,n){return we(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function Zt(t,e,n){var r=we(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Yt(t,e,(function(){return t.shaderSource(r,n)})),Yt(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 te(t,e,n){var r=we(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Yt(t,e,(function(){return t.shaderSource(r,n)})),Yt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=re.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"),i=o.length.toString().length+2,a=o.map((function(t,e){return M((e+1).toString(),i)+t})),s=0,u=0;u<a.length;u++)s=Math.max(a[u].length,s);var c=a.slice(0,r-1),l=a.slice(r-1,r),h=a.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+M(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 ee,ne,re=/ERROR: [0-9]+:([0-9]+):/g;function oe(t,e){return we(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function ie(t,e,n){if(Yt(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 ae(t,e,n){if(Yt(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 se(t,e,n){var r=we(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Yt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),Yt(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function ue(t,e,n){var r=we(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Yt(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),Yt(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function ce(t,e){return we(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function le(t,e){var n=f().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)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function he(t,e){return we(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function fe(t,e,n,r,o,i,a,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Yt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,o)})),Yt(t,e,(function(){return t.vertexAttribPointer(u,i,t.FLOAT,!1,a,s)})),Yt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function pe(t,e,n,r){Ce(t,r),Yt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function de(t,e,n,r){return we(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function ve(t,e,n){return t.getUniformLocation(e,n)}function me(t,e,n,r,o,i){Yt(t,e,(function(){return pe(t,e,r,i)})),Yt(t,e,(function(){return t.uniform1i(o,i)}))}function ge(t,e,n,r){Yt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Yt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function ye(t,e,n){Yt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Yt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function xe(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+be(t,e))}function be(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 we(t,e,n,r){var o=Yt(t,e,(function(){return n()}));if(null==o)throw new Error(r);return o}function Ce(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 Ee(t,e){return void 0===e&&(e=2),D(t.slice(0,t.length-e))}function _e(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 Ie(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ee(t)].concat(_e(t))),e}function Re(t,e){var n;void 0===e&&(e=!1);var r=f().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map((function(e,n){return n>=t.length-2?E(t[n]):t[n]}))).length&&(t=[2,t[0]])),2!==t.length){var o=L(t);t=o.newShape}var i=D(t);if(t.length<=1&&i<=r)return[1,i];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var a=Ee(t),s=2,u=2;return t.length&&(s=(n=_e(t))[0],u=n[1]),F(i=a*(s/2)*(u/2)).map((function(t){return 2*t}))}return F(i)}function Se(t){return t%2==0}function ke(t,e){if(A(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(Se(n)&&Se(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Se(t[0])&&Se(e[0])}function De(t){if(null==ee){var e=Ht(t);ee=e.getParameter(e.MAX_TEXTURE_SIZE)}return ee}function Ae(t){if(null==ne){var e=Ht(t);ne=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ne)}function Te(t){if(0===t)return 0;var e=Ht(t);return Ne(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ne(e,"EXT_disjoint_timer_query")?1:0}function Ne(t,e){return null!=t.getExtension(e)}function Fe(t){try{if(null!=Ht(t))return!0}catch(t){return!1}return!1}function Me(t){if(0===t)return!1;var e=Ht(t);if(1===t){if(!Ne(e,"OES_texture_float"))return!1}else if(!Ne(e,"EXT_color_buffer_float"))return!1;return Pe(e)}function Oe(t){if(0===t)return!1;var e=Ht(t);if(1!==t){if(Ne(e,"EXT_color_buffer_float"))return Pe(e);if(Ne(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Xt(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 i=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),i}(e,n)}return!1}return!!Ne(e,"OES_texture_float")&&!!Ne(e,"WEBGL_color_buffer_float")&&Pe(e)}function Pe(t){var e=Xt(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 Be(t){return 2===t&&null!=Ht(t).fenceSync}var Le=Object.freeze({callAndCheck:Yt,canBeRepresented:$t,getWebGLErrorMessage:Jt,getExtensionOrThrow:Qt,createVertexShader:Zt,createFragmentShader:te,createProgram:oe,linkProgram:ie,validateProgram:ae,createStaticVertexBuffer:se,createStaticIndexBuffer:ue,getNumChannels:function(){return 2===f().getNumber("WEBGL_VERSION")?1:4},createTexture:ce,validateTextureSize:le,createFramebuffer:he,bindVertexBufferToProgramAttribute:fe,bindTextureUnit:pe,unbindTextureUnit:function(t,e,n){Ce(t,n),Yt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:de,getProgramUniformLocation:ve,bindTextureToProgramUniformSampler:me,bindCanvasToFramebuffer:function(t,e){Yt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Yt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Yt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:ge,unbindColorTextureFromFramebuffer:ye,validateFramebuffer:xe,getFramebufferErrorMessage:be,getBatchDim:Ee,getRowsCols:_e,getShapeAs3D:Ie,getTextureShapeFromLogicalShape:Re,isReshapeFree:ke,getWebGLMaxTextureSize:De,resetMaxTextureSize:function(){ee=null},resetMaxTexturesInShader:function(){ne=null},getMaxTexturesInShader:Ae,getWebGLDisjointQueryTimerVersion:Te,hasExtension:Ne,isWebGLVersionEnabled:Fe,isCapableOfRenderingToFloatTexture:Me,isDownloadFloatTextureEnabled:Oe,isWebGLFenceEnabled:Be}),We=f();function ze(t){f().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ue(t,e){return Ot.tidy(t,e)}function Ve(t){Tt(t).forEach((function(t){return t.dispose()}))}function Ge(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];f().getBool("IS_TEST")||console.warn.apply(console,t)}function He(t,e){var n=t;if(H(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||H(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&f().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||H(e)){I(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),I(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),i=0;i<e.length;++i)t(e[i],o,r.concat(i))}else I(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}))}(t,r,[]),r}function qe(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 je(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof xt)return qe(r,t.dtype,e,n),t;var o=$(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),qe(r,o,e,n),null==t||!H(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var i=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+i+"'")}var a=He(t,o);H(t)||Array.isArray(t)||(t=[t]);var s="string"!==o?tt(t,o,f().getBool("DEBUG")):k(t,[],!0);return Ot.makeTensor(s,a,o)}function Ke(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 je(t,e+"["+r+"]",n)}),r)}function Xe(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function Ye(t,e,n){for(var r=t.length+e.length,o=[],i=0,a=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[i++]):o.push(e[a++]);return o}function $e(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 Je(t,e){return Ye(t,e.map((function(t){return 1})),e)}function Qe(t,e,n){I(Xe(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function Ze(t,e){if(Xe(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 tn(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 en(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function nn(t,e){var n=t[0].length;t.forEach((function(t,e){I(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+")"}))})),I(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 i=0;i<n;i++)I(i===e||t[i]===r[i],(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 rn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function on(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];Ot.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Ot.endScope(o),o}catch(t){throw Ot.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}We.registerFlag("HAS_WEBGL",(function(){return We.getNumber("WEBGL_VERSION")>0})),We.registerFlag("WEBGL_VERSION",(function(){return Fe(2)?2:Fe(1)?1:0})),We.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===We.get("WEBGL_VERSION")})),We.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),We.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),We.registerFlag("WEBGL_PACK",(function(){return We.getBool("HAS_WEBGL")})),We.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_CLIP",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),We.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_PACK_REDUCE",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_CONV_IM2COL",(function(){return We.getBool("WEBGL_PACK")})),We.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return De(We.getNumber("WEBGL_VERSION"))})),We.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return Ae(We.getNumber("WEBGL_VERSION"))})),We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=We.getNumber("WEBGL_VERSION");return 0===t?0:Te(t)})),We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return We.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})),We.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Me(We.getNumber("WEBGL_VERSION"))})),We.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!We.getBool("WEBGL_FORCE_F16_TEXTURES")&&We.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),We.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Oe(We.getNumber("WEBGL_VERSION"))})),We.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return Be(We.getNumber("WEBGL_VERSION"))})),We.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return We.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),yt=ze;var an=on({complex_:function(t,e){var n=je(t,"real","complex"),r=je(e,"imag","complex");return R(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Ot.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),sn=on({real_:function(t){var e=je(t,"input","real");return Ot.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),un=on({imag_:function(t){var e=je(t,"input","imag");return Ot.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function cn(t,e,n){return ln(t,e,He(t,n),n)}function ln(t,e,n,r){if(null==r&&(r=$(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!H(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){it(e);var o=D(e),i=D(n);I(o===i,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+i}));for(var a=0;a<n.length;++a){var s=n[a],u=a!==n.length-1||s!==D(e.slice(a));I(n[a]===e[a]||!u,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return H(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?tt(t,r,f().getBool("DEBUG")):k(t,[],!0),Ot.makeTensor(t,e,r)}function hn(t,e){if((H(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&&H(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return ln(t,[],[],e)}function fn(t,e){S(t);var n=He(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ln(t,null,n,e)}function pn(t,e,n){if(S(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=He(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 ln(t,e,r,n)}function dn(t,e,n){if(S(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=He(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 ln(t,e,r,n)}function vn(t,e,n){if(S(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=He(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 ln(t,e,r,n)}function mn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=mn(t,"float32"),r=gn(t,"float32");return an(n,r)}var o=nt(D(t),e);return Ot.makeTensor(o,t,e)}function gn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=gn(t,"float32"),r=gn(t,"float32");return an(n,r)}var o=rt(D(t),e);return Ot.makeTensor(o,t,e)}function yn(t,e,n){return Ot.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function xn(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 gn([0],r);var o=rt(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var i=1;i<o.length;i++)o[i]=o[i-1]+n;return fn(o,r)}var bn=on({onesLike_:function(t){var e=je(t,"x","onesLike");if("complex64"===e.dtype){var n=bn(sn(e)),r=wn(un(e));return an(n,r)}return Ot.runKernelFunc((function(t){return t.onesLike(e)}),{$x:e},(function(t,e){return{$x:function(){return wn(t)}}}))}}),wn=on({zerosLike_:function(t){var e=je(t,"x","zerosLike");return Ot.runKernelFunc((function(t){return t.zerosLike(e)}),{$x:e},(function(t,e){return{$x:function(){return wn(t)}}}))}}),Cn=on({concat_:function(t,e){void 0===e&&(e=0),I(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=Ke(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=B(e,n[0].shape)[0];var r=rn(n.map((function(t){return t.shape})),e);if(0===D(r))return cn([],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}));nn(o,e);var i=n,a={axis:e};return Ot.runKernelFunc((function(t){return t.concat(n,e)}),i,(function(t){var n=o.map((function(t){return t[e]}));return Sn(t,n,e).map((function(t){return function(){return t}}))}),"Concat",a)}}),En=on({concat1d_:function(t){return Cn(t,0)}}),_n=on({concat2d_:function(t,e){return Cn(t,e)}}),In=on({concat3d_:function(t,e){return Cn(t,e)}}),Rn=on({concat4d_:function(t,e){return Cn(t,e)}}),Sn=on({split_:function(t,e,n){void 0===n&&(n=0);var r,o=je(t,"x","split");return n=B(n,o.shape)[0],"number"==typeof e?(I(o.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(o.shape[n]/e)):(I(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),Ot.runKernelFunc((function(t){return t.split(o,r,n)}),{$x:o},(function(t){return{$x:function(){return Cn(t,n)}}}))}});function kn(t,e){return t(e={exports:{}},e.exports),e.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self&&self;var Dn=kn((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 i(t,e){var n=new r(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)})),An=kn((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 i(t,e){var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)})),Tn=kn((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 i(t,e){var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)})),Nn=kn((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 i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)})),Fn=kn((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,i=e.i;return e.w=r=r+1640531527|0,n=o[i+34&127],t=o[i=i+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[i]=n^t,e.i=i,n+(r^r>>>16)|0},function(t,e){var n,r,o,i,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,i=-32;i<u;++i)e&&(r^=e.charCodeAt((i+32)%e.length)),0===i&&(a=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,i>=0&&(a=a+1640531527|0,o=0==(n=s[127&i]^=r+a)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,i=512;i>0;--i)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=a,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 i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)})),Mn=kn((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 i(t,e){var n=new r(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&o(i,n),a.state=function(){return o(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)})),On=kn((function(t){!function(e,r){var o,i=this,a=256,s="random",u=r.pow(a,6),c=r.pow(2,52),l=2*c,h=255;function f(t,n,h){var f=[],g=v(function t(e,n){var r,o=[],i=typeof e;if(n&&"object"==i)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==i?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return o&&(t=o.randomBytes)?t=t(a):(t=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,m(e)]}}():t,3),f),y=new p(f),x=function(){for(var t=y.g(6),e=u,n=0;t<c;)t=(t+n)*a,e*=a,n=y.g(1);for(;t>=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|y.g(4)},x.quick=function(){return y.g(4)/4294967296},x.double=x,v(m(y.S),e),(n.pass||h||function(t,e,n,o){return o&&(o.S&&d(o,y),t.state=function(){return d(y,{})}),n?(r[s]=t,e):t})(x,g,"global"in n?n.global:this==r,n.state)}function p(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 d(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(r["seed"+s]=f,v(r.random(),e),t.exports){t.exports=f;try{o=n(91423)}catch(t){}}}([],Math)}));On.alea=Dn,On.xor128=An,On.xorwow=Tn,On.xorshift7=Nn,On.xor4096=Fn,On.tychei=Mn;var Pn=On.alea,Bn=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 i=o||Math.random();this.random=Pn(i.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,i=void 0,a=void 0;do{a=(o=2*this.random()-1)*o+(i=2*this.random()-1)*i}while(a>=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*i*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}(),Ln=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=Pn(o.toString()),this.randn=new Bn(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,i;;){do{r=this.randn.nextValue(),i=1+this.c*r}while(i<=0);if(i*=i*i,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-i+Math.log(i)),(o=this.randu())<e||Math.log(o)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),Wn=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=Pn(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 zn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",it(t),new vt(t,e,n)}var Un=on({batchToSpaceND_:function(t,e,n){var r=je(t,"x","batchToSpaceND"),o=e.reduce((function(t,e){return t*e}));return I(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),I(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),I(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})),Ot.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),Vn=on({broadcastTo_:function(t,e){var n=je(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 i=Array.from(e),a=e.length-1;a>=0;a--)if(n.shape[a]===e[a])i[a]=1;else if(1!==n.shape[a])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var s=i.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));return 0===s.length?n.clone():Ot.runKernelFunc((function(t){return t.tile(n,i)}),{input:n},(function(t){return{input:function(){return t.sum(s,!0)}}}))}}),Gn=on({cast_:function(t,e){var n=je(t,"x","cast");if(!V(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 Ot.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),Hn=on({clone_:function(t){var e=je(t,"x","clone",null);return Ot.runKernelFunc((function(){return Ot.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{$x:e},(function(t){return{$x:function(){return t.toFloat()}}}))}}),qn=on({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=je(t,"x","cumsum"),i=Ze([e|=0],o.rank),a=o;null!=i&&(a=o.transpose(i));var s=en(1,o.rank)[0],u=Ot.runKernelFunc((function(t){return t.cumsum(a,s,n,r)}),{permutedX:a},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=i&&(u=u.transpose(i)),u}}),jn=on({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=je(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return I(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})),I(i*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape})),I(a%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape})),Ot.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),Kn=on({expandDims_:function(t,e){void 0===e&&(e=0);var n=je(t,"x","expandDims",null);I(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(I(-(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),ar(n,r)}}),Xn=on({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=zn([t,e],r),i=t<=e?t:e,a=0;a<i;++a)o.set(1,a,a);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return lr(Kn(s,0),[n[0],1,1]);if(2===n.length)return lr(Kn(Kn(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return lr(Kn(Kn(Kn(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.")}}),Yn=on({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=je(t,"logits","multinomial"),i=o.size,a=o.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(a>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?o.as2D(1,-1):o,u=Ot.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===a?u.as1D():u}}),$n=on({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=je(t,"indices","oneHot","int32"),i=o.shape.concat([e]);return o=o.flatten(),Ot.runKernelFunc((function(t){return t.oneHot(o,e,n,r)}),{$indices:o},(function(t){return{$indices:function(){return gn(o.shape,"float32")}}})).reshape(i)}}),Jn=on({pad_:function(t,e,n){void 0===n&&(n=0);var r=je(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 Ot.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)}}),Qn=on({pad1d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),Jn(t,[e],n)}}),Zn=on({pad2d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Jn(t,e,n)}}),tr=on({pad3d_:function(t,e,n){return void 0===n&&(n=0),I(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Jn(t,e,n)}}),er=on({pad4d_:function(t,e,n){return void 0===n&&(n=0),I(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Jn(t,e,n)}}),nr=on({rand_:function(t,e,n){var r=D(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 i=0;i<r;i++)o[i]=e();return Ot.makeTensor(o,t,n)}}),rr=on({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 i=new Bn(e,n,r,!1,o),a=zn(t,r),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),or=on({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 i=new Ln(e,n,r,o),a=zn(t,r),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),ir=on({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var i=zn(t,r),a=new Wn(e,n,null,o),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),ar=on({reshape_:function(t,e){var n=je(t,"x","reshape",null);e=P(e,n.size),I(n.size===D(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Ot.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),sr=on({spaceToBatchND_:function(t,e,n){var r=je(t,"x","spaceToBatchND");return I(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),I(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),I(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()})),Ot.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),ur=on({squeeze_:function(t,e){var n=je(t,"x","squeeze");return ar(n,L(n.shape,e).newShape)}}),cr=on({stack_:function(t,e){void 0===e&&(e=0);var n=Ke(t,"tensors","stack");if(I(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,i=n[0].dtype;I(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){R(o,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){I(i===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var a=n.map((function(t){return t.expandDims(e)}));return Cn(a,e)}}),lr=on({tile_:function(t,e){var n=je(t,"x","tile",null);I(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 Ot.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=wn(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 i=0;i<e[1];++i)n=n.add(t.slice([o*r.shape[0],i*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(o=0;o<e[0];++o)for(i=0;i<e[1];++i)for(var a=0;a<e[2];++a)n=n.add(t.slice([o*r.shape[0],i*r.shape[1],a*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(i=0;i<e[1];++i)for(a=0;a<e[2];++a)for(var s=0;s<e[3];++s)n=n.add(t.slice([o*r.shape[0],i*r.shape[1],a*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),"Tile",o,r)}}),hr=on({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 i=new Bn(e,n,r,!0,o),a=zn(t,r),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),fr=on({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=je(t,"x","unstack");I(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 Ot.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return cr(t,e)}}}),"Unpack",r)}});function pr(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 i=e.length,a=0;a<i;++a)o=o.concat([t[a+1]/e[a],e[a]]);o=o.concat(t.slice(i+1))}return o}function dr(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 i=[],a=[];for(o=1;o<t;++o)o>=2*e+1||o%2==1?a.push(o):i.push(o);r.push.apply(r,i),r.push(0),r.push.apply(r,a)}return r}function vr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var i=1;i<t.length;++i)i<=e.length?r?o.push(e[i-1]*t[i]):o.push(t[i]/e[i-1]):o.push(t[i]);return o}function mr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function gr(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 yr(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,i=0;i<n.length-1;++i)o*=n[i];var a=t.shape,s=n.slice();s.pop();var u=1;for(i=r;i<t.rank;++i)u*=a[i],s.push(a[i]);var c=Z(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,o,u,c]}Object.freeze({prepareAndValidate:yr});function xr(t){return t<=30?t:Q(t,Math.floor(Math.sqrt(t)))}function br(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,i="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(i+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(i+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(i+" update.rank != "+(o+t.length-r));for(var a=0;a<o;++a)if(n.shape[a]!==e.shape[a])throw new Error(i+" updates.shape["+a+"] ("+n.shape[a]+") != indices.shape["+a+"] ("+e.shape[a]+").");for(a=0;a<n.rank-o;++a)if(n.shape[a+o]!==t[a+r])throw new Error(i+" updates.shape["+(a+o)+"] ("+n.shape[a+o]+") != shape["+(a+o)+"] ("+t[a+o]+")")}function wr(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)}br(n,e,t)}function Cr(t,e,n){for(var r=e.shape.length,o=r>1?e.shape[r-1]:1,i=n.length,a=1,s=o;s<i;++s)a*=n[s];var u=o<1?1:o;return{sliceRank:o,numUpdates:D(e.shape)/u,sliceSize:a,strides:Z(n.slice(0,o)).concat([1]),outputSize:D(n)}}Object.freeze({validateUpdateShape:br,validateInput:wr,calculateShapes:Cr});function Er(t,e,n){I(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+")."})),I(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){I(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 _r(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function Ir(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 Rr(t,e,n,r,o){var i=e[o],a=n[o]||1;(t&1<<o||null==i)&&(i=a>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return i<0&&(i+=s),C(0,i,s-1)}function Sr(t,e,n,r,o){var i=e[o],a=n[o]||1;(t&1<<o||null==i)&&(i=a>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return i<0&&(i+=s),a>0?C(0,i,s):C(-1,i,s-1)}function kr(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 Dr(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}Object.freeze({assertParamsValid:Er,maskToAxes:_r,computeOutShape:Ir,startForAxis:Rr,stopForAxis:Sr,isSliceContinous:kr,computeFlatOffset:Dr});function Ar(t){return Ot.customGrad(t)}var Tr=on({softmax_:function(t,e){void 0===e&&(e=-1);var n=je(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 Ot.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])}}),Nr=on({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=je(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 Ar((function(t,n){var r=t.max(e,!0),o=t.sub(r),i=o.toFloat().sub(o.exp().sum(e,!0).log());return n([i]),{value:i,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),Fr=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}(),Mr=function(){function t(){}return t.prototype.time=function(t){return Or("time")},t.prototype.read=function(t){return Or("read")},t.prototype.readSync=function(t){return Or("readSync")},t.prototype.numDataIds=function(){return Or("numDataIds")},t.prototype.disposeData=function(t){return Or("disposeData")},t.prototype.write=function(t,e,n){return Or("write")},t.prototype.move=function(t,e,n,r){return Or("move")},t.prototype.memory=function(){return Or("memory")},t.prototype.floatPrecision=function(){return Or("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return Or("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,Or("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return Or("slice")},t.prototype.stridedSlice=function(t,e,n,r){return Or("stridedSlice")},t.prototype.unstack=function(t,e){return Or("unstack")},t.prototype.reverse=function(t,e){return Or("reverse")},t.prototype.concat=function(t,e){return Or("concat")},t.prototype.neg=function(t){return Or("neg")},t.prototype.add=function(t,e){return Or("add")},t.prototype.addN=function(t){return Or("addN")},t.prototype.subtract=function(t,e){return Or("subtract")},t.prototype.multiply=function(t,e){return Or("multiply")},t.prototype.realDivide=function(t,e){return Or("realDivide")},t.prototype.floorDiv=function(t,e){return Or("floorDiv")},t.prototype.sum=function(t,e){return Or("sum")},t.prototype.prod=function(t,e){return Or("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return Or("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return Or("argMin")},t.prototype.argMax=function(t,e){return Or("argMax")},t.prototype.equal=function(t,e){return Or("equal")},t.prototype.notEqual=function(t,e){return Or("notEqual")},t.prototype.less=function(t,e){return Or("less")},t.prototype.lessEqual=function(t,e){return Or("lessEqual")},t.prototype.greater=function(t,e){return Or("greater")},t.prototype.greaterEqual=function(t,e){return Or("greaterEqual")},t.prototype.logicalNot=function(t){return Or("logicalNot")},t.prototype.logicalAnd=function(t,e){return Or("logicalAnd")},t.prototype.logicalOr=function(t,e){return Or("logicalOr")},t.prototype.where=function(t){return Or("where")},t.prototype.select=function(t,e,n){return Or("select")},t.prototype.topk=function(t,e,n){return Or("topk")},t.prototype.min=function(t,e){return Or("min")},t.prototype.minimum=function(t,e){return Or("minimum")},t.prototype.mod=function(t,e){return Or("mod")},t.prototype.max=function(t,e){return Or("max")},t.prototype.maximum=function(t,e){return Or("maximum")},t.prototype.all=function(t,e){return Or("all")},t.prototype.any=function(t,e){return Or("any")},t.prototype.squaredDifference=function(t,e){return Or("squaredDifference")},t.prototype.ceil=function(t){return Or("ceil")},t.prototype.floor=function(t){return Or("floor")},t.prototype.round=function(t){return Or("round")},t.prototype.sign=function(t){return Or("sign")},t.prototype.isNaN=function(t){return Or("isNaN")},t.prototype.isInf=function(t){return Or("isInf")},t.prototype.isFinite=function(t){return Or("isFinite")},t.prototype.pow=function(t,e){return Or("pow")},t.prototype.exp=function(t){return Or("exp")},t.prototype.expm1=function(t){return Or("expm1")},t.prototype.softmax=function(t,e){return Or("softmax")},t.prototype.log=function(t){return Or("log")},t.prototype.log1p=function(t){return Or("log1p")},t.prototype.sqrt=function(t){return Or("sqrt")},t.prototype.rsqrt=function(t){return Or("rsqrt")},t.prototype.square=function(t){return Or("square")},t.prototype.reciprocal=function(t){return Or("reciprocal")},t.prototype.relu=function(t){return Or("relu")},t.prototype.relu6=function(t){return Or("relu6")},t.prototype.prelu=function(t,e){return Or("prelu")},t.prototype.elu=function(t){return Or("elu")},t.prototype.eluDer=function(t,e){return Or("eluDer")},t.prototype.selu=function(t){return Or("selu")},t.prototype.int=function(t){return Or("int")},t.prototype.clip=function(t,e,n){return Or("clip")},t.prototype.abs=function(t){return Or("abs")},t.prototype.complexAbs=function(t){return Or("complexAbs")},t.prototype.sigmoid=function(t){return Or("sigmoid")},t.prototype.softplus=function(t){return Or("softplus")},t.prototype.sin=function(t){return Or("sin")},t.prototype.cos=function(t){return Or("cos")},t.prototype.tan=function(t){return Or("tan")},t.prototype.asin=function(t){return Or("asin")},t.prototype.acos=function(t){return Or("acos")},t.prototype.atan=function(t){return Or("atan")},t.prototype.atan2=function(t,e){return Or("atan2")},t.prototype.sinh=function(t){return Or("sinh")},t.prototype.cosh=function(t){return Or("cosh")},t.prototype.tanh=function(t){return Or("tanh")},t.prototype.asinh=function(t){return Or("asinh")},t.prototype.acosh=function(t){return Or("acosh")},t.prototype.atanh=function(t){return Or("atanh")},t.prototype.erf=function(t){return Or("erf")},t.prototype.step=function(t,e){return Or("step")},t.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,Or("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return Or("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return Or("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return Or("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,Or("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return Or("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return Or("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return Or("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return Or("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return Or("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return Or("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return Or("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return Or("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return Or("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return Or("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return Or("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return Or("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return Or("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return Or("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return Or("reshape")},t.prototype.cast=function(t,e){return Or("cast")},t.prototype.tile=function(t,e){return Or("tile")},t.prototype.pad=function(t,e,n){return Or("pad")},t.prototype.transpose=function(t,e){return Or("transpose")},t.prototype.gather=function(t,e,n){return Or("gather")},t.prototype.gatherND=function(t,e){return Or("gatherND")},t.prototype.scatterND=function(t,e,n){return Or("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return Or("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return Or("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return Or("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return Or("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return Or("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return Or("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,o,i){return Or("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){return Or("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,o,i,a){return Or("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return Or("multinomial")},t.prototype.oneHot=function(t,e,n,r){return Or("oneHot")},t.prototype.cumsum=function(t,e,n,r){return Or("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return Or("nonMaxSuppression")},t.prototype.fft=function(t){return Or("fft")},t.prototype.ifft=function(t){return Or("ifft")},t.prototype.complex=function(t,e){return Or("complex")},t.prototype.real=function(t){return Or("real")},t.prototype.imag=function(t){return Or("imag")},t.prototype.cropAndResize=function(t,e,n,r,o,i){return Or("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return Or("depthToSpace")},t.prototype.split=function(t,e,n){return Or("split")},t.prototype.sparseToDense=function(t,e,n,r){return Or("sparseToDense")},t.prototype.diag=function(t){return Or("diag")},t.prototype.fill=function(t,e,n){return Or("fill")},t.prototype.onesLike=function(t){return Or("onesLike")},t.prototype.zerosLike=function(t){return Or("zerosLike")},t.prototype.linspace=function(t,e,n){return Or("linspace")},t.prototype.dispose=function(){return Or("dispose")},t}();function Or(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function Pr(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var i=n-1-o,a=t[i]||1;(e[e.length-1-o]||1)>1&&1===a&&r.unshift(i)}return r}function Br(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],i=e.length-r-1,a=e[i];(null==o||1===o&&a>1)&&n.unshift(i)}return n}function Lr(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var i=t[t.length-o-1];null==i&&(i=1);var a=e[e.length-o-1];if(null==a&&(a=1),1===i)n.unshift(a);else if(1===a)n.unshift(i);else{if(i!==a)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(i)}}return n}function Wr(t,e,n,r,o,i,a){void 0===a&&(a="channelsLast");var s,u=Hr(e),c=u[0],l=u[1];if("channelsLast"===a)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);s=[c,l,t[1],t[1]]}return Ur(t,s,n,r,o,i,!1,a)}function zr(t,e,n,r,o,i,a){void 0===a&&(a="NDHWC");var s,u,c=qr(e),l=c[0],h=c[1],f=c[2];if("NDHWC"===a)u="channelsLast",s=[l,h,f,t[4],t[4]];else{if("NCDHW"!==a)throw new Error("Unknown dataFormat "+a);u="channelsFirst",s=[l,h,f,t[1],t[1]]}return Vr(t,s,n,r,o,!1,u,i)}function Ur(t,e,n,r,o,i,a,s){void 0===a&&(a=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3];if("channelsLast"===s)c=t[0],l=t[1],h=t[2],f=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],f=t[1],l=t[2],h=t[3]}var p,d=e[0],v=e[1],m=e[3],g=Hr(n),y=g[0],x=g[1],b=Hr(r),w=b[0],C=b[1],E=jr(d,w),_=jr(v,C),R=function(t,e,n,r,o,i,a,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=Gr(t,e,n));var i=t[1],a=Kr((t[0]-e+2*r)/n+1,o);I(T(a),(function(){return"The output # of rows ("+a+") must be an integer. Change the stride and/or zero pad parameters"}));var s=Kr((i-e+2*r)/n+1,o);return I(T(s),(function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"})),[a,s]}([e,n],i,r,t,s);c=h[0],l=h[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/o);var f=Math.max(0,(c-1)*r+i-e),p=Math.max(0,(l-1)*o+a-n),d=Math.floor(f/2),v=f-d,m=Math.floor(p/2);u={top:d,bottom:v,left:m,right:p-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-i+1)/r),l=Math.ceil((n-a+1)/o)}return{padInfo:u,outHeight:c,outWidth:l}}(o,l,h,y,x,E,_,i),S=R.padInfo,k=R.outHeight,D=R.outWidth,A=a?m*f:m;return"channelsFirst"===s?p=[c,A,k,D]:"channelsLast"===s&&(p=[c,k,D,A]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:h,inChannels:f,outHeight:k,outWidth:D,outChannels:A,padInfo:S,strideHeight:y,strideWidth:x,filterHeight:d,filterWidth:v,effectiveFilterHeight:E,effectiveFilterWidth:_,dilationHeight:w,dilationWidth:C,inShape:t,outShape:p,filterShape:e}}function Vr(t,e,n,r,o,i,a,s){void 0===i&&(i=!1),void 0===a&&(a="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3],p=u[4];if("channelsLast"===a)c=t[0],l=t[1],h=t[2],f=t[3],p=t[4];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);c=t[0],p=t[1],l=t[2],h=t[3],f=t[4]}var d,v=e[0],m=e[1],g=e[2],y=e[4],x=qr(n),b=x[0],w=x[1],C=x[2],E=qr(r),_=E[0],R=E[1],S=E[2],k=jr(v,_),D=jr(m,R),A=jr(g,S),N=function(t,e,n,r,o,i,a,s,u,c,l){var h,f,p,d;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,i){null==o&&(o=Gr(t,e,r));var a=t[1],s=t[2],u=Kr((t[0]-e+2*o)/r+1,i);I(T(u),(function(){return"The output # of depths ("+u+") must be an integer. Change the stride and/or zero pad parameters"}));var c=Kr((a-e+2*o)/r+1,i);I(T(c),(function(){return"The output # of rows ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var l=Kr((s-e+2*o)/r+1,i);return I(T(l),(function(){return"The output # of columns ("+l+") must be an integer. Change the stride and/or zero pad parameters"})),[u,c,l,1]}([e,n,r,1],s,0,o,t,l);f=v[0],p=v[1],d=v[2]}else if("same"===t){var m=((f=Math.ceil(e/o))-1)*o+s-e,g=((p=Math.ceil(n/i))-1)*i+u-n,y=((d=Math.ceil(r/a))-1)*a+c-r,x=Math.floor(m/2),b=m-x,w=Math.floor(g/2),C=g-w,E=Math.floor(y/2);h={top:w,bottom:C,left:E,right:y-E,front:x,back:b,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"},f=Math.ceil((e-s+1)/o),p=Math.ceil((n-u+1)/i),d=Math.ceil((r-c+1)/a)}return{padInfo:h,outDepth:f,outHeight:p,outWidth:d}}(o,l,h,f,b,w,C,k,D,A,s),F=N.padInfo,M=N.outDepth,O=N.outHeight,P=N.outWidth,B=i?y*p:y;return"channelsFirst"===a?d=[c,B,M,O,P]:"channelsLast"===a&&(d=[c,M,O,P,B]),{batchSize:c,dataFormat:a,inDepth:l,inHeight:h,inWidth:f,inChannels:p,outDepth:M,outHeight:O,outWidth:P,outChannels:B,padInfo:F,strideDepth:b,strideHeight:w,strideWidth:C,filterDepth:v,filterHeight:m,filterWidth:g,effectiveFilterDepth:k,effectiveFilterHeight:D,effectiveFilterWidth:A,dilationDepth:_,dilationHeight:R,dilationWidth:S,inShape:t,outShape:d,filterShape:e}}function Gr(t,e,n,r){void 0===r&&(r=1);var o=jr(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function Hr(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function qr(t){return"number"==typeof t?[t,t,t]:t}function jr(t,e){return e<=1?t:t+(t-1)*(e-1)}function Kr(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 Xr(t){var e=Hr(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Yr(t,e){return Xr(t)||Xr(e)}function $r(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function Jr(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=gn(t.shape),o=t.toFloat(),i=n.complex(o,r);return r.dispose(),o.dispose(),i}if(!G(t.dtype,e))return Ot.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var a=n.real(t);return i=a.cast(e),a.dispose(),i}if("int32"===e)return n.int(t);if("bool"===e){var s=hn(0,t.dtype);return i=n.notEqual(t,s),s.dispose(),i}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Qr(t,e){return Ot.makeTensorFromDataId(t.dataId,e,t.dtype)}function Zr(t,e,n){var r=(e-t)/(n-1),o=rt(n,"float32");o[0]=t;for(var i=1;i<o.length;i++)o[i]=o[i-1]+r;return fn(o,"float32")}Object.freeze({castTensor:Jr,reshapeTensor:Qr,linspaceImpl:Zr,upcastType:St,axesAreInnerMostDims:Xe,combineLocations:Ye,computeOutAndReduceShapes:$e,expandShapeToKeepDim:Je,assertAxesAreInnerMostDims:Qe,getAxesPermutation:Ze,getUndoAxesPermutation:tn,getInnerMostAxes:en,getBroadcastDims:Pr,getReductionAxes:Br,assertAndGetBroadcastShape:Lr,assertParamsConsistent:nn,computeOutShape:rn,computePool2DInfo:Wr,computePool3DInfo:zr,computeConv2DInfo:Ur,computeConv3DInfo:Vr,computeDefaultPad:Gr,tupleValuesAreOne:Xr,eitherStridesOrDilationsAreOne:Yr,convertConv2DDataFormat:$r,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:xr});function to(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 eo(t,e){return{real:t[2*e],imag:t[2*e+1]}}function no(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function ro(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function oo(t,e,n){var r=function(t,e,n){return function(t,e,n){for(var r=0,o=t.length,i=0,a=!1;r<o;){var s=n(e,t[i=r+(o-r>>>1)]);s>0?r=i+1:(o=i,a=!s)}return a?r:-r-1}(t,e,n||io)}(t,e,n),o=r<0?-(r+1):r;t.splice(o,0,e)}function io(t,e){return t>e?1:t<e?-1:0}function ao(t,e,n,r,o){return uo(t,e,n,r,o,0).selectedIndices}function so(t,e,n,r,o,i){var a=uo(t,e,n,r,o,i,!0);return a.numValidOutputs.dispose(),{selectedIndices:a.selectedIndices,selectedScores:a.selectedScores}}function uo(t,e,n,r,o,i,a,s){void 0===a&&(a=!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(ho),c=i>0?-.5/i:0,l=[],h=[];l.length<n&&u.length>0;){var f=u.pop(),p=f.score,d=f.boxIndex,v=f.suppressBeginIndex;if(p<o)break;for(var m=!1,g=l.length-1;g>=v;--g){var y=co(t,d,l[g]);if(y>=r){m=!0;break}if(f.score=f.score*lo(r,c,y),f.score<=o)break}f.suppressBeginIndex=l.length,m||(f.score===p?(l.push(d),h.push(f.score)):f.score>o&&oo(u,f,ho))}var x=l.length;return s&&(l.fill(0,x),h.fill(0,x)),{selectedIndices:fn(l,"int32"),selectedScores:fn(h,"float32"),numValidOutputs:hn(x,"int32")}}function co(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),f=Math.max(o[1],o[3]),p=(s-i)*(u-a),d=(h-c)*(f-l);if(p<=0||d<=0)return 0;var v=Math.max(i,c),m=Math.max(a,l),g=Math.min(s,h),y=Math.min(u,f),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(p+d-x)}function lo(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function ho(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function fo(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map((function(e){o[n]=e;var i=t.slice(r,o);return r[n]+=e,i}))}function po(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=zn(n,t.dtype);for(r=0;r<o.values.length;++r){for(var i=o.indexToLoc(r),a=new Array(t.rank),s=0;s<a.length;s++)a[s]=i[s]%t.shape[s];var u=t.locToIndex(a);o.values[r]=t.values[u]}return o.toTensor()}function vo(t,e,n,r,o){for(var i=e[e.length-1],a=[t.length/i,i],s=a[0],u=a[1],c=W(n,s*r),l=W("int32",s*r),h=0;h<s;h++){for(var f=h*u,p=t.subarray(f,f+u),d=[],v=0;v<p.length;v++)d.push({value:p[v],index:v});d.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]=d[v].value,y[v]=d[v].index}var x=e.slice();return x[x.length-1]=r,[cn(c,x,n),cn(l,x,"int32")]}function mo(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=zn(t,"int32"),i=zn([n.length,t.length],"int32");for(r=0;r<n.length;r++){var a=o.indexToLoc(n[r]),s=r*t.length;i.values.set(a,s)}return i.toTensor()}var go=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 "},yo=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 "},xo=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,i=t.inSize,a=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,a];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 bo(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function wo(t,e){return 1===e?[t]:bo(t,e)}function Co(){var t,e,n,r,o,i,a,s,u,c;return 2===f().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",i="outputColor",a="out vec4 outputColor;",s="\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 ",u="",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",o="texture2D",i="gl_FragColor",a="",s="\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 ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:i,defineOutput:a,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function Eo(t,e,n){void 0===n&&(n="index");var r=Z(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 _o(t){var e=Z(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 Io="\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 Ro(t,e,n,r){var o=[];t.forEach((function(t){var e=D(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 i,a,s=o.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?ko(t):So(t);var o=t.shapeInfo.logicalShape,i=e.logicalShape;return o.length<=i.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),i="get"+o+"AtOutCoords",a=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Pr(t.shapeInfo.logicalShape,e.logicalShape),c=Oo(s),l=s-a,h=["x","y","z","w","u","v"];n=0===a?"":s<2&&u.length>=1?"coords = 0;":u.map((function(t){return"coords."+h[t+l]+" = 0;"})).join("\n");var f;f=s<2&&a>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+l]})).join(", ");var p="return outputValue;",d=1===D(t.shapeInfo.logicalShape),v=1===D(e.logicalShape);if(1!==a||d||v){if(d&&!v)p=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var m=a-2,g=a-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?p="return vec4(outputValue.x);":u.indexOf(m)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}}else p="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+i+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+f+");\n "+p+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",i=e.texShape,a=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&A(a,i))return"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c,l=Oo(u),h=Pr(t.shapeInfo.logicalShape,e.logicalShape),f=u-s,p=["x","y","z","w","u","v"];c=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map((function(t){return"coords."+p[t+f]+" = 0;"})).join("\n");var d;return d=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+p[e+f]})).join(", "),"\n float "+o+"() {\n "+l+" coords = getOutputCoords();\n "+c+"\n return get"+r+"("+d+");\n }\n "}(t,e)),r}(t,e,r)})).join("\n"),c=e.texShape,l=Co(),h=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(l),f=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 "+Do+"\n "+Ao+"\n "+To+"\n "}(l);return e.isPacked?(i=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 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(A(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=(i=Math.ceil(n[2]/2))*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 / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+i+");\n int c = imod(index, "+i+") * 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),i=o,a="",s="b, r, c",u=2;u<t.length-1;u++)a="\n int b"+u+" = index / "+(i*=t[t.length-u-1])+";\n index -= b"+u+" * "+i+";\n "+a,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 "+a+"\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,i,a}(e.logicalShape,c),a=function(t){return"\n void setOutput(vec4 val) {\n "+t.output+" = val;\n }\n "}(l)):(i=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){return 1===e[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ":1===e[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ":"\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){return A(t,e)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ":1===t[1]?"\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 ":1===t[0]?"\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 ":"\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=Eo(["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=Eo(["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=Eo(["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=Eo(["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),a=function(t){return"\n void setOutput(float val) {\n "+t.output+" = vec4(val, 0, 0, 0);\n }\n "}(l)),r&&(f+=No),[f,h,a,s,i,u,n].join("\n")}function So(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],i=r[1];if(1===o&&1===i)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var a=t.shapeInfo.texShape;return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+a[0]+", "+a[1]+", "+Fo(e)+");\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 "+Mo(t)+"\n }\n ";var r=t.shapeInfo.texShape,o=r[0],i=r[1];if(1===i&&1===o)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var a=Fo(e);return 1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+a+") + 0.5) / "+o+".0);\n return sampleTexture("+e+", uv);\n }\n ":1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+a+") + 0.5) / "+i+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+o+", "+i+", index + "+a+");\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&&A(e,o)){var i=o[0];return"\n float "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o[1]+".0, "+i+".0);\n return sampleTexture("+n+", uv);\n }\n "}var a=L(e),s=a.newShape,u=a.keptDims,c=s;if(c.length<e.length)return"\n "+So(Po(t,c))+"\n float "+r+"(int row, int col) {\n return "+r+"("+Bo(["row","col"],u)+");\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 "+Mo(t)+"\n }\n ";var l=o[0],h=o[1],f=Fo(n);return 1===h?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+f+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+l+".0);\n return sampleTexture("+n+", uv);\n }\n ":1===l?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+f+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+h+".0, 0.5);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+e[1]+" + col + "+f+";\n vec2 uv = uvFromFlat("+l+", "+h+", 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],i=e[2],a=L(e),s=a.newShape,u=a.keptDims,c=s;if(c.length<e.length)return"\n "+So(Po(t,c))+"\n float "+r+"(int row, int col, int depth) {\n return "+r+"("+Bo(["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+", "+i+", 1)));\n "+Mo(t)+"\n }\n ";var l=t.shapeInfo.texShape,h=l[0],f=l[1],p=t.shapeInfo.flatOffset;return f===o&&null==p?"\n float "+r+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+i+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+f+".0, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":f===i&&null==p?"\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, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\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 * "+i+" + depth + "+Fo(n)+";\n vec2 uv = uvFromFlat("+h+", "+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],i=e[2]*o,a=e[1]*i,s=L(e),u=s.newShape,c=s.keptDims;if(u.length<e.length)return"\n "+So(Po(t,u))+"\n float "+r+"(int row, int col, int depth, int depth2) {\n return "+r+"("+Bo(["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("+a+", "+i+", "+o+", 1)));\n "+Mo(t)+"\n }\n ";var l=t.shapeInfo.flatOffset,h=t.shapeInfo.texShape,f=h[0],p=h[1];return p===a&&null==l?"\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("+i+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ":p===o&&null==l?"\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 ":"\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 * "+a+" + col * "+i+" +\n depth * "+o+" + depth2;\n vec2 uv = uvFromFlat("+f+", "+p+", index + "+Fo(n)+");\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],i=e[3]*o,a=e[2]*i,s=e[1]*a,u=L(e),c=u.newShape,l=u.keptDims;if(c.length<e.length)return"\n "+So(Po(t,c))+"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n return "+r+"("+Bo(["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+", "+a+", "+i+", "+o+")) +\n depth3;\n "+Mo(t)+"\n }\n ";var h=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,p=f[0],d=f[1];return d===s&&null==h?"\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("+a+", "+i+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":d===o&&null==h?"\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("+d+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\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 * "+a+" + depth * "+i+" +\n depth2 * "+o+" + depth3 + "+Fo(n)+";\n vec2 uv = uvFromFlat("+p+", "+d+", 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=L(e),i=o.newShape,a=o.keptDims;if(i.length<e.length)return"\n "+So(Po(t,i))+"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+r+"("+Bo(["row","col","depth","depth2","depth3","depth4"],a)+");\n }\n ";var s=e[5],u=e[4]*s,c=e[3]*u,l=e[2]*c,h=e[1]*l;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("+h+", "+l+", "+c+", "+u+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+s+", 1)));\n "+Mo(t)+"\n }\n ";var f=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,d=p[0],v=p[1];return v===h&&null==f?"\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("+l+", "+c+", "+u+", "+s+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ":v===s&&null==f?"\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("+v+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\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 * "+h+" + col * "+l+" + depth * "+c+" +\n depth2 * "+u+" + depth3 * "+s+" + depth4 + "+Fo(n)+";\n vec2 uv = uvFromFlat("+d+", "+v+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function ko(t){var e;switch(t.shapeInfo.logicalShape.length){case 0:return"\n vec4 "+("get"+(e=t.name).charAt(0).toUpperCase()+e.slice(1))+"() {\n return "+Co().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)],i=Co();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+o[0]+", "+o[1]+", index);\n return "+i.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,i=o[0],a=o[1],s=Co();if(null!=o&&A(e,o))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+i+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+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,i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0])return"\n "+ko(Po(t,e.slice(1)))+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+Bo(["b","row","col"],[1,2])+");\n }\n ";var a=i[0],s=i[1],u=Math.ceil(e[2]/2);return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+a+", "+s+", "+u*Math.ceil(e[1]/2)+", "+u+", b, row, col);\n return "+Co().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),i=t.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],s=a[0],u=a[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),h="int b, int row, int col",f="b * "+l+" + (row / 2) * "+c+" + (col / 2)",p=2;p<n-1;p++)h="int b"+p+", "+h,f="b"+p+" * "+(l*=e[n-p-1])+" + "+f;return"\n vec4 "+o+"("+h+") {\n int index = "+f+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+Co().texture2D+"("+r+", uv);\n }\n "}(t)}}var Do="\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",Ao="\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",To="\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",No="\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 Fo(t){return"offset"+t}function Mo(t){var e=t.name,n=D(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 Oo(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 Po(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function Bo(t,e){return e.map((function(e){return t[e]})).join(", ")}var Lo=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,I(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],i=Math.ceil(o/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),r||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,c=u.length,l=Oo(c),h=wo("coords",c);if(1===i){var f=Oo(s=c+1);a="\n "+f+" sourceLocR = "+f+"("+h.join()+", 0);\n ++"+h[c-1]+";\n "+f+" sourceLocG = "+f+"("+h.join()+", 0);\n ++"+h[c-2]+";\n "+f+" sourceLocA = "+f+"("+h.join()+", 0);\n --"+h[c-1]+";\n "+f+" sourceLocB = "+f+"("+h.join()+", 0);\n --"+h[c-2]+";"}else s=c,a="\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 p=["x","y","z","w","u","v"].slice(0,s),d="."+p[s-1],v=p.map((function(t){return"int "+t})),m=wo("sourceLocR",s-1).concat("inIdx.r"),g=wo("sourceLocG",s-1).concat("inIdx.g"),y=wo("sourceLocB",s-1).concat("inIdx.b"),x=wo("sourceLocA",s-1).concat("inIdx.a"),b="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+")));",C="vec4(\n getAChannel("+m.join()+"),\n hasNextCol ? getAChannel("+g.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",E=r?"":"\n float getBestIndicesAChannel("+v.join()+") {\n return getChannel(getBestIndicesA("+p.join()+"),\n vec2("+p.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+v.join()+") {\n return getChannel(getA("+p.join()+"),\n vec2("+p.slice(-2).join()+"));\n }\n "+E+"\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 "+a+"\n ivec4 srcIdx = ivec4(sourceLocR"+d+", sourceLocG"+d+",\n sourceLocB"+d+", sourceLocA"+d+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+b+"(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 "},Wo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=t.dilationHeight,a=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 += "+i+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+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 "},zo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,i=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,f=t.effectiveFilterWidth,p=l-1-t.padInfo.front,d=h-1-t.padInfo.top,v=f-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+p+", "+d+", "+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) / "+i+".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 < "+f+";\n wC += "+c+") {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Uo=function(t,e,n,r,o,i){this.outputShape=[],this.variableNames=["x","mean","variance"],Lr(t,e),Lr(t,n);var a="0.0";null!=r&&(Lr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Lr(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 = "+a+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+i+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Vo=function(t,e,n,r,o,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Lr(t,e),Lr(t,n);var a="vec4(0.0)";null!=r&&(Lr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Lr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+a+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+i+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},Go=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Lr(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 "},Ho="return a + b;",qo="return a - b;",jo="return a * b;",Ko="return (a < 0.) ? b * a : a;",Xo=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Lr(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 "},Yo="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",$o=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=Lr(e,n);var o=this.outputShape.length,i="";if(r)if(0===o||1===D(this.outputShape))i="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(i="\n "+Oo(o)+" coords = getOutputCoords();\n ",1===o)i+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var a=wo("coords",o);i+="\n bool nextRowOutOfBounds =\n ("+a[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+a[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 "+i+"\n\n setOutput(result);\n }\n "},Jo=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}(),Qo=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}(),Zo=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 "},ti=function(t){this.outputShape=[],this.outputShape=rn(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 i=e.length,a=e[e.length-1];r.push("else setOutput(getT"+i+"(yR, yC-"+a+"));"),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 "},ei=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=rn(t,e);var n=this.outputShape,r=n.length,o=Oo(r),i=wo("coords",r),a=["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=a[e],l=a.slice(-2),h=a.join(),f="if ("+c+" < "+s[0]+") {\n return getChannel(\n getT0("+h+"), vec2("+l.join()+"));\n }";for(u=1;u<s.length;u++){var p=s[u-1];f+="\n if ("+c+" < "+s[u]+" && "+c+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+ni(a,c,p)+"),\n vec2("+ni(l,c,p)+"));\n }"}var d=s.length,v=s[s.length-1];f+="\n return getChannel(\n getT"+d+"("+ni(a,c,v)+"),\n vec2("+ni(l,c,v)+"));",this.userCode="\n float getValue("+a.map((function(t){return"int "+t}))+") {\n "+f+"\n }\n\n void main() {\n "+o+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+i+"), 0., 0., 0.);\n\n "+i[r-1]+" = "+i[r-1]+" + 1;\n if ("+i[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+i+");\n }\n\n "+i[r-2]+" = "+i[r-2]+" + 1;\n if ("+i[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+i+");\n }\n\n "+i[r-1]+" = "+i[r-1]+" - 1;\n if ("+i[r-2]+" < "+n[r-2]+" &&\n "+i[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+i+");\n }\n setOutput(result);\n }\n "};function ni(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var ri=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,i="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 ("+i+") {\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 "},oi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i="channelsLast"===t.dataFormat,a=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=i?1:2,c=i?2:3,l=i?3:1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+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 ("+i+") {\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 "},ii=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,i=t.padInfo.top,a=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+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+" - "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},ai=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,i=t.strideHeight,a=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) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},si=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,i=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 * "+i+" + 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 "},ui=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+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 "},ci=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,i=t.padInfo.left,a=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),p=t.inChannels%4,d="channelsLast"===t.dataFormat,v=d?1:2,m=d?2:3,g=d?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("+a+", "+s+");\n const ivec2 pads = ivec2("+o+", "+i+");\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 < "+f+"; 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 ("+d+") {\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===p)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+f+") *\n getW(wR, wC, "+f+", d2);\n } else {\n dotProd +=\n getX(batch, "+f+", xR, xC) *\n getW(wR, wC, "+f+", d2);\n }\n\n } else if ("+(2===p)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===p)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2),\n getW(wR, wC, "+f+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1),\n getX(batch, xR, xC, "+f+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC),\n getX(batch, "+f+" + 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 "},li=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,i=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,h=t.filterHeight,f=t.filterWidth,p=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+i+", "+a+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+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 < "+f+"; 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 < "+p+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+p+") *\n getW(wF, wR, wC, "+p+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+p+"),\n getX(batch, xF, xR, xC, "+p+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+p+", d2),\n getW(wF, wR, wC, "+p+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+p+"),\n getX(batch, xF, xR, xC, "+p+" + 1),\n getX(batch, xF, xR, xC, "+p+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+p+", d2),\n getW(wF, wR, wC, "+p+" + 1, d2),\n getW(wF, wR, wC, "+p+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},hi=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,i=t.inWidth,a=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,p=t.filterWidth,d=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("+a+", "+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 / "+d+";\n int q = d2 - d1 * "+d+";\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 < "+f+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+o+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+h+";\n\n if (xC < 0 || xC >= "+i+") {\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 "},fi=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,i=t.inWidth,a=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,p=t.filterWidth,d=p,v="int xR; int xC; int xCOffset;",m=0;m<f;m++)for(var g=0;g<p;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<f;m++)for(var y=0;y<d;y++){if(v+="\n xR = xRCorner + "+m*l+";\n xC = xCCorner + "+(g=2*y)*h+";\n ",1===c){if(g<p&&(v+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+i+") {\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 >= "+i+") {\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 < "+i+") {\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 >= "+i+") {\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 < "+i+") {\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<p)){var x=s%2==0?E(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(v+="\n xCOffset = xC + "+s%2+" + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\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 < "+i+") {\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 + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\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<p&&(v+="\n if(xR >= 0 && xR < "+o+") {\n ",s%2==1?(v+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\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 < "+i+") {\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<p&&(v+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\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 < "+i+") {\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 < "+i+") {\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<p&&(v+="\n xR"+m+"C"+(g+1)+" = vec4(\n xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n ")),v+="}");g<p&&(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<p&&(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<f;m++)for(g=0;g<p;g++)v+="dotProd += xR"+m+"C"+g+" * wR"+m+"C"+g+";";var b="",w="";n&&(b=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",w="result = activation(result);");var C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+b+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+a+", "+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 "+C+"\n "+w+"\n setOutput(result);\n }\n "},pi=function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=t[0],a=t[1],s=t[2],u=t[3],c=e[0],l=n[0],h=n[1];this.outputShape=[c,l,h,u];var f="bilinear"===r?1:0,p=[a-1+".0",s-1+".0"],d=p[0],v=p[1],m=l>1?[""+(a-1)/(l-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],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 >= "+i+") {\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 > "+d+" ) {\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("+f+" == 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 "},di=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Oo(r)+" coords = getOutputCoords();\n int end = "+vi(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 "+i+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+vi(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 vi(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 mi=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Lt.DENSE;var e=jt(t),n=Co();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Eo(["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 "},gi=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Lt.DENSE;var e=jt(t),n=Co();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Eo(["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 "},yi=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}(),xi=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 "},bi=function(t){this.variableNames=["A"],this.outTexUsage=Wt.DOWNLOAD;var e=Co();this.outputShape=t,this.userCode="\n "+Io+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},wi=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Wt.DOWNLOAD;var e=Co();this.outputShape=t,this.userCode="\n "+Io+"\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 "},Ci=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=Co(),o=e[0],i=e[1];this.outputShape=t;var a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode="\n "+_o(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 / "+i+";\n int c = imod(flatIndex, "+i+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+i+".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("+a+", 0., 0., 0.);\n }\n "},Ei=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=Co(),o=e[0],i=e[1];this.outputShape=t;var a="",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;a+="\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 / "+i+";\n c = imod(flatIndex, "+i+");\n uv = (vec2(c, r) + halfCR) / vec2("+i+".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 "+_o(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 "+a+"\n\n "+r.output+" = "+s+";\n }\n "},_i=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,i=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) / "+i+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},Ii=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}(),Ri=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=Oo(this.rank),i=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=[],i=0;i<t.length;i++)i===e?o.push("int(getIndices("+r[i]+"))"):o.push(""+r[i]);return o.join()}(t,n);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n "},Si=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Oo(e.length),o=Oo(n.length),i=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 * "+i+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function ki(t,e){var n=Co();return Zt(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 Di(t,e){return se(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 Ai(t,e){return ue(t,e,new Uint16Array([0,1,2,2,1,3]))}function Ti(t,e,n,r,o,i,a){le(n,r);var s=ce(t,e),u=t.TEXTURE_2D;return Yt(t,e,(function(){return t.bindTexture(u,s)})),Yt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Yt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Yt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Yt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Yt(t,e,(function(){return t.texImage2D(u,0,o,n,r,0,i,a,null)})),Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function Ni(t,e,n,r,o){var i=qt(n,r);return Ti(t,e,i[0],i[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function Fi(t,e,n,r,o){var i=qt(n,r);return Ti(t,e,i[0],i[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Mi(t,e,n,r,o){var i=qt(n,r);return Ti(t,e,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Oi(t,e,n,r,o){var i=Kt(n,r);return Ti(t,e,i[0],i[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function Pi(t,e,n,r,o){var i=Kt(n,r);return Ti(t,e,i[0],i[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function Bi(t,e,n,r){return Yt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),fe(t,e,n,"clipSpacePos",r,3,20,0)&&fe(t,e,n,"uv",r,2,20,12)}function Li(t,e,n,r,o,i,a){var s,u,c;Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),i 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=a.internalFormatPackedFloat),s.set(i),Yt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)})),Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function Wi(t,e,n,r){Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Yt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Yt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Yt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function zi(t,e,n,r,o){var i=t.createBuffer();Yt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,i)}));var a=16*n*r;return Yt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,a,t.STREAM_READ)})),Yt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Yt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),i}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 Vi(t,e,n,r,o){var i=qt(n,r),a=i[0],s=i[1],u=new Uint8Array(n*r*4);return Yt(t,e,(function(){return t.readPixels(0,0,a,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function Gi(t,e,n,r,o,i,a,s){var u=t,c=new Float32Array(function(t,e){var n=Kt(t,e);return n[0]*n[1]*4}(i,a));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 Yt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)})),o}var qi=Object.freeze({createVertexShader:ki,createVertexBuffer:Di,createIndexBuffer:Ai,createFloat32MatrixTexture:Ni,createFloat16MatrixTexture:Fi,createUnsignedBytesMatrixTexture:Mi,createPackedMatrixTexture:Oi,createFloat16PackedMatrixTexture:Pi,bindVertexProgramAttributeStreams:Bi,uploadDenseMatrixToTexture:Li,uploadPixelDataToTexture:Wi,createBufferFromOutputTexture:zi,downloadFloat32MatrixFromBuffer:Ui,downloadByteEncodedFloatMatrixFromOutputTexture:Vi,downloadPackedMatrixFromBuffer:Gi,downloadMatrixFromPackedOutputTexture:Hi}),ji=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=f().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Gt(e,t)):this.gl=Ht(e);var n="WEBGL_color_buffer_float";if(1===f().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=Qt(this.gl,this.debug,"OES_texture_float"),Ne(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=Qt(this.gl,this.debug,"OES_texture_half_float");else if(f().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),Ne(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=Qt(this.gl,this.debug,"EXT_color_buffer_half_float");else if(f().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",Ne(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Ne(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=Di(this.gl,this.debug),this.indexBuffer=Ai(this.gl,this.debug),this.framebuffer=he(this.gl,this.debug),this.textureConfig=Xt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return f().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;Yt(e,this.debug,(function(){return e.finish()})),Yt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Yt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Yt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Yt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Yt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Ni(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Fi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Mi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Wi(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Li(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Pi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Oi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(ye(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Yt(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 Vi(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,i){return Gi(this.gl,t,0,0,0,o,i,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=zi(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(f().getBool("WEBGL_FENCE_API_ENABLED")){var o=t,i=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(i,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=i}else f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,f().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=te(e,this.debug,t),r=ki(e,this.debug),o=oe(e,this.debug);return Yt(e,this.debug,(function(){return e.attachShader(o,r)})),Yt(e,this.debug,(function(){return e.attachShader(o,n)})),ie(e,this.debug,o),this.debug&&ae(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Bi(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&&Yt(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&&ae(this.gl,this.debug,this.program),Yt(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?de(this.gl,this.debug,t,e):ve(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Yt(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(),me(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=Kt(e,n),o=r[0],i=r[1];this.setOutputMatrixTextureDriver(t,o,i)},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&&ae(this.gl,this.debug,this.program),xe(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Yt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Yt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Qt(this.gl,this.debug,2===f().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===f().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!==f().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 u(this,void 0,void 0,(function(){var e=this;return c(this,(function(n){switch(n.label){case 0:return[4,O((function(){return e.disposed||e.isQueryAvailable(t,f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,f().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}return o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),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&&t[e]();++e);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||O((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ge(this.gl,this.debug,t,this.framebuffer),this.debug&&xe(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ge(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&xe(this.gl)):ye(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;ge(r,this.debug,t,this.framebuffer),this.debug&&xe(r),this.outputTexture=t,Yt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Yt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Yt(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 Ki(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],i=o.shape;if(!A(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!t.isUniform||!o.isUniform){var a=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!A(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}}))}var Xi=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,i=n.strideWidth,a=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,h=n.dataFormat,f=s.left,p=s.top,d=o*r,v=Co(),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+")) * "+a+" - "+p+";\n d0 = offsetY + "+l+" * (pos / "+d+");\n\n if(d0 < "+e[g]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+f+".);\n d1 = offsetX + "+c+" * (int(mod(float(pos), "+d+".) / "+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 "},Yi=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var i,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.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 = -"+a+"; j <= "+a+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "},$i=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 "},Ji=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var i,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.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 - "+a+";\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 = - "+a+"; j <= "+a+"; 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 * "+i+";\n setOutput(result);\n }\n "},Qi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=o-1-t.padInfo.top,s=i-1-t.padInfo.left,u=o*i-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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 < "+i+"; 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 * "+i+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Zi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,h=u-1-t.padInfo.top,f=c-1-t.padInfo.left,p=s*u*c-1;this.userCode="\n const ivec3 pads = ivec3("+l+", "+h+", "+f+");\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 += "+i+") {\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 += "+a+") {\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 = "+p+" -\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 "},ta=function(t,e,n,r,o,i,a){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===i&&(i=null),void 0===a&&(a=!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"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],p="",d="";i&&(p=a?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+i+"\n }":"vec4 activation(vec4 x) {\n "+i+"\n }",d="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+p+"\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]+" * "+f[0]+");\n result += ("+h[1]+" * "+f[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+v+"\n\n "+d+"\n\n setOutput(result);\n }\n "},ea=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}(),na=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 "},ra=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=wo("rc",e),r=Oo(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),i=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),a=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 i=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),a=2;a<t;a++)i=e[e.length-1-a]+","+i;n.push(i)}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 "+i+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}},oa=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=Oo(r),i=e.map((function(t){return t[0]})).join(","),a=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+i+");\n "+o+" end = "+o+"("+a+");\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 = "+i+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},ia=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=Oo(r),i=e.map((function(t){return t[0]})).join(","),a=e.map((function(e,n){return e[0]+t[n]})).join(","),s=wo("rc",r),u=wo("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+") {"],f=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",p="",d=0,v=1===r?2:4;d<v;d++)p+="\n "+h[d]+"\n if ("+f+") {\n result["+d+"] = float("+n+");\n } else {\n "+o+" source = rc - start;\n result["+d+"] = getChannel(getX("+u.join()+"), "+l+");\n }\n ";p+=1===r?"} ":"}}",this.userCode="\n const "+o+" start = "+o+"("+i+");\n const "+o+" end = "+o+"("+a+");\n\n void main() {\n "+o+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+p+"\n setOutput(result);\n }\n "},aa=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,i=t.strideWidth,a=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var f="avg"===e,p="0.0";if(f||(p="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\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 += "+a+") {\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 d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n if ("+f+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+l+", "+h+");\n const float initializationValue = "+p+";\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("+p+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+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("+d+");\n }\n "}},sa=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,i=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,f=t.effectiveFilterWidth,p=t.padInfo.front,d=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+", "+i+", "+a+");\n const ivec3 pads = ivec3("+p+", "+d+", "+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 < "+f+";\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+" * "+f+" +\n wR * "+f+" + 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+", "+i+", "+a+");\n const ivec3 pads = ivec3("+p+", "+d+", "+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 "}},ua=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,i=Math.ceil(o/n);this.outputShape=[r,i];var a="0.0",s="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 1e-20",s="min"):"max"===e&&(a="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var 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 ",f="vec4";"all"===e?(a="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",f="bvec4"):"any"===e&&(a="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",f="bvec4");var p="";o%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+p+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+a+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+c+"; i += 4) {\n int inIdx = inOffset + i;\n "+f+" values = "+f+"(\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 "+f+" values = "+f+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(3===l)+") {\n "+f+" values = "+f+"(\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 "},ca=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 "+Eo(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+_o(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 "},la=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],i=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?o-1:o,n&&u>1?i-1:i],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],p=1/h,d=1/f,v=2*Math.ceil(p)+2,m=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+p+");\n const float invWidthScale = float("+d+");\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), "+(i-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 "},ha=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],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("+i+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},fa=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],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("+i+".0, "+a+".0,\n "+a+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},pa=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],i=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?o-1:o,n&&u>1?i-1:i],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],p=1/h,d=1/f,v=2*Math.ceil(p)+2,m=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+p+");\n const float invWidthScale = float("+d+");\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("+i+") - 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 "},da=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?a-1:a],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("+i+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+l+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},va=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=Oo(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 "},ma=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=wo("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],i=r[n-2]+" + 1 < "+this.outputShape[n-2],a=Oo(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 "+a+" 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("+i+") {\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 "},ga=function(t,e,n,r,o,i,a){void 0===a&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=Oo(o.length),u=Oo(i.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 f="getUpdates("+h+")",p=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 * "+p+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+f+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},ya=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,i=t.numSegments,a=i*Math.ceil(o/n);this.outputShape=[r,a];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 "+i+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+i+")));\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 "},xa=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 i=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u<e.length;u++)s.push(""+i[u]),u<t&&a.push(""+i[u]);r=a.join(),o=s.join()}var c=Oo(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 "},ba=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Oo(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return wa.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."+wa[e]+" = start["+e+"] + coords."+wa[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}(),wa=["x","y","z","w","u","v"],Ca=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Oo(this.rank),n=wo("coords",this.rank),r=wo("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",i="getChannel(getSource("+r.join()+"), "+o+")",a="\n result.x = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+i+";\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 = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+i+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map((function(t,e){return"start["+e+"]"})).join()+");":t.map((function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+"\n vec4 result = vec4(0.);\n "+a+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ea=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=Oo(n.length),i=Oo(n.length),a="";if(1===r)a="coords * strides + begin";else{var s=0;a=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 "+i+" coords = getOutputCoords();\n setOutput(getX("+a+"));\n }\n "},_a=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=Ia(e,n),i=Ra(t,o,n);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[i].shift();return this.usedTextures[i].push(a),a}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[i].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=Ra(e,Ia(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[o],a=i.indexOf(t);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(a,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));for(var e in this.usedTextures)this.usedTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Ia(t,e){if(t===Wt.UPLOAD)return zt.PACKED_2X2_FLOAT32;if(t===Wt.RENDER||null==t)return function(t){return f().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?zt.PACKED_2X2_FLOAT32:zt.UNPACKED_FLOAT32:t?zt.PACKED_2X2_FLOAT16:zt.UNPACKED_FLOAT16}(e);if(t===Wt.DOWNLOAD||t===Wt.PIXELS)return zt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Ra(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Sa=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=Oo(this.rank),i=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("+i+"));\n }\n "},ka=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=Oo(this.rank),i=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("+i+"));\n }\n "},Da=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=Oo(this.rank),i=bo("rc",this.rank),a=new Array(this.rank);for(r=0;r<e.length;r++)a[e[r]]=i[r];var s="vec2("+a.slice(-2).join()+")",u="++"+i[this.rank-1]+" < "+n[this.rank-1],c="getChannel(getA("+a.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 --"+i[this.rank-1]+";\n if(++"+i[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 "},Aa=1.7580993408473768,Ta=1.0507009873554805,Na=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 "},Fa="if (isnan(x)) return x;",Ma="return abs(x);",Oa=Fa+"\n return (x < 0.0) ? 0.0 : x;\n",Pa=Fa+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",Ba="return (x >= 0.0) ? x : (exp(x) - 1.0);",La="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+Aa+";\n float scale = "+Ta+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n",Wa="return -x;",za="return ceil(x);",Ua="return floor(x);",Va="return exp(x);",Ga="return exp(x) - 1.0;",Ha=Fa+"\n return sin(x);\n",qa=Fa+"\n return cos(x);\n",ja=Fa+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n",Ka=Fa+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n",Xa=Fa+"\n return atan(x);\n",Ya=Fa+"return log(x + sqrt(x * x + 1.0));",$a=Fa+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",Ja=Fa+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Qa="return x;",Za="\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",ts="\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",es="\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",ns=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 "},rs=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=wo("rc",e),r=Oo(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),i=n.slice(-2),a=e<=1?"rc":"vec2("+i.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+o+");\n\n setOutput(getChannel(packedInput, "+a+"));\n }\n "},os={};function is(t,e){if(void 0===e&&(e=!1),"linear"===t)return"return x;";if("relu"===t)return e?Za:Oa;if("elu"===t)return e?es:Ba;if("relu6"===t)return e?ts:Pa;if("prelu"===t)return e?Yo:Ko;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var as=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,!f().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var o=Ht(f().getNumber("WEBGL_VERSION"));r.binaryCache=((n=f().getNumber("WEBGL_VERSION"))in os||(os[n]={}),os[n]),r.gpgpu=new ji(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 _a(r.gpgpu),r.numMBBeforeWarning=null==f().global.screen?1024:f().global.screen.height*f().global.screen.width*window.devicePixelRatio*600/1024/1024,r.texData=new Fr(r,Ot),r}return s(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(f().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:Wt.UPLOAD}),r},e.prototype.move=function(t,e,n,r){if(f().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:Wt.UPLOAD})},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,i=e.slice,a=e.shape,s=e.isPacked;if(null!=i){var u;u=s?new ns(a,Qa):new Na(a,Qa);var c=this.runWebGLProgram(u,[{dataId:t,shape:a,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,f,p=null!=this.activeTimers;return p&&(h=ot()),f="complex64"===r?to(o.real.dataSync(),o.imag.dataSync()):this.getValuesFromTexture(t),p&&(this.downloadWaitMs+=ot()-h),this.convertAndCacheOnCPU(t,f)},e.prototype.read=function(t){return u(this,void 0,void 0,(function(){var e,n,r,o,i,a,s,u,l,h,p,d,v,m,g,y,x,b,w,C,E,_;return c(this,(function(c){switch(c.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,o=n.shape,i=n.slice,a=n.dtype,s=n.complexTensors,u=n.isPacked,null!=i)return void 0,l=u?new ns(o,Qa):new Na(o,Qa),h=this.runWebGLProgram(l,[{dataId:t,shape:o,dtype:a}],a),p=this.read(h.dataId),this.disposeData(h.dataId),[2,p];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!f().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===f().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return d=null,"complex64"!==a&&f().get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),m=this.texData.get(v.dataId),d=(_=this.gpgpu).createBufferFromTexture.apply(_,[m.texture].concat(jt(o)))),this.pendingRead.set(t,[]),"complex64"===a?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:c.sent(),c.label=2;case 2:return"complex64"!==a?[3,4]:[4,Promise.all([s.real.data(),s.imag.data()])];case 3:return y=c.sent(),x=y[0],b=y[1],g=to(x,b),[3,5];case 4:null==d?g=this.getValuesFromTexture(t):(w=D(o),g=this.gpgpu.downloadFloat32MatrixFromBuffer(d,w)),c.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(!$t(n)){if(f().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,i=n.isPacked,a=D(r);if(f().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var s=this.decode(t),u=this.texData.get(s.dataId),c=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[u.texture].concat(jt(r))).subarray(0,a);return this.disposeData(s.dataId),c}var l=f().getBool("WEBGL_PACK")&&!0===i,h=l?Ie(r):r,p=l?new wi(h):new bi(h),d=this.runWebGLProgram(p,[{shape:h,dtype:o,dataId:t}],"float32"),v=this.texData.get(d.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,a);return this.disposeData(d.dataId),m},e.prototype.time=function(t){return u(this,void 0,void 0,(function(){var e,n,r,o,i,a,s;return c(this,(function(u){switch(u.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(),o=k(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),i=k(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,r&&(this.programTimersStack=null),a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(o)]:[3,2];case 1:return s=u.sent(),a.kernelMs=_(s),a.getExtraProfileInfo=function(){return s.map((function(t,e){return{name:i[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:a.kernelMs={error:"WebGL query timers are not supported in this environment."},u.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,a]}}))}))},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:ot(),endMs:null}},e.prototype.endTimer=function(t){return f().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=ot(),t)},e.prototype.getQueryTime=function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return f().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,i=e.usage,a=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,i,a)));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 f().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Ot.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:Ot.keep(t.clone()),imag:Ot.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===D(n))return cn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=kr(t.shape,e,n);if(r||!o){var i=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ca(n):new ba(n),a=i.getCustomSetupFunc(e);return this.compileAndRun(i,[t],null,a)}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),i=this.texData.get(o.dataId);Object.assign(i,r),i.shape=n,i.dtype=t.dtype;var a=Dr(e,t.strides);r.slice&&(a+=r.slice.flatOffset),i.slice={flatOffset:a,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(i.slice.origDataId)||1;return this.dataRefCount.set(i.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=Ir(e,n,r);if(o.some((function(t){return 0===t})))return cn([],o);var i=new Ea(e,r,o);return this.compileAndRun(i,[t])},e.prototype.reverse=function(t,e){var n=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ma(t.shape,e):new va(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 sn(t)})),r=t.map((function(t){return un(t)}));return an(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>f().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),i=this.concat(t.slice(0,o),e),a=this.concat(t.slice(o),e);return this.concat([i,a],e)}if(f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var s=new ei(t.map((function(t){return t.shape})),e);return this.compileAndRun(s,t)}var u=rn(t.map((function(t){return t.shape})),e),c=t.map((function(t){return t.as2D(-1,D(t.shape.slice(e)))})),l=new ti(c.map((function(t){return t.shape})));return this.compileAndRun(l,c).reshape(u)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Wa,t.dtype);var e=new Na(t.shape,Wa);return this.compileAndRun(e,[t])},e.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],a=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===i)&&a>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===i?t:t.as3D(s,a,1),c=1===i?2:1,l=1===i?e.as3D(s,1,a):e;return this.multiply(u,l).sum(c,!0)}var h=St(t.dtype,e.dtype),f=new ta(t.shape,[s,o,i],n,r);return this.compileAndRun(f,[t,e],h)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,i=t.bias,a=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),f=null!=i,p=null!=s,d=a?is(a,!0):null,v=new ta(e.shape,[l,u,c],r,o,f,d,p),m=[e,n];return i&&m.push(i),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 Go("return areal * breal - aimag * bimag;",t.shape,e.shape),i=new Go("return areal * bimag + aimag * breal;",t.shape,e.shape),a=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],s=this.compileAndRun(o,a),u=this.compileAndRun(i,a),c=this.complex(s,u);return s.dispose(),u.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,jo,t.dtype);var l=new Xo(jo,t.shape,e.shape);return this.compileAndRun(l,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,i){var a=[t,e,n],s=null;null!=i&&(s=i.shape,a.push(i));var u=null;if(null!=o&&(u=o.shape,a.push(o)),f().getBool("WEBGL_PACK_NORMALIZATION")){var c=new Vo(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,a)}var l=new Uo(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,a)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){var i=f().getBool("WEBGL_PACK_NORMALIZATION")?new Ji(t.shape,e,n,r,o):new Yi(t.shape,e,n,r,o);return this.compileAndRun(i,[t])},e.prototype.LRNGrad=function(t,e,n,r,o,i,a){var s=new $i(e.shape,r,o,i,a);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 st(t)}));return po(zn(t.shape,t.dtype,n),e)}var r=new Sa(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ia(t.shape,e,n):new oa(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=f().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Da(t.shape,e):new ka(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 Ri(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){I(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=pr(t.shape,e,r),i=dr(o.length,e.length),a=vr(t.shape,e,r),s=mr(n,e.length),u=gr(a,n,e.length);return t.reshape(o).transpose(i).reshape(a).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){I(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 i=1+e.length;i<t.shape.length;++i)o.push([0,0]);var a=t.pad(o),s=pr(a.shape,e,r,!1),u=dr(s.length,e.length,!1),c=vr(a.shape,e,r,!1);return a.reshape(s).transpose(u).reshape(c)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],i=xr(o),a=new ua({windowSize:i,inSize:o,batchSize:r},e),s=this.compileAndRun(a,[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 i=xr(o),a=new xo({windowSize:i,inSize:o,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(a,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=xr(r[r.length-1]),i=new Lo(r,o,e,null==n),a=null==n?[t]:[t,n],s=this.compileAndRun(i,a,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){Qe("sum",e,t.rank);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o),a=kt(t.dtype);return this.reduce(i,"sum",a).reshape(r)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o),a=kt(t.dtype);return this.reduce(i,"prod",a).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=Ze([r],t.rank),i=t;null!=o&&(i=t.transpose(o),r=en(1,t.rank)[0]);var a=function(t,e,n){for(var r=[],o=t.length,i=0;i<o;i++)i!==e?r.push(t[i]):r.push(n);return r}(i.shape,r,n),s=D([i.shape[r]]),u=i.as2D(-1,s),c=kt(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(a);return null!=o&&(l=l.transpose(tn(o))),l},e.prototype.segOpCompute=function(t,e,n,r,o){var i=t.shape[0],a=t.shape[1],s=function(t,e){var n,r=!1;for(t<=30?(n=t,r=!0):n=Q(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=Q(t,n+1);return n}(a,o),u=new ya({windowSize:s,inSize:a,batchSize:i,numSegments:o},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===o?c:(n=xn(0,o).tile([a/s]),this.segOpCompute(c,e,n,r,o))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(Qe("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!f().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=$e(t.shape,r),i=o[0],a=D(o[1]),s=t.as2D(-1,a);return this.argReduce(s,n).reshape(i)}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 di(t.shape,n,r);return this.compileAndRun(o,[t])},e.prototype.equal=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Xo("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Xo("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(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Xo("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Xo("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(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Xo("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Xo("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new Na(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(f().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 Xo("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(f().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 Xo("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 xa(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],St(e.dtype,n.dtype))},e.prototype.where=function(t){Ge("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return mo(t.shape,e)},e.prototype.topk=function(t,e,n){return vo(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){Qe("min",e,t.rank);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("\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=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("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);Qe("max",e,t.rank);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("\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){Qe("all",e,t.rank);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(t,e){Qe("any",e,t.rank);var n=$e(t.shape,e),r=n[0],o=D(n[1]),i=t.as2D(-1,o);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.realDivide=function(t,e){if(f().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 Xo("\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(f().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 Xo("\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,Ho);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=St(t.dtype,e.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Ho,n);var r=new Xo(Ho,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new ns(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var i=new $o(n,t.shape,e.shape,o);return this.compileAndRun(i,[t,e],r)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),i=this.texData.get(e.dataId),a=[[o.complexTensors.real,i.complexTensors.real],[o.complexTensors.imag,i.complexTensors.imag]].map((function(o){var i=o[0],a=o[1],s=r.makeComplexComponentTensorInfo(t,i),u=r.makeComplexComponentTensorInfo(e,a),c=new Xo(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],St(i.dtype,a.dtype))})),s=a[0],u=a[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>f().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)})),i=t.map((function(t){return t.shape})),a=f().getBool("WEBGL_PACK")?new yo(t[0].shape,i):new go(t[0].shape,i);return this.compileAndRun(a,t,o)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,qo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=St(t.dtype,e.dtype);if(f().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,qo,t.dtype);var r=new Xo(qo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("\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(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,za,t.dtype);var e=new Na(t.shape,za);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ua,t.dtype);var e=new Na(t.shape,Ua);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new Na(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 Na(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new Na(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new Na(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new Na(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(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Va,t.dtype);var e=new Na(t.shape,Va);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ga,t.dtype);var e=new Na(t.shape,Ga);return this.compileAndRun(e,[t])},e.prototype.softmax=function(t,e){var n=B([e],t.shape),r=this.max(t,n),o=Je(r.shape,n),i=this.subtract(t,r.reshape(o)),a=this.exp(i),s=this.sum(a,n).reshape(o);return this.realDivide(a,s)},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(f().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 Na(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 Na(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Na(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 Na(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Na(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=f().getBool("WEBGL_PACK")?new ns(t.shape,Za):new Na(t.shape,Oa),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=f().getBool("WEBGL_PACK")?new ns(t.shape,ts):new Na(t.shape,Pa),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o(Yo,t.shape,e.shape):new Xo(Ko,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,es,t.dtype);var e=new Na(t.shape,Ba);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("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 Na(t.shape,La);return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Na(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,o=(r=f().getBool("WEBGL_PACK_CLIP")?new Qo(t.shape):new Jo(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(f().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ma,t.dtype);var e=new Na(t.shape,Ma);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Zo(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 Na(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Na(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 Na(t.shape,Ha);return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Na(t.shape,qa);return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Na(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Na(t.shape,ja);return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Na(t.shape,Ka);return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Na(t.shape,Xa);return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("\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 Xo("\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 Na(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 Na(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 Na(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 Na(t.shape,Ya);return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Na(t.shape,$a);return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Na(t.shape,Ja);return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Na(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 Na(t.shape,function(t){return void 0===t&&(t=0),Fa+"\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,i){var a=t.shape,s=this.texData.get(t.dataId),u=n.inChannels,c=a[0]*a[1]*a[2],l=n.outChannels,h="channelsLast"===n.dataFormat,p=(1===c||1===l)&&u>1e3,d=a[2]%2!=0&&!!s.isPacked;if(p||!f().getBool("WEBGL_LAZILY_UNPACK")||!f().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!d){var v=h?a[0]*a[1]*a[2]:a[0]*a[2]*a[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:i}),n.outShape)}var y=h?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),x={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},b=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,I(ke(s.shape,x.shape),(function(){return"packed reshape "+s.shape+" to "+x.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),C=this.fusedBatchMatMul({a:x,b:w,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:i}),E=this.texData.get(C.dataId);return I(E.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=b,E.shape=n.outShape,Ot.makeTensorFromDataId(C.dataId,n.outShape,C.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,o,i){var a=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,h="channelsLast"===n.dataFormat,f=a*s*u,p=l*c,d=[f,p],v=t.squeeze([0]),m=e.reshape([1,f,-1]),g=new Xi(d,v.shape,n),y=this.compileAndRun(g,[v]).reshape([1,d[0],d[1]]),x=null!=r,b=null!=i,w=o?is(o,!0):null,C=new ta(y.shape,[1,p,n.outChannels],!0,!1,x,w,b),E=[y,m];r&&E.push(r),b&&E.push(i);var _=this.compileAndRun(C,E);return h?_.reshape([1,l,c,n.outChannels]):_.reshape([1,n.outChannels,l,c])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,i=t.activation,a=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,i,a);if(f().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,i,a);var s=null!=o,u=null!=a,c=i?is(i,!1):null,l=new ci(r,s,c,u),h=[e,n];return o&&h.push(o),a&&h.push(a),this.compileAndRun(l,h)},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(f().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new ci(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new oi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new ri(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,i=t.bias,a=t.activation,s=t.preluActivationWeights,u=f().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,c=a?is(a,u):null,l=[n,r],h=null!=i,p=null!=s;return h&&l.push(i),p&&l.push(s),u?(e=new fi(o,h,c,p),this.compileAndRun(e,l)):(e=new hi(o,h,c,p),this.compileAndRun(e,l))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return f().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new fi(n),this.compileAndRun(r,[t,e])):(r=new hi(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new ui(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new si(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new li(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new ai(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new ii(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new aa(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new aa(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var o=new aa(r,"max",!0),i=this.compileAndRun(o,[e]),a=new Qi(r),s=this.compileAndRun(a,[t,i],e.dtype);return i.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new Wo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return Jr(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,i=0;i<t.rank;i++)i!==e&&(r[o++]=t.shape[i]);var a=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(i=0;i<u.length;i++)a[e]=i,u[i]=this.slice(t,a,s).reshape(r);return u},e.prototype.avgPool3d=function(t,e){var n=new sa(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new zo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new sa(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new sa(r,"max",!0),i=this.compileAndRun(o,[e]),a=new Zi(r),s=this.compileAndRun(a,[t,i],e.dtype);return i.dispose(),s},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!ke(t.shape,e)&&(null===n.texture||!ke(n.shape,e))){var r=this.packedReshape(t,e);return Ot.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Qr(t,e)},e.prototype.resizeBilinear=function(t,e,n,r){var o=f().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new fa(t.shape,e,n,r):new ha(t.shape,e,n,r);return this.compileAndRun(o,[t],"float32")},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new la(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new da(t.shape,e,n,r);return this.compileAndRun(o,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new pa(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var o=e?t:Tr(t),i=o.shape[0],a=o.shape[1],s=new ea(i,a,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],"int32",u)},e.prototype.oneHot=function(t,e,n,r){var o=new na(t.size,e,n,r);return this.compileAndRun(o,[t])},e.prototype.diag=function(t){var e=new xi(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return Ge("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),ao(t.dataSync(),e.dataSync(),n,r,o)},e.prototype.cropAndResize=function(t,e,n,r,o,i){var a=new pi(t.shape,e.shape,r,o,i);return this.compileAndRun(a,[t,e,n],"float32")},e.prototype.depthToSpace=function(t,e,n){I(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],i="NHWC"===n?t.shape[2]:t.shape[3],a="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=i*e,c=a/(e*e),l=new yi("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 fo(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=Cr(0,t,n),o=r.sliceRank,i=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/a,a],l=t.reshape([i,o]),h=e.reshape([i,a]);if(0===u)return Qr(cn([]),n);var f=hn(0),p=new ga(i,o,l.rank,h.rank,s,c);return this.compileAndRun(p,[h,l,f]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var o=Cr(0,t,n),i=o.sliceRank,a=o.numUpdates,s=o.strides,u=o.outputSize,c=new ga(a,i,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 _i("return real * expR - imag * expI;",t.shape,e),o=new _i("return real * expI + imag * expR;",t.shape,e),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],a=this.compileAndRun(r,i),s=this.compileAndRun(o,i),u=this.complex(a,s).as2D(t.shape[0],t.shape[1]);return a.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=yr(t,e),i=o[0],a=o[1],s=o[2],u=o[3],c=e.reshape([a,r]),l=t.reshape([t.size/s,s]),h=new Si(r,u,[a,s]);return this.compileAndRun(h,[l,c]).reshape(i)},e.prototype.fill=function(t,e,n){if("string"===(n=n||$(e))){var r=z(n,D(t));return r.fill(e),Ot.makeTensor(r,t,n,this)}var o=new Ii(t,e),i=o.getCustomSetupFunc(e);return this.compileAndRun(o,[],n,i)},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 Zr(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 Ot.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new rs(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new ra(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[Ee(t.shape)].concat(_e(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},o=[Ee(e)].concat(_e(e)),i=new ca(o,n),a=this.runWebGLProgram(i,[r],t.dtype,null,!0);return{dataId:a.dataId,shape:e,dtype:a.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,i=n.dtype,a=Ie(o);return e=r?new gi(a):new mi(a),{dtype:i,shape:o,dataId:this.runWebGLProgram(e,[{shape:a,dtype:i,dataId:t}],i,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,o){var i=this;void 0===o&&(o=!1);var a=this.makeTensorInfo(t.outputShape,n),s=this.texData.get(a.dataId);if(t.packedOutput&&(s.isPacked=!0),t.outPackingScheme===Lt.DENSE){var u=jt(t.outputShape);s.texShape=u.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(s.usage=t.outTexUsage),0===D(a.shape))return s.values=W(a.dtype,0),a;var c=[],l=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=i.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&D(e.shape)<=f().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?i.unpackTensor(e):i.packTensor(e),c.push(e),n=i.texData.get(e.dataId);else if(n.isPacked&&!ke(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=i.packedReshape(e,o),c.push(e),n=i.texData.get(e.dataId),r.shape=o}return i.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(a.dataId);var h,p={shape:a.shape,texData:s,isUniform:!1},d=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;return t.constructor.name+"_"+r+"_"+o}(t,l,p),v=this.getAndSaveBinary(d,(function(){return function(t,e,n,r){var o=e.userCode,i=n.map((function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}})),a=i.map((function(t){return t.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=Ro(i,s,o,e.packedInputs),c=t.createProgram(u),l=null,h=t.getUniformLocation(c,"NAN",!1);1===f().getNumber("WEBGL_VERSION")&&(l=t.getUniformLocation(c,"INFINITY",!1));for(var p={},d=0;d<e.variableNames.length;d++){var v=e.variableNames[d];p[v]=t.getUniformLocation(c,v,!1),p["offset"+v]=t.getUniformLocation(c,"offset"+v,!1)}return{program:e,source:u,webGLProgram:c,uniformLocations:p,inShapeInfos:a,outShapeInfo:s,infLoc:l,nanLoc:h}}(i.gpgpu,t,l,p)})),m=null!=this.activeTimers;if(m&&(h=this.startTimer()),function(t,e,n,r,o){Ki(e.inShapeInfos,n),Ki([e.outShapeInfo],[r]);var i=r.texData.texture,a=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(i,a[0],a[1]):t.setOutputMatrixTexture(i,a[0],a[1]),t.setProgram(e.webGLProgram),1===f().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],i=e.uniformLocations[o],a=e.uniformLocations["offset"+o];if(null!=i)if(n.isUniform)if(D(n.shape)<2)t.gl.uniform1f(i,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(i,s)}else null!=n.texData.slice&&null!=a&&t.gl.uniform1i(a,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,i,r)})),null!=o&&o(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,v,l,p,r),c.forEach((function(t){return i.disposeData(t.dataId)})),m&&(h=this.endTimer(h),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(h)})),!f().getBool("WEBGL_LAZILY_UNPACK")&&s.isPacked&&!1===o){var g=this.unpackTensor(a);return this.disposeData(a.dataId),g}return a},e.prototype.compileAndRun=function(t,e,n,r,o){void 0===o&&(o=!1),n=n||e[0].dtype;var i=this.runWebGLProgram(t,e,n,r,o);return Ot.makeTensorFromDataId(i.dataId,i.shape,i.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;this.disposed||(f().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=Ue((function(){if(!f().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=f().getBool("DEBUG");f().set("DEBUG",!1);var n=t.abs(hn(1e-8)).dataSync()[0];if(f().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,i=n.values,a=n.texture,s=n.usage,u=n.isPacked;if(null==a){var c,l=null!=this.activeTimers;l&&(c=ot());var h=n.texShape;if(null==h&&(h=Re(r,u),n.texShape=h),null!=i){var f=Ie(r),p=void 0,d=h[1],v=h[0],m=i instanceof Uint8Array;u?(d=(e=Kt(h[0],h[1]))[0],v=e[1],p=new Ei(f,[v,d],m)):p=new Ci(f,[v,d],m);var g=this.makeTensorInfo([v,d],o);this.texData.get(g.dataId).usage=m?Wt.PIXELS:Wt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,v,i);var y=this.runWebGLProgram(p,[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+=ot()-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]*q(e)},e}(Mr);Pt()&&Ot.registerBackend("webgl",(function(){return new as}),2);var ss=on({square_:function(t){var e=je(t,"x","square"),n=[e];return Ot.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}}),us="SquaredDifference",cs=on({squaredDifference_:function(t,e){var n,r=je(t,"a","squaredDifference"),o=je(e,"b","squaredDifference");n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape);var i={a:r,b:o},a=[r,o];return Ot.runKernelFunc((function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n}),i,(function(t,e){var n=e[0],r=e[1],o=hn(2);return{a:function(){return t.mul(n.sub(r).mul(o))},b:function(){return t.mul(r.sub(n).mul(o))}}}),us,{},a,[])}}),ls=on({abs_:function(t){var e=je(t,"x","abs");return"complex64"===e.dtype?Ot.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Ot.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")}}),hs=on({acos_:function(t){var e=je(t,"x","acos");return Ot.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(hn(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),fs=on({acosh_:function(t){var e=je(t,"x","acosh");return Ot.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=on({asin_:function(t){var e=je(t,"x","asin");return Ot.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(hn(1).sub(n.toFloat().square()).sqrt())}}}))}}),ds=on({asinh_:function(t){var e=je(t,"x","asinh");return Ot.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(hn(1).add(n.toFloat().square()).sqrt())}}}))}}),vs=on({atan_:function(t){var e=je(t,"x","atan");return Ot.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))}}}))}}),ms=on({atanh_:function(t){var e=je(t,"x","atanh");return Ot.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(hn(1).sub(n.toFloat().square()))}}}))}}),gs=on({ceil_:function(t){var e=je(t,"x","ceil");return Ot.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),ys=on({clipByValue_:function(t,e,n){var r=je(t,"x","clipByValue");I(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var o=[r],i={min:e,max:n};return Ot.runKernelFunc((function(t,o){var i=t.clip(r,e,n);return o([r]),i}),{x:r},(function(t,r){var o=r[0];return{x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),wn(t))}}}),"ClipByValue",i,o)}}),xs=on({cos_:function(t){var e=je(t,"x","cos"),n=[e];return Ot.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)}}),bs=on({cosh_:function(t){var e=je(t,"x","cosh");return Ot.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)}}}))}}),ws=on({erf_:function(t){var e=je(t,"x","erf");return I("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Ot.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)))}}}))}}),Cs=on({exp_:function(t){var e=je(t,"x","exp");return Ot.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])}}),Es=on({expm1_:function(t){var e=je(t,"x","expm1");return Ot.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())}}}))}}),_s=on({floor_:function(t){var e=je(t,"x","floor");return Ot.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Is=on({log_:function(t){var e=je(t,"x","log"),n=[e];return Ot.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)}}),Rs=on({log1p_:function(t){var e=je(t,"x","log1p");return Ot.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))}}}))}}),Ss=on({logSigmoid_:function(t){var e=je(t,"x","logSigmoid");return Ot.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())}}}))}}),ks=on({neg_:function(t){var e=je(t,"x","neg"),n=[e];return Ot.runKernelFunc((function(t){return t.neg(e)}),{x:e},(function(t){return{x:function(){return t.neg()}}}),"Neg",{},n)}}),Ds=on({reciprocal_:function(t){var e=je(t,"x","reciprocal");return Ot.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())}}}))}}),As=on({round_:function(t){var e=je(t,"x","round");return Ot.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Ts=on({rsqrt_:function(t){var e=je(t,"x","rsqrt"),n=[e];return Ot.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)}}),Ns=on({sigmoid_:function(t){var e=je(t,"x","sigmoid");return Ot.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(hn(1).sub(n)))}}}),"Sigmoid")}}),Fs=on({sign_:function(t){var e=je(t,"x","sign");return Ot.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Ms=on({isNaN_:function(t){var e=je(t,"x","isNaN");return Ot.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Os=on({isInf_:function(t){var e=je(t,"x","isInf");return Ot.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Ps=on({isFinite_:function(t){var e=je(t,"x","isFinite");return Ot.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return wn(t)}}}))}}),Bs=on({sin_:function(t){var e=je(t,"x","sin"),n=[e];return Ot.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)}}),Ls=on({sinh_:function(t){var e=je(t,"x","sinh");return Ot.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)}}}))}}),Ws=on({softplus_:function(t){var e=je(t,"x","softplus");return Ot.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())}}}))}}),zs=on({sqrt_:function(t){var e=je(t,"x","sqrt");return Ot.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))}}}))}}),Us=on({step_:function(t,e){void 0===e&&(e=0);var n=je(t,"x","step");return Ot.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return wn(t)}}}))}}),Vs=on({tan_:function(t){var e=je(t,"x","tan");return Ot.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())}}}))}}),Gs=on({tanh_:function(t){var e=je(t,"x","tanh");return Ot.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 hn(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}});function Hs(t,e,n,r,o,i){var a,s,u=je(t,"x","batchNorm"),c=je(e,"mean","batchNorm"),l=je(n,"variance","batchNorm");return null!=o&&(a=je(o,"scale","batchNorm")),null!=r&&(s=je(r,"offset","batchNorm")),I(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),I(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!=a&&I(2===a.rank||1===a.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."})),null!=s&&I(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),Ks(u,c,l,s,a,i)}function qs(t,e,n,r,o,i){var a,s,u=je(t,"x","batchNorm"),c=je(e,"mean","batchNorm"),l=je(n,"variance","batchNorm");return null!=o&&(a=je(o,"scale","batchNorm")),null!=r&&(s=je(r,"offset","batchNorm")),I(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),I(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!=a&&I(3===a.rank||1===a.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."})),null!=s&&I(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),Ks(u,c,l,s,a,i)}function js(t,e,n,r,o,i){var a,s,u=je(t,"x","batchNorm"),c=je(e,"mean","batchNorm"),l=je(n,"variance","batchNorm");return null!=o&&(a=je(o,"scale","batchNorm")),null!=r&&(s=je(r,"offset","batchNorm")),I(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),I(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),I(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!=a&&I(4===a.rank||1===a.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."})),null!=s&&I(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),Ks(u,c,l,s,a,i)}function Ks(t,e,n,r,o,i){null==i&&(i=.001);var a,s,u,c=je(t,"x","batchNorm"),l=je(e,"mean","batchNorm"),h=je(n,"variance","batchNorm");null!=o&&(a=je(o,"scale","batchNorm")),null!=r&&(s=je(r,"offset","batchNorm")),I(l.rank===h.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),I(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),I(null==a||l.rank===a.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 f=[c,l,h,a];return Ot.runKernelFunc((function(t,e){var n=t.batchNormalization(u,Xs(l),Xs(h),i,Xs(a),Xs(s));return e([c,l,h,a]),n}),{x:c,mean:l,variance:h,scale:a,offset:s},(function(t,e){var n=e,r=n[0],o=n[1],a=n[2],s=n[3],c=null==s?hn(1):s,l=Br(o.shape,u.shape),h=[];if(1===o.rank){for(var f=0;f<u.shape.length-1;++f)h.push(u.shape[f]);h.push(1)}var p=r.sub(o),d=t.mul(c),v=Ts(a.add(hn(i))),m=v.mul(v).mul(v).mul(hn(-.5));return{x:function(){return 1===o.rank?t.mul(lr(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(hn(-1)).mul(d);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},variance:function(){var t=m.mul(p).mul(d);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},scale:function(){var e=p.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:i},f).reshape(c.shape)}function Xs(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 Ys(){ze("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var $s=on({batchNormalization2d_:function(t,e,n,r,o,i){return void 0===r&&(r=.001),Ys(),Hs(t,e,n,i,o,r)}}),Js=on({batchNormalization3d_:function(t,e,n,r,o,i){return void 0===r&&(r=.001),Ys(),qs(t,e,n,i,o,r)}}),Qs=on({batchNormalization4d_:function(t,e,n,r,o,i){return void 0===r&&(r=.001),Ys(),js(t,e,n,i,o,r)}}),Zs=on({batchNormalization_:function(t,e,n,r,o,i){return void 0===r&&(r=.001),Ys(),Ks(t,e,n,i,o,r)}}),tu=on({batchNorm_:Ks}),eu=on({batchNorm2d_:Hs}),nu=on({batchNorm3d_:qs}),ru=on({batchNorm4d_:js}),ou=on({logicalAnd_:function(t,e){var n=je(t,"a","logicalAnd","bool"),r=je(e,"b","logicalAnd","bool");return Lr(n.shape,r.shape),Ot.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),iu=on({logicalNot_:function(t){var e=je(t,"x","logicalNot","bool");return Ot.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),au=on({logicalOr_:function(t,e){var n=je(t,"a","logicalOr","bool"),r=je(e,"b","logicalOr","bool");return Lr(n.shape,r.shape),Ot.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),su=on({logicalXor_:function(t,e){var n=je(t,"a","logicalXor","bool"),r=je(e,"b","logicalXor","bool");return Lr(n.shape,r.shape),au(t,e).logicalAnd(ou(t,e).logicalNot())}}),uu=on({where_:function(t,e,n){var r=je(e,"a","where"),o=je(n,"b","where"),i=je(t,"condition","where","bool");return R(r.shape,o.shape,"Error in where: "),1===i.rank?I(i.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):R(i.shape,o.shape,"Error in where: "),Ot.runKernelFunc((function(t,e){var n=t.select(i,r,o);return e([i]),n}),{$condition:i,$a:r,$b:o},(function(t,e){var n=e[0];return{$condition:function(){return wn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),cu=function(t){return u(this,void 0,void 0,(function(){var e,n,r;return c(this,(function(o){switch(o.label){case 0:return[4,(e=je(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=mo(e.shape,n),t!==e&&e.dispose(),[2,r]}}))}))},lu=on({add_:function(t,e){var n,r=je(t,"a","add"),o=je(e,"b","add");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.runKernelFunc((function(t){return t.add(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Br(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Br(o.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}}),"Add")}}),hu=on({addN_:function(t){I(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),I(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 je(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(!A(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Ot.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")}}),fu=on({addStrict_:function(t,e){var n=je(t,"a","addStrict"),r=je(e,"b","addStrict");return R(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),pu=on({atan2_:function(t,e){var n,r=je(t,"a","atan2"),o=je(e,"b","atan2");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.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=lu(n.square(),r.square()),o=t.mul(r.div(e)),a=Br(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},$b:function(){var e=lu(n.square(),r.square()),o=ks(t.mul(n.div(e))),a=Br(r.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(r.shape)}}}))}}),du=on({div_:function(t,e){var n,r=je(t,"a","div"),o=je(e,"b","div");if(n=Dt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return gu(r,o);var i=Lr(r.shape,o.shape);return Ot.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=Br(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Br(r.shape,i);o.length>0&&(e=e.sum(o).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}}),"Div")}}),vu=on({divNoNan_:function(t,e){var n,r=je(t,"a","div"),o=je(e,"b","div");r=(n=Dt(r,o))[0],o=n[1];var i=du(r,o),a=wn(i),s=o.equal(a);return uu(s,a,i)}}),mu=on({divStrict_:function(t,e){var n=je(t,"a","div"),r=je(e,"b","div");return R(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),gu=on({floorDiv_:function(t,e){var n,r=je(t,"a","floorDiv"),o=je(e,"b","floorDiv");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.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=Br(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Br(r.shape,i);o.length>0&&(e=e.sum(o).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}}),"FloorDiv")}}),yu=on({maximum_:function(t,e){var n,r=je(t,"a","maximum"),o=je(e,"b","maximum");return n=Dt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Lr(r.shape,o.shape),Ot.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")}}),xu=on({maximumStrict_:function(t,e){var n=je(t,"a","maximumStrict"),r=je(e,"b","maximumStrict");return R(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),bu=on({minimum_:function(t,e){var n,r=je(t,"a","minimum"),o=je(e,"b","minimum");return n=Dt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Lr(r.shape,o.shape),Ot.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")}}),wu=on({minimumStrict_:function(t,e){var n=je(t,"a","minimumStrict"),r=je(e,"b","minimumStrict");return R(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Cu=on({mod_:function(t,e){var n,r=je(t,"a","mod"),o=je(e,"b","mod");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.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=Br(n.shape,i);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Br(r.shape,i);return o.length>0?e.sum(o).reshape(r.shape):e}}}))}}),Eu=on({modStrict_:function(t,e){var n=je(t,"a","modStrict"),r=je(e,"b","modStrict");return R(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),_u=on({mul_:function(t,e){var n,r=je(t,"a","mul"),o=je(e,"b","mul");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.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=Br(n.shape,i);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Br(r.shape,i);return o.length>0?e.sum(o).reshape(r.shape):e}}}),"Mul")}}),Iu=on({mulStrict_:function(t,e){var n=je(t,"a","mul"),r=je(e,"b","mul");return R(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Ru=on({pow_:function(t,e){var n,r=je(t,"base","pow"),o=je(e,"exp","pow");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape),a=[r,o];return Ot.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(hn(1))))),a=Br(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},b:function(){var e=n.greater(0),a=n.log().where(e,wn(n)),s=t.mul(o.mul(a)),u=Br(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},a,[!0])}}),Su=on({powStrict_:function(t,e){return R(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),ku=on({squaredDifferenceStrict_:function(t,e){var n=je(t,"a","squaredDifferenceStrict"),r=je(e,"b","squaredDifferenceStrict");return R(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Du=on({sub_:function(t,e){var n,r=je(t,"a","sub"),o=je(e,"b","sub");n=Dt(r,o),r=n[0],o=n[1];var i=Lr(r.shape,o.shape);return Ot.runKernelFunc((function(t){return t.subtract(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Br(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Br(o.shape,i);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}}),"Sub")}}),Au=on({subStrict_:function(t,e){var n=je(t,"a","subStrict"),r=je(e,"b","subStrict");return R(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),Tu=on({equal_:function(t,e){var n,r=je(t,"a","equal"),o=je(e,"b","equal");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.runKernelFunc((function(t){return t.equal(r,o)}),{$a:r,$b:o})}}),Nu=on({equalStrict_:function(t,e){var n=je(t,"a","equalStrict"),r=je(e,"b","equalStrict");return R(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),Fu=on({greater_:function(t,e){var n,r=je(t,"a","greater"),o=je(e,"b","greater");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.runKernelFunc((function(t){return t.greater(r,o)}),{a:r,b:o},null,"Greater")}}),Mu=on({greaterEqual_:function(t,e){var n,r=je(t,"a","greaterEqual"),o=je(e,"b","greaterEqual");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.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 wn(n)},b:function(){return wn(r)}}}),"GreaterEqual")}}),Ou=on({greaterEqualStrict_:function(t,e){var n=je(t,"a","greaterEqualStrict"),r=je(e,"b","greaterEqualStrict");return R(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),Pu=on({greaterStrict_:function(t,e){var n=je(t,"a","greaterStrict"),r=je(e,"b","greaterStrict");return R(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),Bu=on({less_:function(t,e){var n,r=je(t,"a","less"),o=je(e,"b","less");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.runKernelFunc((function(t){return t.less(r,o)}),{a:r,b:o},null,"Less")}}),Lu=on({lessEqual_:function(t,e){var n,r=je(t,"a","lessEqual"),o=je(e,"b","lessEqual");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.runKernelFunc((function(t,e){var n=t.lessEqual(r,o);return e([r,o]),n}),{a:r,b:o},null,"LessEqual")}}),Wu=on({lessEqualStrict_:function(t,e){var n=je(t,"a","lessEqualStrict"),r=je(e,"b","lessEqualStrict");return R(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),zu=on({lessStrict_:function(t,e){var n=je(t,"a","lessStrict"),r=je(e,"b","lessStrict");return R(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Uu=on({notEqual_:function(t,e){var n,r=je(t,"a","notEqual"),o=je(e,"b","notEqual");return n=Dt(r,o),r=n[0],o=n[1],Lr(r.shape,o.shape),Ot.runKernelFunc((function(t){return t.notEqual(r,o)}),{a:r,b:o},null,"NotEqual")}}),Vu=on({notEqualStrict_:function(t,e){var n=je(t,"a","notEqualStrict"),r=je(e,"b","notEqualStrict");return R(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Gu(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Hu(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 qu=on({gather_:function(t,e,n){void 0===n&&(n=0);var r=je(t,"x","gather"),o=je(e,"indices","gather","int32");n=B(n,r.shape)[0];var i=function(t,e,n){for(var r=t.shape[n],o=[],i=1,a=1,s=0;s<n;s++)o.push(t.shape[s]),i*=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]),a*=t.shape[s];return{batchSize:i,sliceSize:a,dimSize:r,outputShape:o}}(r,o,n);return Ot.runKernelFunc((function(t,e){var i=t.gather(r,o.flatten(),n);return e([o]),i}),{x:r,indices:o},(function(t,e){var o=e[0];return{x:function(){var e=r.shape,i=o.size,a=e.slice(0,n),s=a.length,u=e.slice(n,e.length).slice(1),c=u.length,l=Gu(0,s),h=Gu(s+1,s+1+c),f=Hu([a,[i],u]),p=t.reshape(f),d=o.reshape([i]),v=Hu([[s],l,h]),m=p.transpose(v),g=ju(m,d,r.shape[n]),y=tn(v);return g.transpose(y)},indices:function(){return o}}}),"Gather",{axis:n}).reshape(i.outputShape)}}),ju=on({unsortedSegmentSum_:function(t,e,n){var r=je(t,"x","unsortedSegmentSum"),o=je(e,"segmentIds","unsortedSegmentSum","int32");return I(T(n),(function(){return"numSegments must be of dtype int"})),Ot.runKernelFunc((function(t,e){var i=t.unsortedSegmentSum(r,o,n);return e([o]),i}),{$x:r},(function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=yu(e,wn(e)),r=qu(t,n),o=Mu(e,hn(0,"int32")),i=r.rank-o.rank,a=0;a<i;++a)o=Kn(o,a+1);o=ou(o,mn(r.shape,"bool"));var s=wn(r);return uu(o,r,s)}(t,n)}}}))}});function Ku(t,e,n,r,o,i,a){void 0===i&&(i="NHWC"),I(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]]),I(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),I(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),I(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var l="NHWC"===i?s[3]:s[1],h="NHWC"===i?u.shape[3]:u.shape[1];I(l===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."})),I(h===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."})),null!=a&&I(T(o),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var f=$r(i),p=Ur(s,n.shape,r,1,o,a,!1,f),d=Ot.runKernelFunc((function(t,e){var r=t.conv2dDerInput(u,n,p);return e([n,u]),r}),{dy4D:u,filter:n},(function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return Ju(t,n,r,o,i,1,a)},filter:function(){return Zu(t,s,n.shape,r,o,i,a)}}}));return c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function Xu(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 Yu(t,e,n,r,o){I(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var i=t,a=e,s=!1;4===e.rank&&(s=!0,a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),i=[1,t[0],t[1],t[2],t[3]]);var u=i[4],c=a.shape[4];I(5===i.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+i.length+"."})),I(5===a.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+a.rank})),I(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),I(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),I(c===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."}));var l=Vr(i,n.shape,r,1,o),h=Ot.runKernelFunc((function(t){return t.conv3dDerInput(a,n,l)}),{dy5D:a});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var $u=on({conv1d_:function(t,e,n,r,o,i,a){void 0===o&&(o="NWC"),void 0===i&&(i=1);var s=je(t,"x","conv1d"),u=je(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),I(3===c.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."})),I(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=a&&I(T(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."})),I(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]+"."})),I(Yr(n,i),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"})),I("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]),f=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),p=Ju(f,h,[1,n],r,"NHWC",[1,i],a);return l?p.as2D(p.shape[2],p.shape[3]):p.as3D(p.shape[0],p.shape[2],p.shape[3])}}),Ju=on({conv2d_:function(t,e,n,r,o,i,a){void 0===o&&(o="NHWC"),void 0===i&&(i=[1,1]);var s=je(t,"x","conv2d"),u=je(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])),I(4===c.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."})),I(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=a&&I(T(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var h="NHWC"===o?c.shape[3]:c.shape[1];I(h===u.shape[2],(function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."})),I(Yr(n,i),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}));var f=$r(o),p=Ur(c.shape,u.shape,n,i,r,a,!1,f),d=[u,c],v=Ot.runKernelFunc((function(t,e){var n=t.conv2d(c,u,p);return e([u,c]),n}),{x:c,filter:u},(function(t,e){var a=e,s=a[0],u=a[1];return I(Xr(i),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+i+"'"})),{x:function(){return tc(u.shape,t,s,n,r,o)},filter:function(){return Zu(u,t,s.shape,n,r,o)}}}),"Conv2D",p,d);return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Qu=on({conv3d_:function(t,e,n,r,o,i){void 0===o&&(o="NDHWC"),void 0===i&&(i=[1,1,1]);var a=je(t,"x","conv3d"),s=je(e,"filter","conv3d"),u=a,c=!1;4===a.rank&&(c=!0,u=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3])),I(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),I(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),I(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]+"."})),I(function(t,e){return Xu(t)||Xu(e)}(n,i),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),I("NDHWC"===o,(function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."}));var l=Vr(u.shape,s.shape,n,i,r),h=Ot.runKernelFunc((function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){I(Xu(i),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+i+"'"}));var o=e[0],a=e[1];return{x:function(){return Yu(o.shape,t,a,n,r)},$filter:function(){return function(t,e,n,r,o){var i=t;4===t.rank&&(i=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var a=e;4===a.rank&&(a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),I(5===i.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+i.shape+"."})),I(5===a.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+a.shape+"."})),I(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),I(i.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+i.shape[4]+") must match input depth in filter ("+n[3]+"."})),I(a.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+a.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=Vr(i.shape,n,r,1,o);return Ot.runKernelFunc((function(t){return t.conv3dDerFilter(i,a,s)}),{x5D:i,dy5D:a})}(o,t,a.shape,n,r)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Zu=on({conv2dDerFilter_:function(t,e,n,r,o,i,a){void 0===i&&(i="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])),I(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),I(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),I(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var c="NHWC"===i?s.shape[3]:s.shape[1],l="NHWC"===i?u.shape[3]:u.shape[1];I(c===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."})),I(l===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."})),null!=a&&I(T(o),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var h=$r(i),f=Ur(s.shape,n,r,1,o,a,!1,h);return Ot.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,f)}),{x4D:s,dy4D:u})}}),tc=on({conv2dDerInput_:Ku}),ec=on({depthwiseConv2d_:function(t,e,n,r,o,i,a){void 0===o&&(o="NHWC"),void 0===i&&(i=[1,1]);var s=je(t,"x","depthwiseConv2d"),u=je(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])),I(4===c.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."})),I(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),I(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==i&&(i=[1,1]),I(Yr(n,i),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=a&&I(T(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var h=Ur(c.shape,u.shape,n,i,r,a,!0),f=[c,u],p=Ot.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(c,u,h);return e([c,u]),n}),{x:c,filter:u},(function(t,e){I(Xr(i),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"}));var n=e[0],r=e[1];return{x:function(){return nc(n.shape,t,r,h)},filter:function(){return rc(n,t,r.shape,h)}}}),"DepthwiseConv2dNative",h,f);return l?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),nc=on({depthwiseConv2dDerInput_:function(t,e,n,r){var o=e,i=!1;3===e.rank&&(i=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var a=Ot.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(o,n,r)}),{dy4D:o});return i?a.as3D(a.shape[1],a.shape[2],a.shape[3]):a}}),rc=on({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 i=e;return 3===i.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Ot.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(o,i,r)}),{x4D:o,dy4D:i})}}),oc=on({separableConv2d_:function(t,e,n,r,o,i,a){void 0===i&&(i=[1,1]),void 0===a&&(a="NHWC");var s=je(t,"x","separableConv2d"),u=je(e,"depthwiseFilter","separableConv2d"),c=je(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"===a)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");I(4===l.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."})),I(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),I(4===c.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),I(1===c.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."})),I(1===c.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."}));var f=u.shape[2],p=u.shape[3];I(c.shape[2]===f*p,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+f*p+", but got "+c.shape[2]+"."}));var d=ec(l,u,r,o,a,i),v=Ju(d,c,1,"valid",a);return h?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),ic=on({conv2dTranspose_:function(t,e,n,r,o,i){return Ku(n,je(t,"x","conv2dTranspose"),je(e,"filter","conv2dTranspose"),r,o,"NHWC",i)}}),ac=on({conv3dTranspose_:function(t,e,n,r,o){return Yu(n,je(t,"x","conv3dTranspose"),je(e,"filter","conv3dTranspose"),r,o)}}),sc=on({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var i=je(t,"a","matMul"),a=je(e,"b","matMul");o=Dt(i,a),i=o[0],a=o[1];var s=n?i.shape[i.rank-2]:i.shape[i.rank-1],u=r?a.shape[a.rank-1]:a.shape[a.rank-2],c=n?i.shape[i.rank-1]:i.shape[i.rank-2],l=r?a.shape[a.rank-2]:a.shape[a.rank-1],h=i.shape.slice(0,-2),f=a.shape.slice(0,-2),p=D(h),d=D(f);I(i.rank>=2&&a.rank>=2&&i.rank===a.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+i.rank+" and "+a.rank+"."})),I(A(h,f),(function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+i.shape+" and "+a.shape+" must match."})),I(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+i.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var v=i.shape.slice(0,-2).concat([c,l]),m=n?i.as3D(p,s,c):i.as3D(p,c,s),g=r?a.as3D(d,l,u):a.as3D(d,u,l),y={transposeA:n,transposeB:r};return Ot.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,i=o[0],a=o[1];return n||r?!n&&r?{a:function(){return t.matMul(a,!1,!1)},b:function(){return t.matMul(i,!0,!1)}}:n&&!r?{a:function(){return a.matMul(t,!1,!0)},b:function(){return i.matMul(t,!1,!1)}}:{a:function(){return a.matMul(t,!0,!0)},b:function(){return t.matMul(i,!0,!0)}}:{a:function(){return t.matMul(a,!1,!0)},b:function(){return i.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(v)}}),uc=on({dot_:function(t,e){var n=je(t,"t1","dot"),r=je(e,"t2","dot");I(!(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],i=1===r.rank?r.size:r.shape[0];return I(o===i,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+i+"."})),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]))}}),cc=on({outerProduct_:function(t,e){var n=je(t,"v1","outerProduct"),r=je(e,"v2","outerProduct");return I(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))}}),lc=on({reverse_:function(t,e){var n=je(t,"x","reverse");if(0===n.rank)return n.clone();var r=B(e,n.shape);return Ot.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),hc=on({reverse1d_:function(t){var e=je(t,"x","reverse");return I(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),lc(e,0)}}),fc=on({reverse2d_:function(t,e){var n=je(t,"x","reverse");return I(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),lc(n,e)}}),pc=on({reverse3d_:function(t,e){var n=je(t,"x","reverse");return I(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),lc(n,e)}}),dc=on({reverse4d_:function(t,e){var n=je(t,"x","reverse");return I(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),lc(n,e)}});function vc(t,e,n,r,o,i){var a=je(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),I(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),I(Yr(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=i&&I(T(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var c=Wr(s.shape,e,n,r,o,i);if(1===c.filterWidth&&1===c.filterHeight&&A(c.inShape,c.outShape))return a.clone();var l=[s],h=Ot.runKernelFunc((function(t,e){var n=t.maxPool(s,c);return e([s,n]),n}),{x:s},(function(t,i){var a=i[0],s=i[1];return{x:function(){return function(t,e,n,r,o,i,a,s){var u=je(t,"dy","maxPoolBackprop"),c=je(e,"input","maxPoolBackprop"),l=je(n,"output","maxPoolBackprop");I(c.rank===u.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"})),null==i&&(i=[1,1]),I(Yr(o,i),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"})),I(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),I(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."}));var h=Wr(c.shape,r,o,i,a,s);return Ot.runKernelFunc((function(t){return t.maxPoolBackprop(u,c,l,h)}),{$dy:u,$input:c})}(t,a,s,e,n,r,o)}}}),"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function mc(t,e,n,r,o,i){var a=je(t,"x","avgPool","float32");null==r&&(r=[1,1]),I(Yr(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),I(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=i&&I(T(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var c=Wr(s.shape,e,n,r,o,i);if(1===c.filterWidth&&1===c.filterHeight&&A(c.inShape,c.outShape))return a.clone();var l=Ot.runKernelFunc((function(t){return t.avgPool(s,c)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,o,i){var a=je(t,"dy","avgPoolBackprop"),s=je(e,"input","avgPoolBackprop");I(s.rank===a.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"})),null==o&&(o=[1,1]),I(Yr(r,o),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}));var u=s,c=a,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),I(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),I(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var h=Wr(u.shape,n,r,o,i),f=Ot.runKernelFunc((function(t){return t.avgPoolBackprop(c,u,h)}),{dy4D:c,input4D:u});return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(t,s,e,n,r,o)}}}),"AvgPool",c);return l=l.cast(a.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var gc=on({maxPool_:function(t,e,n,r,o){return vc(t,e,n,1,r,o)}}),yc=on({avgPool_:function(t,e,n,r,o){return mc(t,e,n,1,r,o)}}),xc=on({pool_:function(t,e,n,r,o,i){null==o&&(o=[1,1]),null==i&&(i=1),0===r&&(r="valid");var a=je(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),I(Yr(i,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"}));var c,l=Wr(s.shape,e,i,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 f=1===h[0]&&1===h[1],p=function(t,e,n){var r=n.map((function(t){return t[0]})),o=n.map((function(t){return t[1]})),i=t.concat(r,o),a=e.map((function(t,e){return(t-i[e]%t)%t})),s=o.map((function(t,e){return t+a[e]}));return[e.map((function(t,e){return[r[e],s[e]]})),e.map((function(t,e){return[0,a[e]]}))]}([l.inHeight,l.inWidth],h,c),d=p[0],v=p[1],m=f?r:"valid",g=f?s:sr(s,h,d),y=("avg"===n?function(){return mc(g,e,i,1,m)}:function(){return vc(g,e,i,1,m)})(),x=f?y:Un(y,h,v);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),bc=on({maxPool3d_:function(t,e,n,r,o,i,a){void 0===i&&(i="NDHWC");var s=je(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==a&&(a=[1,1,1]),I(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(Yr(n,a),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=o&&I(T(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=zr(u.shape,e,n,a,r,o,i),h=Ot.runKernelFunc((function(t,e){var n=t.maxPool3d(u,l);return e([u,n]),n}),{x:u},(function(t,i){var s=i[0],u=i[1];return{x:function(){return function(t,e,n,r,o,i,a,s){var u=je(t,"dy","maxPool3dBackprop"),c=je(e,"input","maxPool3dBackprop"),l=je(n,"output","maxPool3dBackprop"),h=u,f=c,p=l,d=!1;4===c.rank&&(d=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),p=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3])),I(5===h.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."})),I(5===f.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."})),I(5===p.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+p.rank+"."})),null==i&&(i=[1,1,1]),I(Yr(o,i),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"})),null!=s&&I(T(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."}));var v=zr(f.shape,r,o,i,a,s),m=Ot.runKernelFunc((function(t){return t.maxPool3dBackprop(h,f,p,v)}),{dy5D:h,input5D:f});return d?m.as4D(m.shape[1],m.shape[2],m.shape[3],m.shape[4]):m}(t,s,u,e,n,a,r,o)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),wc=on({avgPool3d_:function(t,e,n,r,o,i,a){void 0===i&&(i="NDHWC");var s=je(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==a&&(a=[1,1,1]),I(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(Yr(n,a),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=o&&I(T(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=zr(u.shape,e,n,a,r,o,i),h=Ot.runKernelFunc((function(t){return t.avgPool3d(u,l)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,o,i,a){var s=je(t,"dy","avgPool3dBackprop"),u=je(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])),I(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),I(5===l.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."})),null==o&&(o=[1,1,1]),I(Yr(r,o),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"})),null!=a&&I(T(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."}));var f=zr(l.shape,n,r,o,i,a),p=Ot.runKernelFunc((function(t){return t.avgPool3dBackprop(c,l,f)}),{dy5D:c,input5D:l});return h?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}(t,u,e,n,a,r,o)}}}));return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Cc=on({slice_:function(t,e,n){var r,o,i=je(t,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(i.rank-1).fill(0)):e.length<i.rank?e.concat(new Array(i.rank-e.length).fill(0)):e.slice()).forEach((function(t){I(-1!==t,(function(){return"slice() does not support negative begin indexing."}))})),o=(o=null==n?new Array(i.rank).fill(-1):"number"==typeof n?[n].concat(new Array(i.rank-1).fill(-1)):n.length<i.rank?n.concat(new Array(i.rank-n.length).fill(-1)):n).map((function(t,e){return t>=0?t:(I(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),i.shape[e]-r[e])})),Er(i,r,o);var a=i.shape,s={begin:r,size:o};return Ot.runKernelFunc((function(t){return t.slice(i,r,o)}),{x:i},(function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],a[n]-r[n]-o[n]]);return{x:function(){return t.pad(e)}}}),"Slice",s)}}),Ec=on({slice1d_:function(t,e,n){var r=je(t,"x","slice1d");return I(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),Cc(r,[e],[n])}}),_c=on({slice2d_:function(t,e,n){var r=je(t,"x","slice2d");return I(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),Cc(r,e,n)}}),Ic=on({slice3d_:function(t,e,n){var r=je(t,"x","slice3d");return I(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),Cc(r,e,n)}}),Rc=on({slice4d_:function(t,e,n){var r=je(t,"x","slice4d");return I(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),Cc(r,e,n)}});function Sc(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(Je(e.shape,r))),t.rank<n.rank&&(t=t.reshape(Je(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}var kc=on({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","all","bool"),o=B(e,r.shape),i=o,a=Ze(i,r.rank);null!=a&&(r=r.transpose(a),i=en(i.length,r.rank));var s=Ot.runKernelFunc((function(t){return t.all(r,i)}),{$x:r});if(n){var u=Je(s.shape,o);return s.reshape(u)}return s}}),Dc=on({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","any","bool"),o=B(e,r.shape),i=o,a=Ze(i,r.rank);null!=a&&(r=r.transpose(a),i=en(i.length,r.rank));var s=Ot.runKernelFunc((function(t){return t.any(r,i)}),{$x:r});if(n){var u=Je(s.shape,o);return s.reshape(u)}return s}}),Ac=on({argMax_:function(t,e){void 0===e&&(e=0);var n=je(t,"x","argMax");null==e&&(e=0);var r=B(e,n.shape),o=Ze(r,n.rank);null!=o&&(n=n.transpose(o),r=en(r.length,n.rank));var i={axis:r[0]},a=[n];return Ot.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 wn(n)}}}),"ArgMax",i,a)}}),Tc=on({argMin_:function(t,e){void 0===e&&(e=0);var n=je(t,"x","argMin");null==e&&(e=0);var r=B(e,n.shape),o=Ze(r,n.rank);return null!=o&&(n=n.transpose(o),r=en(r.length,n.rank)),Ot.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 wn(n)}}}))}}),Nc=on({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","logSumExp"),o=B(e,r.shape),i=r.max(o,!0),a=r.sub(i).exp().sum(o).log(),s=i.reshape(a.shape).add(a);if(n){var u=Je(s.shape,o);return s.reshape(u)}return s}}),Fc=on({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","max"),o=r,i=B(e,r.shape),a=i,s=Ze(a,r.rank);null!=s&&(r=r.transpose(s),a=en(a.length,r.rank));var u=[r],c=Ot.runKernelFunc((function(t,e){var n=t.max(r,a);return e([o,n]),n}),{x:r},(function(t,e){return Sc(t,e[1],e[0],i,s)}),"Max",{axes:a},u,[!0]);if(n){var l=Je(c.shape,i);c=c.reshape(l)}return c}}),Mc=on({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","mean"),o=B(e,r.shape),i=D($e(r.shape,o)[1]);return Ar((function(t){var r=hn(i);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(mn(t.shape,"float32")).div(i)}}}))(r)}}),Oc=on({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","min"),o=r,i=B(e,r.shape),a=i,s=Ze(a,r.rank);null!=s&&(r=r.transpose(s),a=en(a.length,r.rank));var u=[r],c=Ot.runKernelFunc((function(t,e){var n=t.min(r,a);return e([o,n]),n}),{x:r},(function(t,e){return Sc(t,e[1],e[0],i,s)}),"Min",{axes:a},u,[!0]);if(n){var l=Je(c.shape,i);c=c.reshape(l)}return c}}),Pc=on({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=B(e,(t=je(t,"x","moments")).shape),o=t.mean(r,n),i=o.shape;n||(i=Je(o.shape,r));var a=t.toFloat().sub(o.reshape(i)).square();return{mean:o,variance:a.mean(r,n)}}}),Bc=on({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=B(e,r.shape);return Ar((function(t){var e=Ze(o,t.rank),r=o,i=t;null!=e&&(i=t.transpose(e),r=en(r.length,t.rank));var a=function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(mn(t.shape,"float32"))},s={axes:r},u=Ot.runKernelFunc((function(t){return t.sum(i,r)}),{x:i},(function(t){return{x:function(){return a(t)}}}),"Sum",s);if(n){var c=Je(u.shape,o);u=u.reshape(c)}return{value:u,gradFunc:a}}))(r)}}),Lc=on({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=je(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=B(e,r.shape),i=Ze(o,r.rank),a=o,s=r;null!=i&&(s=r.transpose(i),a=en(a.length,r.rank));var u=Ot.runKernelFunc((function(t){return t.prod(s,a)}),{permutedX:s});if(n){var c=Je(u.shape,o);u=u.reshape(c)}return u}}),Wc=on({elu_:function(t){var e=je(t,"x","elu");return Ot.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 Ot.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),zc=on({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=je(t,"x","leakyRelu");return yu(hn(e).mul(n),n)}}),Uc=on({prelu_:function(t,e){var n=je(t,"x","prelu"),r=je(e,"alpha","prelu");return Ot.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 uu(o,t,t.mul(r))},alpha:function(){var e=uu(o,wn(t),t.mul(n)),i=Br(r.shape,t.shape);return i.length>0&&(e=e.sum(i)),e.reshape(r.shape)}}}),"Prelu")}}),Vc=on({relu_:function(t){var e=je(t,"x","relu");return"bool"===e.dtype?e.toInt():Ot.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")}}),Gc=on({relu6_:function(t){var e=je(t,"x","relu6");return"bool"===e.dtype?e.toInt():Ot.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")}}),Hc=on({selu_:function(t){var e=je(t,"x","selu");return Ot.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(hn(0)),r=hn(Aa),o=hn(Ta),i=t.mul(o),a=t.mul(r).mul(n.toFloat().exp());return uu(e,i,a)}}}))}}),qc=on({transpose_:function(t,e){var n=je(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),I(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){I(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 Ot.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},(function(t){var n=tn(e);return{x:function(){return t.transpose(n)}}}),"Transpose",r)}}),jc=on({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 i=je(t,"x","localResponseNormalization");I(4===i.rank||3===i.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+i.rank+"."})),I(T(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var a=i,s=!1;3===i.rank&&(s=!0,a=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));var u=Ot.runKernelFunc((function(t,i){var s=t.localResponseNormalization4D(a,e,n,r,o);return i([a,s]),s}),{x4D:a},(function(t,i){var a=i[0],s=i[1];return{x4D:function(){return Ot.runKernelFunc((function(i){return i.LRNGrad(t,a,s,e,n,r,o)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Kc=on({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(hn(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=je(t,"x","norm"),e,n),i=o.shape;if(r){var a=B(n,t.shape);i=Je(o.shape,a)}return o.reshape(i)}}),Xc=on({basicLSTMCell_:function(t,e,n,r,o,i){var a=je(t,"forgetBias","basicLSTMCell"),s=je(e,"lstmKernel","basicLSTMCell"),u=je(n,"lstmBias","basicLSTMCell"),c=je(r,"data","basicLSTMCell"),l=je(o,"c","basicLSTMCell"),h=je(i,"h","basicLSTMCell"),f=c.concat(h,1).matMul(s).add(u),p=f.shape[0],d=f.shape[1]/4,v=[p,d],m=f.slice([0,0],v),g=f.slice([0,d],v),y=f.slice([0,2*d],v),x=f.slice([0,3*d],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(l.mulStrict(a.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),Yc=on({multiRNNCell_:function(t,e,n,r){for(var o=je(e,"data","multiRNNCell"),i=Ke(n,"c","multiRNNCell"),a=Ke(r,"h","multiRNNCell"),s=o,u=[],c=0;c<t.length;c++){var l=t[c](s,i[c],a[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var h=[],f=[];for(c=0;c<u.length;c+=2)h.push(u[c]),f.push(u[c+1]);return[h,f]}}),$c=on({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var i=je(t,"v","movingAverage"),a=je(e,"x","movingAverage"),s=je(n,"decay","movingAverage");At(i,a),I(A(i.shape,a.shape),(function(){return"Shape mismatch in v and x"}));var u=hn(1),c=u.sub(s),l=a.sub(i).mul(c);if(o){I(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var h=je(r,"step","movingAverage");l=l.div(u.sub(Ru(s,h)))}return i.add(l)}}),Jc=on({stridedSlice_:function(t,e,n,r,o,i,a,s,u){if(void 0===o&&(o=0),void 0===i&&(i=0),void 0===a&&(a=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==a)throw new Error("ellipsis mask is not yet supported");var c=je(t,"x","stridedSlice"),l=_r(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 f=0;f<c.rank;f++)e[f]=Rr(o,e,r,c.shape,f),n[f]=Sr(i,n,r,c.shape,f),r[f]=r[f]||1;var p=_r(u);p.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var d=Ir(e,n,r),v=d.filter((function(t,e){return-1===p.indexOf(e)}));return r.every((function(t){return 1===t}))?Cc(c,e,d).reshape(v):Ot.runKernelFunc((function(t){return t.stridedSlice(c,e,n,r)}),{$x:c}).reshape(v)}}),Qc=on({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=je(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 i=Ot.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:i[0],indices:i[1]}}}),Zc=on({scatterND_:function(t,e,n){var r=je(t,"indices","scatterND","int32"),o=je(e,"updates","scatterND");return wr(o,r,n),Ot.runKernelFunc((function(t){return t.scatterND(r,o,n)}),{indices:r,updates:o},null,"ScatterNd",{shape:n})}}),tl=on({fft_:function(t){I("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 Ot.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),el=on({ifft_:function(t){I("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 Ot.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),nl=on({rfft_:function(t,e){I("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 i=t.shape.map((function(t){return 0})),a=t.shape.map((function(t){return t}));a[t.shape.length-1]=e,n=t.slice(i,a),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(gn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=an(n,u).as2D(o,r),l=tl(c),h=Math.floor(r/2)+1,f=sn(l),p=un(l),d=f.split([h,r-h],f.shape.length-1),v=p.split([h,r-h],p.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=h,an(d[0],v[0]).reshape(m)}}),rl=on({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=el(r);return sn(o)}var i=[n,2*(e-1)],a=sn(t).as2D(n,e),s=un(t).as2D(n,e),u=a.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(hn(-1)),l=a.concat(u,1),h=s.concat(c,1);return r=an(l,h).as2D(i[0],i[1]),o=el(r),sn(o)}}),ol=Object.freeze({fft:tl,ifft:el,rfft:nl,irfft:rl}),il=on({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=je(t,"sparseIndices","sparseToDense","int32"),i=je(e,"sparseValues","sparseToDense"),a=je(r,"defaultValue","sparseToDense",i.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,i=t.rank>1?t.shape[1]:1;if(n.length!==i)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+i+".");var a=e.size;if(0!==e.rank&&(1!==e.rank||a!==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,i,n,a),Ot.runKernelFunc((function(t){return t.sparseToDense(o,i,n,a)}),{$sparseIndices:o,$sparseValues:i,$defaultValue:a})}}),al=on({gatherND_:function(t,e){var n=je(e,"indices","gatherND","int32"),r=je(t,"x","gatherND");return Ot.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}}),sl=on({diag_:function(t){var e=je(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Ot.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}}),ul=on({dropout_:function(t,e,n,r){var o=je(t,"x","dropout");if(I("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."})),I(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 i=function(t,e){if(null==e)return t.shape.slice();if(A(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),a=1-e,s=ir(i,0,1,"float32",r).add(a).floor().div(a);return o.mul(s)}});function cl(t,e,n){for(var r=1-t%2,o=new Float32Array(t),i=0;i<t;++i){var a=2*Math.PI*i/(t+r-1);o[i]=e-n*Math.cos(a)}return fn(o,"float32")}var ll,hl=on({hannWindow_:function(t){return cl(t,.5,.5)}}),fl=on({hammingWindow_:function(t){return cl(t,.54,.46)}}),pl=on({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var i=0,a=[];i+e<=t.size;)a.push(Cc(t,i,e)),i+=n;if(r)for(;i<t.size;){var s=i+e-t.size,u=Cn([Cc(t,i,e-s),yn([s],o)]);a.push(u),i+=n}return 0===a.length?pn([],[0,e]):Cn(a).as2D(a.length,e)}}),dl=on({stft_:function(t,e,n,r,o){var i;void 0===o&&(o=hl),null==r&&(i=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(i)/Math.log(2)))));for(var a=pl(t,e,n),s=_u(a,o(e)),u=[],c=0;c<a.shape[0];c++)u.push(nl(s.slice([c,0],[1,e]),r));return Cn(u)}}),vl=Object.freeze({hannWindow:hl,hammingWindow:fl,frame:pl,stft:dl});!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(ll||(ll={}));var ml=on({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=ll.SUM_BY_NONZERO_WEIGHTS);var o=je(t,"labels","absoluteDifference"),i=je(e,"predictions","absoluteDifference"),a=null;null!=n&&(a=je(n,"weights","absoluteDifference")),R(o.shape,i.shape,"Error in absoluteDifference: ");var s=o.sub(i).abs();return gl(s,a,r)}}),gl=on({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=ll.SUM_BY_NONZERO_WEIGHTS);var r=je(t,"losses","computeWeightedLoss"),o=null;null!=e&&(o=je(e,"weights","computeWeightedLoss"));var i=null==o?r:r.mul(o);if(n===ll.NONE)return i;if(n===ll.SUM)return i.sum();if(n===ll.MEAN){if(null==o)return i.mean();var a=r.size/o.size,s=i.sum().div(o.sum());return a>1?s.div(hn(a)):s}if(n===ll.SUM_BY_NONZERO_WEIGHTS){if(null==o)return i.sum().div(hn(r.size));var u=o.mul(mn(r.shape)).notEqual(hn(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),yl=on({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=ll.SUM_BY_NONZERO_WEIGHTS);var i=je(t,"labels","cosineDistance"),a=je(e,"predictions","cosineDistance"),s=null;null!=r&&(s=je(r,"weights","cosineDistance")),R(i.shape,a.shape,"Error in cosineDistance: ");var u=hn(1).sub(i.mul(a).sum(n,!0));return gl(u,s,o)}}),xl=on({hingeLoss_:function(t,e,n,r){void 0===r&&(r=ll.SUM_BY_NONZERO_WEIGHTS);var o=je(t,"labels","hingeLoss"),i=je(e,"predictions","hingeLoss"),a=null;null!=n&&(a=je(n,"weights","hingeLoss")),R(o.shape,i.shape,"Error in hingeLoss: ");var s=hn(1);o=hn(2).mul(o).sub(s);var u=s.sub(o.mul(i)).relu();return gl(u,a,r)}}),bl=on({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=ll.SUM_BY_NONZERO_WEIGHTS);var i=je(t,"labels","huberLoss"),a=je(e,"predictions","huberLoss"),s=null;null!=n&&(s=je(n,"weights","huberLoss")),R(i.shape,a.shape,"Error in huberLoss: ");var u=hn(r),c=a.sub(i).abs(),l=bu(c,u),h=c.sub(l),f=hn(.5).mul(l.square()).add(u.mul(h));return gl(f,s,o)}}),wl=on({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=ll.SUM_BY_NONZERO_WEIGHTS);var i=je(t,"labels","logLoss"),a=je(e,"predictions","logLoss"),s=null;null!=n&&(s=je(n,"weights","logLoss")),R(i.shape,a.shape,"Error in logLoss: ");var u=hn(1),c=hn(r),l=i.mul(a.add(c).log()).neg().sub(u.sub(i).mul(u.sub(a).add(c).log()));return gl(l,s,o)}}),Cl=on({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=ll.SUM_BY_NONZERO_WEIGHTS);var o=je(t,"labels","meanSquaredError"),i=je(e,"predictions","meanSquaredError"),a=null;null!=n&&(a=je(n,"weights","meanSquaredError")),R(o.shape,i.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(i);return gl(s,a,r)}}),El=on({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=ll.SUM_BY_NONZERO_WEIGHTS);var i=je(t,"multiClassLabels","sigmoidCrossEntropy"),a=je(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=je(n,"weights","sigmoidCrossEntropy")),R(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=hn(r),c=hn(1),l=hn(.5);i=i.mul(c.sub(u)).add(l.mul(u))}var h=function(t,e){var n=je(t,"labels","sigmoidCrossEntropyWithLogits"),r=je(e,"logits","sigmoidCrossEntropyWithLogits");R(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),i=r.mul(n),a=r.abs().neg().exp().log1p();return o.sub(i).add(a)}(i,a);return gl(h,s,o)}}),_l=on({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=ll.SUM_BY_NONZERO_WEIGHTS);var i=je(t,"onehotLabels","softmaxCrossEntropy"),a=je(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=je(n,"weights","softmaxCrossEntropy")),R(i.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){var u=hn(r),c=hn(1),l=hn(i.shape[1]);i=i.mul(c.sub(u)).add(u.div(l))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Ar((function(t,e,r){var o=e.logSumExp([n],!0),i=e.toFloat().sub(o);return r([t,i]),{value:i.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],i=Je(t.shape,[n]);return[t.reshape(i).mul(r.toFloat().sub(o.exp())),t.reshape(i).mul(o.exp().sub(r.toFloat()))]}}}))(t,e)}(i,a);return gl(h,s,o)}}),Il=Object.freeze({get Reduction(){return ll},absoluteDifference:ml,computeWeightedLoss:gl,cosineDistance:yl,hingeLoss:xl,huberLoss:bl,logLoss:wl,meanSquaredError:Cl,sigmoidCrossEntropy:El,softmaxCrossEntropy:_l});function Rl(t,e){return void 0===e&&(e=!1),Ot.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=Xn(n),i=t.clone(),a=pn([[1]],[1,1]),s=a.clone(),u=n>=r?r:n,c=function(t){var e,u=i,c=s,l=o;e=Ot.tidy((function(){var e=i.slice([t,t],[n-t,1]),u=e.norm(),c=i.slice([t,t],[1,1]),l=pn([[-1]]).where(c.greater(0),pn([[1]])),h=c.sub(l.mul(u)),f=e.div(h);s=1===f.shape[0]?a.clone():a.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var p=l.matMul(h).div(u).neg(),d=i.slice([t,0],[n-t,r]),v=p.mul(s);if(0===t)i=d.sub(v.matMul(s.transpose().matMul(d)));else{var m=d.sub(v.matMul(s.transpose().matMul(d)));i=i.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,i,o]})),s=e[0],i=e[1],o=e[2],Ve([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(o=o.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[o,i]}))}var Sl=on({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=je(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var o=r.shape,i=r.shape.slice(-2),a=i[0],s=i[1];if(!(e<=a))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+a+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=a),n<0&&(n=s);var u=xn(0,a,1,"int32").reshape([-1,1]),c=xn(0,s,1,"int32"),l=Du(u,c),h=ou(l.lessEqual(hn(+e,"int32")),l.greaterEqual(hn(-n,"int32"))),f=gn([a,s],r.dtype);return cr(fr(r.reshape([-1,a,s])).map((function(t){return uu(h,t,f)}))).reshape(o)}}),kl=on({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,I(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){I(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=Sn(t,t.shape[0],0).map((function(t){return ur(t,[0])}));I(t.length<=t[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."}));var i=[],a=t,s=function(t){i.push(Ot.tidy((function(){var e=a[t];if(t>0)for(var n=0;n<t;++n){var r=Bc(i[n].mulStrict(e)).mul(i[n]);e=e.sub(r)}return e.div(Kc(e,"euclidean"))})))};for(o=0;o<t.length;++o)s(o);return e?cr(i,0):i}}),Dl=on({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 Rl(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=fr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],i=[];return r.forEach((function(t){var n=Rl(t,e),r=n[0],a=n[1];o.push(r),i.push(a)})),[cr(o,0).reshape(t.shape),cr(i,0).reshape(t.shape)]}}),Al=Object.freeze({bandPart:Sl,gramSchmidt:kl,qr:Dl});function Tl(t,e,n,r,o,i){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY),null==i&&(i=0);var a=t.shape[0];return n=Math.min(n,a),I(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),I(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),I(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),I(1===e.rank,(function(){return"scores must be a 1D tensor"})),I(e.shape[0]===a,(function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]})),I(0<=i&&i<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+i+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i}}var Nl=on({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=je(t,"images","resizeBilinear");I(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Ot.runKernelFunc((function(t,e){return e([o]),t.resizeBilinear(o,a,s,n)}),{x:o},(function(t,e){return{x:function(){return Ot.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:a,newWidth:s});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Fl=on({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=je(t,"images","resizeNearestNeighbor");I(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),I("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Ot.runKernelFunc((function(t,e){return e([o]),t.resizeNearestNeighbor(o,a,s,n)}),{batchImages:o},(function(t,e){return{batchImages:function(){return Ot.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ml=on({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var i=je(t,"boxes","nonMaxSuppression"),a=je(e,"scores","nonMaxSuppression"),s=Tl(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return Ot.runKernelFunc((function(t){return t.nonMaxSuppression(i,a,n,r,o)}),{boxes:i,scores:a},null,"NonMaxSuppressionV3",u)}}),Ol=on({nonMaxSuppressionWithScore_:function(t,e,n,r,o,i){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===i&&(i=0);var a=je(t,"boxes","nonMaxSuppression"),s=je(e,"scores","nonMaxSuppression"),u=Tl(a,s,n,r,o,i),c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:i=u.softNmsSigma},l=Ot.runKernel("NonMaxSuppressionV5",{boxes:a,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),Pl=on({cropAndResize_:function(t,e,n,r,o,i){var a=je(t,"image","cropAndResize"),s=je(e,"boxes","cropAndResize","float32"),u=je(n,"boxInd","cropAndResize","int32");o=o||"bilinear",i=i||0;var c=s.shape[0];return I(4===a.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."})),I(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),I(1===u.rank&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),I(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),I(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),I("bilinear"===o||"nearest"===o,(function(){return"method must be bilinear or nearest, but was "+o})),Ot.runKernelFunc((function(t,e){return t.cropAndResize(a,s,u,r,o,i)}),{images:a,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:i,cropSize:r})}}),Bl=Object.freeze({resizeBilinear:Nl,resizeNearestNeighbor:Fl,nonMaxSuppression:Ml,nonMaxSuppressionAsync:function(t,e,n,r,o){return void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),u(this,void 0,void 0,(function(){var i,a,s,u,l,h,f;return c(this,(function(c){switch(c.label){case 0:return i=je(t,"boxes","nonMaxSuppressionAsync"),a=je(e,"scores","nonMaxSuppressionAsync"),s=Tl(i,a,n,r,o),n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([i.data(),a.data()])];case 1:return u=c.sent(),l=u[0],h=u[1],f=ao(l,h,n,r,o),i!==t&&i.dispose(),a!==e&&a.dispose(),[2,f]}}))}))},nonMaxSuppressionWithScore:Ol,nonMaxSuppressionWithScoreAsync:function(t,e,n,r,o,i){return void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===i&&(i=0),u(this,void 0,void 0,(function(){var a,s,u,l,h,f,p;return c(this,(function(c){switch(c.label){case 0:return a=je(t,"boxes","nonMaxSuppressionAsync"),s=je(e,"scores","nonMaxSuppressionAsync"),u=Tl(a,s,n,r,o,i),n=u.maxOutputSize,r=u.iouThreshold,o=u.scoreThreshold,i=u.softNmsSigma,[4,Promise.all([a.data(),s.data()])];case 1:return l=c.sent(),h=l[0],f=l[1],p=so(h,f,n,r,o,i),a!==t&&a.dispose(),s!==e&&s.dispose(),[2,p]}}))}))},cropAndResize:Pl}),Ll=function(t,e){return!(t>0)||"linear"===e},Wl=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.")},zl=function(t,e){var n=e,r=Br(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},Ul=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Vc(t);if("elu"===e)return Wc(t);if("relu6"===e)return Gc(t);if("prelu"===e)return Uc(t,n);throw new Error("Unknown fused activation "+e+".")},Vl=on({fusedMatMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,i=void 0!==o&&o,a=t.transposeB,s=void 0!==a&&a,u=t.bias,c=t.activation,l=void 0===c?"linear":c,h=t.preluActivationWeights;if(!1===Ll(Ot.state.gradientDepth,l)){var f=sc(n,r,i,s);return null!=u&&(f=lu(f,u)),Ul(f,l,h)}var p=je(n,"a","fused matMul"),d=je(r,"b","fused matMul");e=Dt(p,d),p=e[0],d=e[1];var v=i?p.shape[p.rank-2]:p.shape[p.rank-1],m=s?d.shape[d.rank-1]:d.shape[d.rank-2],g=i?p.shape[p.rank-1]:p.shape[p.rank-2],y=s?d.shape[d.rank-2]:d.shape[d.rank-1],x=p.shape.slice(0,-2),b=d.shape.slice(0,-2),w=D(x),C=D(b);I(p.rank>=2&&d.rank>=2&&p.rank===d.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+p.rank+" and "+d.rank+"."})),I(A(x,b),(function(){return"Error in fused matMul: outer dimensions ("+x+") and ("+b+") of Tensors with shapes "+p.shape+" and "+d.shape+" must match."})),I(v===m,(function(){return"Error in fused matMul: inner shapes ("+v+") and ("+m+") of Tensors with shapes "+p.shape+" and "+d.shape+" and transposeA="+i+" and transposeB="+s+" must match."}));var E,_,R=p.shape.slice(0,-2).concat([g,y]),S=i?p.as3D(w,v,g):p.as3D(w,g,v),k=s?d.as3D(C,y,m):d.as3D(C,m,y);null!=u&&Lr(R,(E=Dt(E=je(u,"bias","fused matMul"),p)[0]).shape),null!=h&&(_=je(h,"prelu weights","fused matMul"));var T={a:S,b:k};null!=u&&(T.bias=E),null!=h&&(T.preluActivationWeights=_);var N=[S,k];return Ot.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:S,b:k,transposeA:i,transposeB:s,bias:E,activation:l,preluActivationWeights:_});return e([S,k,n]),n}),T,(function(t,e){var n=e[0],r=e[1],o=e[2],a=Wl(t,o,l),c={};return null!=u&&(c={bias:function(){return zl(E,a)}}),i||s?!i&&s?Object.assign({a:function(){return a.matMul(r,!1,!1)},b:function(){return a.matMul(n,!0,!1)}},c):i&&!s?Object.assign({a:function(){return r.matMul(a,!1,!0)},b:function(){return n.matMul(a,!1,!1)}},c):Object.assign({a:function(){return r.matMul(a,!0,!0)},b:function(){return a.matMul(n,!0,!0)}},c):Object.assign({a:function(){return a.matMul(r,!1,!0)},b:function(){return n.matMul(a,!0,!1)}},c)}),"_FusedMatMul",{transposeA:i,transposeB:s,activation:l},N,[!0]).reshape(R)}}),Gl=on({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,i=t.dataFormat,a=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,p=t.preluActivationWeights;if(f=f||"linear",!1===Ll(Ot.state.gradientDepth,f)){var d=Ju(e,n,r,o,a,u,c);return null!=l&&(d=lu(d,l)),Ul(d,f,p)}var v=je(e,"x","conv2d"),m=je(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])),I(4===g.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),I(4===m.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."})),null!=c&&I(T(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."})),I(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]+"."})),I(Yr(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),I("NHWC"===a,(function(){return"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported."}));var x,b,w=Ur(g.shape,m.shape,r,u,o,c);null!=l&&(x=Dt(x=je(l,"bias","fused conv2d"),v)[0],Lr(w.outShape,x.shape)),null!=p&&(b=je(p,"prelu weights","fused conv2d"));var C={x:g,filter:m};null!=l&&(C.bias=x),null!=p&&(C.preluActivationWeights=b);var E=[m,g],_=Ot.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:g,filter:m,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([m,g,n]),n}),C,(function(t,e){var n=e,i=n[0],a=n[1],s=n[2],c=Wl(t,s,f);I(Xr(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 zl(x,c)}}),Object.assign({x:function(){return tc(a.shape,c,i,r,o)},filter:function(){return Zu(a,c,i.shape,r,o)}},h)}),"FusedConv2D",{convInfo:w,activation:f},E,[!0]);return y?_.as3D(_.shape[1],_.shape[2],_.shape[3]):_}}),Hl=on({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,i=t.dataFormat,a=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,p=t.preluActivationWeights;if(!1===Ll(Ot.state.gradientDepth,f)){var d=ec(e,n,r,o,a,u,c);return null!=l&&(d=lu(d,l)),Ul(d,f,p)}var v=je(e,"x","depthwiseConv2d"),m=je(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])),I(4===g.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),I(4===m.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."})),I(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]),I(Yr(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=c&&I(T(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."}));var x,b,w=Ur(g.shape,m.shape,r,u,o,c,!0);null!=l&&(x=Dt(x=je(l,"bias","fused conv2d"),v)[0],Lr(w.outShape,x.shape)),null!=p&&(b=je(p,"prelu weights","fused depthwiseConv2d"));var C={x:g,filter:m};null!=l&&(C.bias=x),null!=p&&(C.preluActivationWeights=b);var E=[m,g],_=Ot.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:g,filter:m,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([m,g,n]),n}),C,(function(t,e){I(Xr(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],i=Wl(t,o,f),a={};return null!=l&&(a={bias:function(){return zl(x,i)}}),Object.assign({x:function(){return nc(r.shape,i,n,w)},filter:function(){return rc(r,i,n.shape,w)}},a)}),"FusedDepthwiseConv2D",{convInfo:w,activation:f},E,[!0]);return y?_.as3D(_.shape[1],_.shape[2],_.shape[3]):_}}),ql=Object.freeze({matMul:Vl,conv2d:Gl,depthwiseConv2d:Hl}),jl=Object.freeze({image:Bl,linalg:Al,losses:Il,spectral:ol,fused:ql,signal:vl,square:ss,squaredDifference:cs,conv1d:$u,conv2d:Ju,conv3d:Qu,depthwiseConv2d:ec,separableConv2d:oc,conv2dTranspose:ic,conv3dTranspose:ac,op:on,batchNormalization2d:$s,batchNormalization3d:Js,batchNormalization4d:Qs,batchNormalization:Zs,batchNorm:tu,batchNorm2d:eu,batchNorm3d:nu,batchNorm4d:ru,booleanMaskAsync:function(t,e,n){return u(this,void 0,void 0,(function(){var r,o,i,a,s,u,l,h,f,p,d,v,m;return c(this,(function(c){switch(c.label){case 0:for(r=je(t,"tensor","boolMask"),o=je(e,"mask","boolMask","bool"),i=null==n?0:n,a=o.rank,s=r.shape,I(a>0,(function(){return"mask cannot be scalar"})),R(s.slice(i,i+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,l=i;l<i+a;l++)u*=s[l];return h=s.slice(0,i).concat([u],s.slice(i+a)),f=r.reshape(h),p=o.reshape([-1]),[4,cu(p)];case 1:return d=c.sent(),v=d.squeeze([1]),m=qu(f,v,i),t!==r&&r.dispose(),e!==o&&o.dispose(),v.dispose(),f.dispose(),p.dispose(),d.dispose(),[2,m]}}))}))},complex:an,real:sn,imag:un,concat:Cn,concat1d:En,concat2d:_n,concat3d:In,concat4d:Rn,split:Sn,matMul:sc,dot:uc,outerProduct:cc,reverse:lc,reverse1d:hc,reverse2d:fc,reverse3d:pc,reverse4d:dc,maxPool:gc,avgPool:yc,pool:xc,maxPool3d:bc,avgPool3d:wc,slice:Cc,slice1d:Ec,slice2d:_c,slice3d:Ic,slice4d:Rc,abs:ls,acos:hs,acosh:fs,asin:ps,asinh:ds,atan:vs,atanh:ms,ceil:gs,clipByValue:ys,cos:xs,cosh:bs,erf:ws,exp:Cs,expm1:Es,floor:_s,log:Is,log1p:Rs,logSigmoid:Ss,neg:ks,reciprocal:Ds,round:As,rsqrt:Ts,sigmoid:Ns,sign:Fs,isNaN:Ms,isInf:Os,isFinite:Ps,sin:Bs,sinh:Ls,softplus:Ws,sqrt:zs,step:Us,tan:Vs,tanh:Gs,all:kc,any:Dc,argMax:Ac,argMin:Tc,logSumExp:Nc,max:Fc,mean:Mc,min:Oc,moments:Pc,sum:Bc,prod:Lc,equal:Tu,equalStrict:Nu,greater:Fu,greaterEqual:Mu,greaterEqualStrict:Ou,greaterStrict:Pu,less:Bu,lessEqual:Lu,lessEqualStrict:Wu,lessStrict:zu,notEqual:Uu,notEqualStrict:Vu,add:lu,addN:hu,addStrict:fu,atan2:pu,div:du,divNoNan:vu,divStrict:mu,floorDiv:gu,maximum:yu,maximumStrict:xu,minimum:bu,minimumStrict:wu,mod:Cu,modStrict:Eu,mul:_u,mulStrict:Iu,pow:Ru,powStrict:Su,squaredDifferenceStrict:ku,sub:Du,subStrict:Au,elu:Wc,leakyRelu:zc,prelu:Uc,relu:Vc,relu6:Gc,selu:Hc,logicalAnd:ou,logicalNot:iu,logicalOr:au,logicalXor:su,where:uu,whereAsync:cu,buffer:zn,print:function(t,e){void 0===e&&(e=!1),console.log(t.toString(e))},batchToSpaceND:Un,broadcastTo:Vn,cast:Gn,clone:Hn,cumsum:qn,depthToSpace:jn,expandDims:Kn,eye:Xn,multinomial:Yn,oneHot:$n,pad:Jn,pad1d:Qn,pad2d:Zn,pad3d:tr,pad4d:er,rand:nr,randomNormal:rr,randomGamma:or,randomUniform:ir,reshape:ar,spaceToBatchND:sr,squeeze:ur,stack:cr,tile:lr,truncatedNormal:hr,unstack:fr,setdiff1dAsync:function(t,e){return u(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,l,h,f;return c(this,(function(c){switch(c.label){case 0:return n=je(t,"x","setdiff1d"),r=je(e,"y","setdiff1d"),I(n.dtype===r.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."})),I(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),I(1===r.rank,(function(){return"y should be 1D tensor, but got y ("+r.shape+")."})),[4,n.data()];case 1:return o=c.sent(),[4,r.data()];case 2:for(i=c.sent(),a=new Set(i),s=0,h=0;h<o.length;h++)a.has(o[h])||s++;for(u=new vt([s],n.dtype),l=new vt([s],"int32"),h=0,f=0;h<o.length;h++)a.has(o[h])||(u.values[f]=o[h],l.values[f]=h,f++);return[2,[u.toTensor(),l.toTensor()]]}}))}))},fill:yn,linspace:function(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Ot.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})},ones:mn,range:xn,scalar:hn,tensor:cn,tensor1d:fn,tensor2d:pn,tensor3d:dn,tensor4d:vn,tensor5d:function(t,e,n){if(S(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=He(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 ln(t,e,r,n)},tensor6d:function(t,e,n){if(S(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=He(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 ln(t,e=e||r,r,n)},variable:function(t,e,n,r){return void 0===e&&(e=!0),Ot.makeVariable(t,e,n,r)},zeros:gn,onesLike:bn,zerosLike:wn,transpose:qc,softmax:Tr,logSoftmax:Nr,localResponseNormalization:jc,norm:Kc,gather:qu,unsortedSegmentSum:ju,basicLSTMCell:Xc,multiRNNCell:Yc,movingAverage:$c,stridedSlice:Jc,topk:Qc,scatterND:Zc,fft:tl,ifft:el,rfft:nl,irfft:rl,sparseToDense:il,gatherND:al,diag:sl,dropout:ul,hannWindow:hl,hammingWindow:fl,frame:pl,stft:dl,inTopKAsync:function(t,e,n){return void 0===n&&(n=1),u(this,void 0,void 0,(function(){var r,o,i,a,s,u,l,h,f,p,d,v,m,g;return c(this,(function(c){switch(c.label){case 0:return r=je(t,"predictions","inTopK"),o=je(e,"targets","inTopK"),I(r.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),I(r.rank-1===o.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+o.rank})),R(r.shape.slice(0,r.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=r.shape[r.shape.length-1],I(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 a=c.sent(),[4,o.data()];case 2:for(s=c.sent(),u=[a.length/i,i],h=u[1],f=W("bool",l=u[0]),p=0;p<l;p++){for(d=p*h,v=a.subarray(d,d+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})),f[p]=0,g=0;g<n;g++)if(m[g].index===s[p]){f[p]=1;break}}return t!==r&&r.dispose(),e!==o&&o.dispose(),[2,cn(f,o.shape,"bool")]}}))}))}});function Kl(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&I("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function Xl(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 Yl=function(t){function e(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new Fr(e,Ot),e}return s(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,f().get("IS_NODE")&&Ge("\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 u(this,void 0,void 0,(function(){return c(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?to(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 st(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return zn(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Ot.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 u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return e=ot(),t(),[2,{kernelMs:ot()-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:Ot.keep(t.clone()),imag:Ot.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(Kl(t,"slice"),kr(t.shape,e,n)){var r=Dr(e,t.strides),o=D(n);return cn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var i=zn(n,t.dtype),a=this.bufferSync(t),s=0;s<i.size;++s){var u=i.indexToLoc(s).map((function(t,n){return t+e[n]}));i.values[s]=a.get.apply(a,u)}return i.toTensor()},e.prototype.stridedSlice=function(t,e,n,r){Kl(t,"stridedSlice");var o=Ir(e,n,r);if(o.some((function(t){return 0===t})))return cn([],o);for(var i=zn(o,t.dtype),a=this.bufferSync(t),s=0;s<i.size;s++){for(var u=i.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];i.set.apply(i,[a.get.apply(a,c)].concat(u))}return i.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=zn([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,i=0;i<t.rank;i++)i!==e&&(r[o++]=t.shape[i]);var a=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(i=0;i<u.length;i++)a[e]=i,u[i]=this.slice(t,a,s).reshape(r);return u},e.prototype.reverse=function(t,e){Kl(t,"reverse");for(var n=zn(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var i=n.indexToLoc(o),a=i.slice();e.forEach((function(e){return a[e]=t.shape[e]-1-a[e]})),n.set.apply(n,[r.get.apply(r,a)].concat(i))},i=0;i<n.size;i++)o(i);return n.toTensor()},e.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map((function(t){return sn(t)})),o=t.map((function(t){return un(t)}));return an(this.concat(r,e),this.concat(o,e))}var i=t.map((function(t){var n=D(t.shape.slice(e));return t.as2D(-1,n)})),a=rn(i.map((function(t){return t.shape})),1),s=zn(a,t[0].dtype).values;if(1===i[0].shape[0]){var u=0;i.forEach((function(t){s.set(n.readSync(t.dataId),u),u+=t.size}))}else{var c=0;i.forEach((function(t){for(var e=n.readSync(t.dataId),r=0,o=0;o<t.shape[0];++o)for(var i=o*a[1]+c,u=0;u<t.shape[1];++u)s[i+u]=e[r++];c+=t.shape[1]}))}var l=rn(t.map((function(t){return t.shape})),e);return cn(s,l,t[0].dtype)},e.prototype.neg=function(t){return Kl(t,"neg"),this.multiply(hn(-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;Kl(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=zn(t[0].shape,t[0].dtype),o=r.values,i=0;i<t.length;i++)for(var a=n[i],s=0;s<o.length;s++)o[s]+=a[s];return r.toTensor()},e.prototype.softmax=function(t,e){var n=B([e],t.shape),r=this.max(t,n),o=Je(r.shape,n),i=this.subtract(t,r.reshape(o)),a=this.exp(i),s=this.sum(a,n).reshape(o);return this.realDivide(a,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 Kl([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){Kl([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],i=n?t.shape[2]:t.shape[1],a=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],f=l[1],p=l[2],d=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=d[0],m=d[1],g=d[2],y=i*a,x=zn([s,i,a],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<i;E+=w)for(var _=0;_<a;_+=w)for(var I=0;I<o;I+=w)for(var R=Math.min(E+w,i),S=Math.min(_+w,a),k=Math.min(I+w,o),D=E;D<R;D++)for(var A=_;A<S;A++){for(var T=0,N=I;N<k;N++)T+=u[C*h+D*f+N*p]*c[N*v+A*m+C*g];b[C*y+(D*a+A)]+=T}return x.toTensor()},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,i=t.bias,a=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,o);return i&&(u=this.add(u,i)),a&&(u=Xl(this,u,a,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){return Kl([t,e],"realDivide"),this.broadcastedBinaryOp(t,e,"float32",(function(t,e){return t/e}))},e.prototype.floorDiv=function(t,e){return Kl([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},e.prototype.sum=function(t,e){Kl(t,"sum"),Qe("sum",e,t.rank);for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,St(t.dtype,"int32")),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=0,f=0;f<a;++f)h+=u[l+f];s[c]=h}return i},e.prototype.prod=function(t,e){Kl(t,"sum");for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,St(t.dtype,"int32")),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=1,f=0;f<a;++f)h*=u[l+f];s[c]=h}return i},e.prototype.unsortedSegmentSum=function(t,e,n){Kl(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,i=0;i<o;++i)e=e.expandDims(i+1);for(i=0;i<n;++i){var a=hn(i,"int32"),s=Tu(a,e).asType("float32").mul(t).sum(0);r.push(s)}return cr(r)},e.prototype.argMin=function(t,e){Kl(t,"argMin");var n=[e];Qe("argMin",n,t.rank);for(var r=$e(t.shape,n),o=r[0],i=r[1],a=gn(o,"int32"),s=D(i),u=this.readSync(a.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],p=0,d=0;d<s;++d){var v=c[h+d];v<f&&(f=v,p=d)}u[l]=p}return a},e.prototype.argMax=function(t,e){Kl(t,"argMax");var n=[e];Qe("argMax",n,t.rank);for(var r=$e(t.shape,n),o=r[0],i=r[1],a=gn(o,"int32"),s=D(i),u=this.readSync(a.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],p=0,d=0;d<s;++d){var v=c[h+d];v>f&&(f=v,p=d)}u[l]=p}return a},e.prototype.cumsum=function(t,e,n,r){if(Kl(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"),i=gn(t.shape,o),a=this.readSync(i.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 f=c(l,h);if(0===h)a[f]=n?0:s[f];else{var p=c(l,h-1);a[f]=n?s[p]+a[p]:s[f]+a[p]}}return i},e.prototype.equal=function(t,e){return Kl([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},e.prototype.notEqual=function(t,e){return Kl([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},e.prototype.less=function(t,e){return Kl([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},e.prototype.lessEqual=function(t,e){return Kl([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},e.prototype.greater=function(t,e){return Kl([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},e.prototype.greaterEqual=function(t,e){return Kl([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},e.prototype.logicalNot=function(t){Kl(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 Kl([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},e.prototype.logicalOr=function(t,e){return Kl([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},e.prototype.select=function(t,e,n){Kl([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),i=this.readSync(n.dataId),a=gn(e.shape,St(e.dtype,n.dtype)),s=this.readSync(a.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:D(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++]=i[l];return a},e.prototype.where=function(t){Kl([t],"where");var e=this.readSync(t.dataId);return mo(t.shape,e)},e.prototype.topk=function(t,e,n){return Kl(t,"topk"),vo(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){Kl(t,"min"),Qe("min",e,t.rank);for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,t.dtype),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=u[l],f=0;f<a;++f){var p=u[l+f];p<h&&(h=p)}s[c]=h}return i},e.prototype.minimum=function(t,e){return Kl([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},e.prototype.mod=function(t,e){return Kl([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){Kl(t,"max"),Qe("max",e,t.rank);for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,t.dtype),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=u[l],f=0;f<a;++f){var p=u[l+f];p>h&&(h=p)}s[c]=h}return i},e.prototype.maximum=function(t,e){return Kl([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},e.prototype.all=function(t,e){Kl(t,"all"),Qe("all",e,t.rank);for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,t.dtype),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=u[l],f=0;f<a;++f){var p=u[l+f];h=h&&p}s[c]=h}return i},e.prototype.any=function(t,e){Kl(t,"any"),Qe("any",e,t.rank);for(var n=$e(t.shape,e),r=n[0],o=n[1],i=gn(r,t.dtype),a=D(o),s=this.readSync(i.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*a,h=u[l],f=0;f<a;++f){var p=u[l+f];h=h||p}s[c]=h}return i},e.prototype.squaredDifference=function(t,e){return Kl([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},e.prototype.ceil=function(t){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(t,"relu");for(var e=gn(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){Kl(t,"relu");for(var e=gn(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 Kl([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},e.prototype.elu=function(t){Kl(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){Kl([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),i=0;i<r.length;++i){var a=r[i];n[i]=a>=1?o[i]:o[i]*(a+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){Kl(t,"selu");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?1.0507009873554805*o:1.7580993408473768*(Math.exp(o)-1)}return this.makeOutput(e,t.shape,"float32")},e.prototype.clip=function(t,e,n){Kl(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),i=0;i<o.length;++i){var a=o[i];r[i]=a>n?n:a<e?e:a}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],i=n[2*r+1];e[r]=Math.hypot(o,i)}return this.makeOutput(e,t.shape,"float32")},e.prototype.int=function(t){Kl(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){Kl(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){Kl(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 i,a=r[o]>-e,s=r[o]<e,u=Math.exp(r[o]);i=s?u:a?r[o]:Math.log(1+u),n[o]=i}return this.makeOutput(n,t.shape,"float32")},e.prototype.sin=function(t){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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){Kl(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 Kl([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},e.prototype.sinh=function(t){Kl(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){Kl(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){Kl(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=N(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asinh=function(t){Kl(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){Kl(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){Kl(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){Kl(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]),i=Math.abs(n[r]),a=1/(1+.3275911*i);e[r]=o*(1-((((1.061405429*a-1.453152027)*a+1.421413741)*a-.284496736)*a+.254829592)*a*Math.exp(-i*i))}return this.makeOutput(e,t.shape,"float32")},e.prototype.step=function(t,e){void 0===e&&(e=0),Kl(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var i=r[o];isNaN(i)?n[o]=NaN:n[o]=i>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,i=t.activation,a=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),i&&(s=Xl(this,s,i,a)),s},e.prototype.conv2d=function(t,e,n){Kl([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,i=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c="channelsLast"===n.dataFormat,l=zn(n.outShape,t.dtype),h=t.strides[0],f=c?t.strides[1]:t.strides[2],p=c?t.strides[2]:1,d=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,_=C*v,I=0;I<n.outHeight;++I)for(var R=_+I*m,S=I*n.strideHeight-u,k=0;k<r;k++){var D=S+k*i;if(!(D<0||D>=n.inHeight))for(var A=k*e.strides[0],T=E+D*f,N=0;N<n.outWidth;++N)for(var F=R+N*g,M=N*n.strideWidth-s,O=0;O<o;O++){var P=M+O*a;if(!(P<0||P>=n.inWidth))for(var B=T+P*p,L=A+O*e.strides[1],W=0;W<n.inChannels;++W){for(var z=x[B+W*d],U=0;U<n.outChannels;++U)w[F+U*y]+=z*b[L+U];L+=n.outChannels}}}return l.toTensor()},e.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,i=n.filterWidth,a=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,c=n.padInfo.front,l=n.padInfo.left,h=n.padInfo.top,f=zn(n.outShape,t.dtype),p=this.readSync(t.dataId),d=this.readSync(e.dataId),v=f.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],y=m*f.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*f.strides[1],w=x*n.strideDepth-c,C=0;C<r;C++){var E=w+C*a;if(!(E<0||E>=n.inDepth))for(var _=C*e.strides[0],I=g+E*t.strides[1],R=0;R<n.outHeight;++R)for(var S=b+R*f.strides[2],k=R*n.strideHeight-h,D=0;D<o;D++){var A=k+D*s;if(!(A<0||A>=n.inHeight))for(var T=_+D*e.strides[1],N=I+A*t.strides[2],F=0;F<n.outWidth;++F)for(var M=S+F*n.outChannels,O=F*n.strideWidth-l,P=0;P<i;P++){var B=O+P*u;if(!(B<0||B>=n.inWidth))for(var L=T+P*e.strides[2],W=N+B*n.inChannels,z=L,U=0;U<n.inChannels;++U){for(var V=p[W+U],G=0;G<n.outChannels;++G)v[M+G]+=V*d[z+G];z+=n.outChannels}}}}return f.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){Kl([t,e],"conv2dDerInput");for(var r=zn(n.inShape,"float32"),o=r.values,i=this.readSync(t.dataId),a=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],h=n.batchSize,f=n.filterHeight,p=n.filterWidth,d=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=f-1-n.padInfo.top,_=p-1-n.padInfo.left,I="channelsLast"===C,R=r.strides[0],S=I?r.strides[1]:r.strides[2],k=I?r.strides[2]:1,D=I?1:r.strides[1],A=t.strides[0],T=I?t.strides[1]:t.strides[2],N=I?t.strides[2]:1,F=I?1:t.strides[1],M=0;M<h;++M)for(var O=0;O<d;++O)for(var P=0;P<v;++P)for(var B=P-E,L=Math.max(0,Math.ceil(B/b)),W=Math.min(y,(f+B)/b),z=0;z<m;++z){for(var U=z-_,V=Math.max(0,Math.ceil(U/w)),G=Math.min(x,(p+U)/w),H=0,q=L;q<W;++q)for(var j=q*b-B,K=V;K<G;++K)for(var X=A*M+T*q+N*K,Y=u*(f-1-j)+c*(p-1-(K*w-U))+l*O,$=0;$<g;++$)H+=i[X+F*$]*a[Y+$];o[R*M+S*P+k*z+D*O]=H}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=zn(n.inShape,"float32"),o=r.values,i=r.strides,a=i[0],s=i[1],u=i[2],c=i[3],l=this.readSync(t.dataId),h=t.strides,f=h[0],p=h[1],d=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,_=n.filterHeight,I=n.filterWidth,R=n.inChannels,S=n.inDepth,k=n.inHeight,D=n.inWidth,A=n.outChannels,T=n.outDepth,N=n.outHeight,F=n.outWidth,M=n.strideDepth,O=n.strideHeight,P=n.strideWidth,B=E-1-n.padInfo.front,L=_-1-n.padInfo.top,W=I-1-n.padInfo.left,z=0;z<C;++z)for(var U=0;U<R;++U)for(var V=0;V<S;++V)for(var G=V-B,H=Math.max(0,Math.ceil(G/M)),q=Math.min(T,(E+G)/M),j=0;j<k;++j)for(var K=j-L,X=Math.max(0,Math.ceil(K/O)),Y=Math.min(N,(_+K)/O),$=0;$<D;++$){for(var J=$-W,Q=Math.max(0,Math.ceil(J/P)),Z=Math.min(F,(I+J)/P),tt=0,et=H;et<q;++et)for(var nt=et*M-G,rt=X;rt<Y;++rt)for(var ot=rt*O-K,it=Q;it<Z;++it)for(var at=f*z+p*et+d*rt+v*it,st=y*(E-1-nt)+x*(_-1-ot)+b*(I-1-(it*P-J))+w*U,ut=0;ut<A;++ut)tt+=l[at+ut]*m[st+ut];o[a*z+s*V+u*j+c*$+U]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){Kl([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,i=n.filterHeight,a=n.filterWidth,s="channelsLast"===n.dataFormat,u=zn(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,h=this.bufferSync(t),f=this.bufferSync(e),p=0;p<i;++p)for(var d=Math.max(0,Math.ceil((l-p)/r)),v=Math.min(n.outHeight,(n.inHeight+l-p)/r),m=0;m<a;++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=d;E<v;++E)for(var _=p+E*r-l,I=g;I<y;++I){var R=m+I*o-c;w+=s?h.get(C,_,R,x)*f.get(C,E,I,b):h.get(C,x,_,R)*f.get(C,b,E,I)}u.set(w,p,m,x,b)}return u.toTensor()},e.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,i=n.strideWidth,a=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=zn(n.filterShape,"float32"),l=c.values,h=c.strides,f=h[0],p=h[1],d=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,_=E[0],I=E[1],R=E[2],S=E[3],k=n.padInfo.front,D=n.padInfo.left,A=n.padInfo.top,T=0;T<a;++T)for(var N=Math.max(0,Math.ceil((k-T)/r)),F=Math.min(n.outDepth,(n.inDepth+k-T)/r),M=T*f,O=0;O<s;++O)for(var P=Math.max(0,Math.ceil((A-O)/o)),B=Math.min(n.outHeight,(n.inHeight+A-O)/o),L=O*p+M,W=0;W<u;++W)for(var z=Math.max(0,Math.ceil((D-W)/i)),U=Math.min(n.outWidth,(n.inWidth+D-W)/i),V=W*d+L,G=0;G<n.inChannels;++G)for(var H=G*v+V,q=0;q<n.outChannels;++q){for(var j=0,K=0;K<n.batchSize;++K)for(var X=K*_,Y=K*y,$=N;$<F;++$)for(var J=(T+$*r-k)*I+X,Q=$*x+Y,Z=P;Z<B;++Z)for(var tt=(O+Z*o-A)*R+J,et=Z*b+Q,nt=z;nt<U;++nt){var rt=nt*w+et;j+=C[(W+nt*i-D)*S+tt+G]*m[rt+q]}l[H+q]=j}return c.toTensor()},e.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,i=t.activation,a=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return o&&(s=this.add(s,o)),i&&(s=Xl(this,s,i,a)),s},e.prototype.depthwiseConv2D=function(t,e,n){Kl([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,i=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=zn(n.outShape,t.dtype),h=this.readSync(t.dataId),f=this.readSync(e.dataId),p=l.values,d=0;d<n.batchSize;++d)for(var v=d*t.strides[0],m=d*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*i;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],_=0;_<n.outWidth;++_)for(var I=y+_*l.strides[2],R=_*n.strideWidth-u,S=0;S<o;++S){var k=R+S*a;if(!(k<0||k>=n.inWidth))for(var D=C+S*e.strides[1],A=E+k*n.inChannels,T=I,N=D,F=0;F<n.inChannels;++F){for(var M=h[A+F],O=0;O<c;++O)p[T+O]+=M*f[N+O];T+=c,N+=c}}}return l.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){Kl([t,e],"depthwiseConv2DDerInput");for(var r=zn(n.inShape,"float32"),o=r.values,i=r.strides,a=i[0],s=i[1],u=i[2],c=this.readSync(t.dataId),l=t.strides,h=l[0],f=l[1],p=l[2],d=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,_=n.inWidth,I=n.outChannels,R=n.outHeight,S=n.outWidth,k=n.strideHeight,D=n.strideWidth,A=b-1-n.padInfo.top,T=w-1-n.padInfo.left,N=I/C,F=0;F<x;++F)for(var M=0;M<C;++M)for(var O=0;O<E;++O)for(var P=O-A,B=Math.max(0,Math.ceil(P/k)),L=Math.min(R,(b+P)/k),W=0;W<_;++W){for(var z=W-T,U=Math.max(0,Math.ceil(z/D)),V=Math.min(S,(w+z)/D),G=0,H=B;H<L;++H)for(var q=H*k-P,j=U;j<V;++j)for(var K=h*F+f*H+p*j,X=m*(b-1-q)+g*(w-1-(j*D-z))+y*M,Y=0;Y<N;++Y)G+=c[K+(M*N+Y)]*d[X+Y];o[a*F+s*O+u*W+M]=G}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){Kl([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,i=n.filterHeight,a=n.filterWidth,s=zn(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,h=this.bufferSync(t),f=this.bufferSync(e),p=0;p<i;++p)for(var d=Math.max(0,Math.ceil((c-p)/r)),v=Math.min(n.outHeight,(n.inHeight+c-p)/r),m=0;m<a;++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 _=d;_<v;++_)for(var I=p+_*r-c,R=g;R<y;++R){var S=m+R*o-u;C+=h.get(E,I,S,b)*f.get(E,_,R,x)}s.set(C,p,m,b,w)}return s.toTensor()},e.prototype.tile=function(t,e){return Kl(t,"tile"),po(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){Kl(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]})),i=this.bufferSync(t),a=zn(r,t.dtype);0!==n&&a.values.fill(n);for(var s=0;s<t.size;s++){var u=i.indexToLoc(s),c=u.map((function(t,e){return t+o[e]}));a.set.apply(a,[i.get.apply(i,u)].concat(c))}return a.toTensor()},e.prototype.transpose=function(t,e){Kl(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),i=zn(n,t.dtype),a=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=a.indexToLoc(r),u=new Array(s.length),c=0;c<u.length;c++)u[c]=s[e[c]];var l=i.locToIndex(u);i.values[l]=o[r]}return i.toTensor()},e.prototype.gather=function(t,e,n){Kl([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var i=zn(r,t.dtype),a=this.bufferSync(t),s=0;s<i.size;++s){var u=i.indexToLoc(s),c=u.slice();c[n]=o[u[n]];var l=a.locToIndex(c);i.values[s]=a.values[l]}return i.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){Kl([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),o=pr(t.shape,e,r),i=dr(o.length,e.length),a=vr(t.shape,e,r),s=mr(n,e.length),u=gr(a,n,e.length);return t.reshape(o).transpose(i).reshape(a).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){Kl([t],"spaceToBatchND");var r=e.reduce((function(t,e){return t*e})),o=[[0,0]];o.push.apply(o,n);for(var i=1+e.length;i<t.shape.length;++i)o.push([0,0]);var a=t.pad(o),s=pr(a.shape,e,r,!1),u=dr(s.length,e.length,!1),c=vr(a.shape,e,r,!1);return a.reshape(s).transpose(u).reshape(c)},e.prototype.pool=function(t,e,n){Kl(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,i=e.dilationHeight,a=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,f=this.readSync(t.dataId),p=zn(e.outShape,t.dtype),d=p.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,_=Math.max(0,E),I=Math.min(e.inHeight,s+E),R=x+C*m,S=0;S<e.outWidth;++S){for(var k=S*o-l,D=Math.max(0,k),A=Math.min(e.inWidth,u+k),T=h,N=0,F=0,M=_;M<I;M+=i){for(var O=b+M*t.strides[1],P=D;P<A;P+=a){var B=f[O+P*t.strides[2]+w];"max"===n&&B>T?T=B:"avg"===n&&(N+=B,F++)}if(isNaN(T))break}d[R+S*g+w]="avg"===n?N/F:T}return p.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=zn(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,i=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h=this.bufferSync(t),f=0;f<e.batchSize;++f)for(var p=0;p<e.inChannels;++p)for(var d=0;d<e.outHeight;++d){for(var v=d*r-c,m=v;m<0;)m+=i;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+=a;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,_=m;_<g;_+=i)for(var I=_-v,R=b;R<w;R+=a){var S=R-x,k=h.get(f,_,R,p);k>C&&(C=k,E=I*u+S)}n.set(E,f,d,y,p)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){Kl([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),i=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,h=l-1-r.padInfo.left,f=c-1-r.padInfo.top,p=zn(e.shape,"float32"),d=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-f,w=x-h,C=0,E=0;E<c;E+=s){var _=(b+E)/i;if(!(_<0||_>=r.outHeight||Math.floor(_)!==_))for(var I=0;I<l;I+=u){var R=(w+I)/a;if(!(R<0||R>=r.outWidth||Math.floor(R)!==R)){var S=c*l-1-d.get(m,_,R,g)===E*l+I?1:0;0!==S&&(C+=v.get(m,_,R,g)*S)}}}p.set(C,m,y,x,g)}return p.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){Kl([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,i=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,f=c-1-n.padInfo.top,p=zn(e.shape,"float32"),d=1/(i*a),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-f,w=x-h,C=0,E=0;E<c;E+=s){var _=(b+E)/r;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var I=0;I<l;I+=u){var R=(w+I)/o;R<0||R>=n.outWidth||Math.floor(R)!==R||(C+=v.get(m,_,R,g))}}p.set(C*d,m,y,x,g)}return p.toTensor()},e.prototype.pool3d=function(t,e,n){Kl(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,i=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,p=e.padInfo.top,d=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=zn(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 _=E*x,I=E*t.strides[0],R=0;R<e.inChannels;++R)for(var S=0;S<e.outDepth;++S){for(var k=S*r-f,D=k;D<0;)D+=a;for(var A=Math.min(e.inDepth,c+k),T=_+S*b,N=0;N<e.outHeight;++N){for(var F=N*o-p,M=F;M<0;)M+=s;for(var O=Math.min(e.inHeight,l+F),P=T+N*w,B=0;B<e.outWidth;++B){for(var L=B*i-d,W=L;W<0;)W+=u;for(var z=Math.min(e.inWidth,h+L),U=P+B*C,V=v,G=0,H=0,q=D;q<A;q+=a){for(var j=I+q*t.strides[1],K=M;K<O;K+=s){for(var X=j+K*t.strides[2],Y=W;Y<z;Y+=u){var $=m[X+Y*t.strides[3]+R];if("max"===n&&$>V?V=$:"avg"===n&&(G+=$,H++),isNaN(V))break}if(isNaN(V))break}if(isNaN(V))break}y[U+R]="avg"===n?G/H:V}}}return g.toTensor()},e.prototype.avgPool3d=function(t,e){return Kl(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){Kl([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,i=n.strideWidth,a=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,h=n.dilationWidth,f=n.effectiveFilterDepth,p=n.effectiveFilterHeight,d=n.effectiveFilterWidth,v=f-1-n.padInfo.front,m=d-1-n.padInfo.left,g=p-1-n.padInfo.top,y=zn(e.shape,"float32"),x=1/(a*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 _=0;_<n.inHeight;++_)for(var I=0;I<n.inWidth;++I){for(var R=E-v,S=_-g,k=I-m,D=0,A=0;A<f;A+=c){var T=(R+A)/r;if(!(T<0||T>=n.outDepth||Math.floor(T)!==T))for(var N=0;N<p;N+=l){var F=(S+N)/o;if(!(F<0||F>=n.outHeight||Math.floor(F)!==F))for(var M=0;M<d;M+=h){var O=(k+M)/i;O<0||O>=n.outWidth||Math.floor(O)!==O||(D+=b.get(w,T,F,O,C))}}}y.set(D*x,w,E,_,I,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return Kl(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=zn(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,i=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,p=e.padInfo.top,d=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-f,b=x;b<0;)b+=a;for(var w=Math.min(e.inDepth,c+x),C=0;C<e.outHeight;++C){for(var E=C*o-p,_=E;_<0;)_+=s;for(var I=Math.min(e.inHeight,l+E),R=0;R<e.outWidth;++R){for(var S=R*i-d,k=S;k<0;)k+=u;for(var D=Math.min(e.inWidth,h+S),A=Number.NEGATIVE_INFINITY,T=-1,N=b;N<w;N+=a)for(var F=N-x,M=_;M<I;M+=s)for(var O=M-E,P=k;P<D;P+=u){var B=P-S,L=v.get(m,N,M,P,g);L>=A&&(A=L,T=F*l*h+O*l+B)}n.set(T,m,y,C,R,g)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){Kl([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),i=r.strideDepth,a=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,h=r.effectiveFilterDepth,f=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=h-1-r.padInfo.front,v=p-1-r.padInfo.left,m=f-1-r.padInfo.top,g=zn(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 _=0;_<r.inWidth;++_){for(var I=C-d,R=E-m,S=_-v,k=0,D=0;D<h;D+=u){var A=(I+D)/i;if(!(A<0||A>=r.outDepth||Math.floor(A)!==A))for(var T=0;T<f;T+=c){var N=(R+T)/a;if(!(N<0||N>=r.outHeight||Math.floor(N)!==N))for(var F=0;F<p;F+=l){var M=(S+F)/s;if(!(M<0||M>=r.outWidth||Math.floor(M)!==M)){var O=h*f*p-1-y.get(b,A,N,M,w)===D*f*p+T*p+F?1:0;0!==O&&(k+=x.get(b,A,N,M,w)*O)}}}}g.set(k,b,C,E,_,w)}return g.toTensor()},e.prototype.cast=function(t,e){return Jr(t,e,this)},e.prototype.reshape=function(t,e){return Qr(t,e)},e.prototype.avgPool=function(t,e){return Kl(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){Kl(t,"resizeBilinear");for(var o=t.shape,i=o[0],a=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(D([i,e,n,u])),h=[r&&e>1?a-1:a,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],p=0,d=h[0]/f[0],v=h[1]/f[1],m=0;m<i;m++)for(var g=0;g<e;g++)for(var y=d*g,x=Math.floor(y),b=y-x,w=Math.min(a-1,Math.ceil(y)),C=m*t.strides[0]+x*t.strides[1],E=m*t.strides[0]+w*t.strides[1],_=0;_<n;_++)for(var I=v*_,R=Math.floor(I),S=I-R,k=Math.min(s-1,Math.ceil(I)),A=C+R*t.strides[2],T=E+R*t.strides[2],N=C+k*t.strides[2],F=E+k*t.strides[2],M=0;M<u;M++){var O=c[A+M],P=c[T+M],B=O+(c[N+M]-O)*S,L=B+(P+(c[F+M]-P)*S-B)*b;l[p++]=L}return cn(l,[i,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){Kl([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],i=r[1],a=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*i*a*s),f=[n&&c>1?i-1:i,n&&l>1?a-1:a],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],d=f[0]/p[0],v=f[1]/p[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*d,C=Math.floor(w),E=Math.min(Math.ceil(w),i-1),_=x+C*e.strides[1],I=x+E*e.strides[1],R=w-C,S=1-R,k=0;k<l;k++)for(var D=k*v,A=Math.floor(D),T=Math.min(Math.ceil(D),a-1),N=D-A,F=1-N,M=_+A*e.strides[2],O=_+T*e.strides[2],P=I+A*e.strides[2],B=I+T*e.strides[2],L=S*F,W=S*N,z=R*F,U=R*N,V=0;V<s;V++){var G=m[g++];h[M+V]+=G*L,h[O+V]+=G*W,h[P+V]+=G*z,h[B+V]+=G*U}return vn(h,[o,a,i,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){Kl(t,"resizeNearestNeighbor");for(var o=t.shape,i=o[0],a=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(i*e*n*u),h=[r&&e>1?a-1:a,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],p=h[0]/f[0],d=h[1]/f[1],v=0,m=0;m<i;m++)for(var g=m*t.strides[0],y=0;y<e;y++)for(var x=p*y,b=g+Math.min(a-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=d*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],_=0;_<u;_++){var I=c[E+_];l[v++]=I}return cn(l,[i,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){Kl([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],i=r[1],a=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*i*a*s),f=this.readSync(t.dataId),p=[n&&c>1?i-1:i,n&&l>1?a-1:a],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=p[0]/d[0],m=p[1]/d[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<i;E++)for(var _=C+E*e.strides[1],I=Math.floor(E*g),R=Math.floor(I-x/2),S=0;S<a;S++)for(var k=_+S*e.strides[2],D=Math.floor(S*y),A=Math.floor(D-b/2),T=0;T<s;T++){for(var N=0,F=0;F<x;F++){var M=F+R;if(!(M<0||M>=c)){var O=C+M*t.strides[1],P=M*v;if(E===Math.min(i-1,n?Math.round(P):Math.floor(P)))for(var B=0;B<b;B++){var L=B+A;if(!(L<0||L>=l)){var W=O+L*t.strides[2],z=L*m;S===Math.min(a-1,n?Math.round(z):Math.floor(z))&&(N+=f[W+T])}}}}h[k+T]=N}return vn(h,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,i){Kl([t,e,n,o,i],"batchNorm");for(var a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=i?this.readSync(i.dataId):new Float32Array([0]),h=new Float32Array(a.length),f=l.length,p=c.length,d=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b<a.length;++b)h[b]=l[m++]+(a[b]-s[g++])*c[y++]/Math.sqrt(u[x++]+r),m>=f&&(m=0),g>=v&&(g=0),y>=p&&(y=0),x>=d&&(x=0);return vn(h,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){Kl(t,"localResponseNormalization4D");var i=t.shape[3],a=i-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%i,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,a),u=0;r<=o;r++){var c=s[r];u+=c*c}return u}for(var h=0;h<u;h++){var f=l(h),p=s[h]*Math.pow(n+r*f,-o);c[h]=p}return vn(c,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,o,i,a){Kl(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),f=t.size,p=0;p<f;p++){for(var d=p%s,v=p-d+Math.max(0,d-r),m=p-d+Math.min(s,d+r+1),g=0,y=v;y<m;y++)g+=Math.pow(c[y],2);for(g=i*g+o,y=v;y<m;y++){var x=-2*i*a*c[y]*l[p]/g;p===y&&(x+=Math.pow(g,-a)),x*=u[p],h[y]+=x}}return vn(h,t.shape)},e.prototype.multinomial=function(t,e,n,r){Kl(t,"multinomial");for(var o=e?t:Tr(t),i=o.shape[0],a=o.shape[1],s=gn([i,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(o.dataId),l=0;l<i;++l){var h=l*a,f=new Float32Array(a-1);f[0]=c[h];for(var p=1;p<f.length;++p)f[p]=f[p-1]+c[h+p];for(var d=Pn(r.toString()),v=l*n,m=0;m<n;++m){var g=d();u[v+m]=f.length;for(var y=0;y<f.length;y++)if(g<f[y]){u[v+m]=y;break}}}return s},e.prototype.oneHot=function(t,e,n,r){Kl(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var i=this.readSync(t.dataId),a=0;a<t.size;++a)i[a]>=0&&i[a]<e&&(o[a*e+i[a]]=n);return pn(o,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return Kl(t,"nonMaxSuppression"),ao(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=zn(t.shape,"float32"),i=zn(t.shape,"float32"),a=sn(t).as2D(n,r),s=un(t).as2D(n,r),u=0;u<n;u++)for(var c=a.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),h=an(c,l),f=this.readSync(this.fftImpl(h,e).dataId),p=0;p<r;p++){var d=eo(f,p);o.values[u*r+p]=d.real,i.values[u*r+p]=d.imag}return an(o.toTensor(),i.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=an(sn(o).div(hn(r)),un(o).div(hn(r)))),o}var i=this.readSync(t.dataId),a=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(i,r,e));return an(a.real,a.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,i=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),a=an(i.real,i.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=an(s.real,s.imag).as1D();a=this.fftRadix2(a,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 i=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(i),r[o]=Math.sin(i)}return{real:n,imag:r}}(e,n),l=an(c.real,c.imag).mul(u),h=a.add(l),f=a.sub(l),p=sn(h).concat(sn(f)),d=un(h).concat(un(f));return an(p,d).as1D()},e.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var i=0,a=0,s=0;s<e;s++){var u=ro(o*s,e,n),c=eo(t,s);i+=c.real*u.real-c.imag*u.imag,a+=c.real*u.imag+c.imag*u.real}n&&(i/=e,a/=e),no(r,i,a,o)}return r},e.prototype.depthToSpace=function(t,e,n){I("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),I(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],o=t.shape[1],i=t.shape[2],a=t.shape[3],s=o*e,u=i*e,c=a/(e*e),l=this.readSync(t.dataId),h=new Float32Array(r*s*u*c),f=0,p=0;p<r;++p)for(var d=0;d<s;++d)for(var v=Math.floor(d/e),m=d%e,g=0;g<u;++g)for(var y=Math.floor(g/e),x=(m*e+g%e)*c,b=0;b<c;++b){var w=b+x+a*(y+i*(v+o*p));h[f++]=l[w]}return vn(h,[r,s,u,c])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=Lr(t.shape,e.shape),i=zn(o,n),a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Pr(t.shape,o),c=Pr(e.shape,o),l=i.values;if(u.length+c.length===0)for(var h=0;h<l.length;++h)l[h]=r(a[h%a.length],s[h%s.length]);else{var f=this.bufferSync(t),p=this.bufferSync(e),d=function(n){var o=i.indexToLoc(n),h=o.slice(-t.rank);u.forEach((function(t){return h[t]=0}));var d=f.locToIndex(h),v=o.slice(-e.rank);c.forEach((function(t){return v[t]=0}));var m=p.locToIndex(v);l[n]=r(a[d],s[m])};for(h=0;h<l.length;++h)d(h)}return i.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Lr(t.shape,e.shape),o=zn(r,"float32"),i=zn(r,"float32"),a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Pr(t.shape,r),c=Pr(e.shape,r),l=o.values,h=i.values;if(u.length+c.length===0)for(var f=0;f<l.length;f++){var p=f%a.length,d=f%s.length,v=n(a[2*p],a[2*p+1],s[2*d],s[2*d+1]);l[f]=v.real,h[f]=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 i=o.indexToLoc(r),f=i.slice(-t.rank);u.forEach((function(t){return f[t]=0}));var p=m.locToIndex(f),d=i.slice(-e.rank);c.forEach((function(t){return d[t]=0}));var v=g.locToIndex(d),y=n(a[2*p],a[2*p+1],s[2*v],s[2*v+1]);l[r]=y.real,h[r]=y.imag};for(f=0;f<l.length;f++)y(f)}return this.complex(o.toTensor(),i.toTensor())},e.prototype.split=function(t,e,n){return fo(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,i){for(var a=t.shape,s=a[0],u=a[1],c=a[2],l=a[3],h=e.shape[0],f=r[0],p=r[1],d=zn([h,f,p,l],"float32"),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=d.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],_=v[w+2],I=v[w+3],R=m[b];if(!(R>=s))for(var S=f>1?(_-C)*(u-1)/(f-1):0,k=p>1?(I-E)*(c-1)/(p-1):0,D=0;D<f;D++){var A=f>1?C*(u-1)+D*S:.5*(C+_)*(u-1);if(A<0||A>u-1)for(var T=0;T<p;T++)for(var N=0;N<l;N++){var F=N+T*x[2]+D*x[1]+b*x[0];d.values[F]=i}else if("bilinear"===o){var M=Math.floor(A),O=Math.ceil(A),P=A-M;for(T=0;T<p;T++)if((q=p>1?E*(c-1)+T*k:.5*(E+I)*(c-1))<0||q>c-1)for(N=0;N<l;N++)F=N+T*x[2]+D*x[1]+b*x[0],d.values[F]=i;else{var B=Math.floor(q),L=Math.ceil(q),W=q-B;for(N=0;N<l;N++){var z=g[F=N+B*y[2]+M*y[1]+R*y[0]],U=g[F=N+L*y[2]+M*y[1]+R*y[0]],V=g[F=N+B*y[2]+O*y[1]+R*y[0]],G=z+(U-z)*W,H=V+(g[F=N+L*y[2]+O*y[1]+R*y[0]]-V)*W;F=N+T*x[2]+D*x[1]+b*x[0],d.values[F]=G+(H-G)*P}}}else for(T=0;T<p;++T){var q;if((q=p>1?E*(c-1)+T*k:.5*(E+I)*(c-1))<0||q>c-1)for(N=0;N<l;N++)F=N+T*x[2]+D*x[1]+b*x[0],d.values[F]=i;else{var j=Math.round(q),K=Math.round(A);for(N=0;N<l;N++){var X=N+j*y[2]+K*y[1]+R*y[0],Y=N+T*x[2]+D*x[1]+b*x[0];d.values[Y]=g[X]}}}}}return d.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var o=Cr(0,t,n),i=o.sliceRank,a=o.numUpdates,s=o.sliceSize,u=o.strides,c=o.outputSize;return this.scatter(t,e,n,c,s,a,i,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=yr(t,e),i=o[0],a=o[1],s=o[2],u=o[3];if(0===a)return cn([],i,t.dtype);for(var c=new vt([a,s],t.dtype),l=this.readSync(e.dataId),h=this.readSync(t.dataId),f=0;f<a;f++){for(var p=[],d=0,v=0;v<r;v++){var m=l[f*r+v];d+=m*u[v],p.push(m)}if(d<0||d>=t.size/s)throw new Error("Invalid indices: "+p+" does not index into "+t.shape);for(var g=0;g<s;g++)c.values[f*s+g]=h[d*s+g]}return c.toTensor().reshape(i)},e.prototype.scatterND=function(t,e,n){var r=Cr(0,t,n),o=r.sliceRank,i=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,c=hn(0);return this.scatter(t,e,n,u,a,i,o,s,c,!0)},e.prototype.fill=function(t,e,n){var r=z(n=n||$(e),D(t));return r.fill(e),Ot.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=z(t.dtype,D(t.shape));return this.makeOutput(e,t.shape,t.dtype)},e.prototype.linspace=function(t,e,n){return Zr(t,e,n)},e.prototype.scatter=function(t,e,n,r,o,i,a,s,u,c){var l=[r/o,o],h=this.readSync(t.dataId),f=this.readSync(e.dataId);if(0===r)return cn([],n,e.dtype);var p=new vt(l,e.dtype);p.values.fill(this.readSync(u.dataId)[0]);for(var d=0;d<i;d++){for(var v=[],m=0,g=0;g<a;g++){var y=h[d*a+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?p.values[m*o+x]+=f[d*o+x]:p.values[m*o+x]=0===e.rank?f[0]:f[d*o+x]}return p.toTensor().reshape(n)},e}(Mr);Ot.registerBackend("cpu",(function(){return new Yl}),1);for(var $l=0,Jl=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e,i=o.boxes,a=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n;Kl(i,"NonMaxSuppressionWithScore");var p=so(f.data.get(i.dataId).values,f.data.get(a.dataId).values,u,c,l,h);return[p.selectedIndices,p.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n;Kl(r,"square");for(var i=o.data.get(r.dataId).values,a=new Float32Array(i.length),s=0;s<i.length;++s){var u=i[s];a[s]=u*u}return{dataId:o.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:us,backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,i=r.b,a=n;Kl([o,i],us);var s=a.data.get(o.dataId).values,u=a.data.get(i.dataId).values,c=function(t,e,n,r,o,i){var a=Lr(t,e),s=a.length,u=Z(a),c=W(o,D(a)),l=t.length,h=e.length,f=Z(t),p=Z(e),d=Pr(t,a),v=Pr(e,a);if(d.length+v.length===0)for(var m=0;m<c.length;++m)c[m]=i(n[m%n.length],r[m%r.length]);else{var g=function(t){var e=ct(t,s,u),o=e.slice(-l);d.forEach((function(t){return o[t]=0}));var a=ut(o,l,f),m=e.slice(-h);v.forEach((function(t){return m[t]=0}));var g=ut(m,h,p);c[t]=i(n[a],r[g])};for(m=0;m<c.length;++m)g(m)}return[c,a]}(o.shape,i.shape,s,u,o.dtype,(function(t,e){var n=t-e;return n*n})),l=c[0],h=c[1];return{dataId:a.write(l,h,o.dtype),shape:h,dtype:o.dtype}}}];$l<Jl.length;$l++)y(Jl[$l]);for(var Ql,Zl=function(t){this.variableNames=["A"];var e=Co(),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 "},th=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Co(),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 "},eh=0,nh=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e.pixels,i=r.numChannels,a="undefined"!=typeof HTMLVideoElement&&o instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&o instanceof HTMLImageElement,u=a?[o.videoWidth,o.videoHeight]:[o.width,o.height],c=u[0],l=u[1],h=[l,c],p=[l,c,i];(s||a)&&(null==Ql&&(Ql=document.createElement("canvas").getContext("2d")),Ql.canvas.width=c,Ql.canvas.height=l,Ql.drawImage(o,0,0,c,l),o=Ql.canvas);var d=n.makeTensorInfo(h,"int32");n.texData.get(d.dataId).usage=Wt.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),o);var v=f().getBool("WEBGL_PACK")?new th(p):new Zl(p),m=n.runWebGLProgram(v,[d],"int32");return n.disposeData(d.dataId),m}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;Ge("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var o=e,i=o.boxes,a=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n,p=so(f.readSync(i.dataId),f.readSync(a.dataId),u,c,l,h);return[p.selectedIndices,p.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n,i=new Na(r.shape,"return x * x;");return o.runWebGLProgram(i,[r],r.dtype)}},{kernelName:us,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,i=r.b,a=n,s=f().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $o("return (a - b) * (a - b);",o.shape,i.shape):new Xo("return (a - b) * (a - b);",o.shape,i.shape);return a.compileAndRun(s,[o,i])}}];eh<nh.length;eh++)y(nh[eh]);for(var rh=0,oh=[{kernelName:"Square",gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}},{kernelName:us,gradFunc:function(t,e){var n=e[0],r=e[1],o=hn(2);return{a:function(){return _u(t,_u(o,Du(n,r)))},b:function(){return _u(t,_u(o,Du(r,n)))}}}}];rh<oh.length;rh++)x(oh[rh]);var ih=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}();f().get("IS_BROWSER")&&f().setPlatform("browser",new ih);var ah,sh=function(){function t(){this.util=n(24726),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=f().global.fetch?f().global.fetch(t,e):(null==ah&&(ah=n(22591)),ah(t,e))},t.prototype.now=function(){var t=o.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}();f().get("IS_NODE")&&f().setPlatform("node",new sh);var uh={float32:4,int32:4,uint16:2,uint8:1,bool:1};function ch(t,e){for(var n={},r=0,o=function(e){var o=e.name,i=e.dtype,a=e.shape,s=D(a),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=uh[c.dtype],h=t.slice(r,r+s*l),f="uint8"===c.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===i)u=Float32Array.from(f,(function(t){return t*c.scale+c.min}));else{if("int32"!==i)throw new Error("Unsupported dtype in weight '"+o+"': "+i);u=Int32Array.from(f,(function(t){return Math.round(t*c.scale+c.min)}))}r+=s*l}else if("string"===i){var p=D(e.shape);u=[];for(var d=0;d<p;d++){var v=new Uint32Array(t.slice(r,r+4))[0];r+=4;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v}}else{var g=uh[i];if(h=t.slice(r,r+s*g),"float32"===i)u=new Float32Array(h);else if("int32"===i)u=new Int32Array(h);else{if("bool"!==i)throw new Error("Unsupported dtype in weight '"+o+"': "+i);u=new Uint8Array(h)}r+=s*g}n[o]=cn(u,a,i)},i=0,a=e;i<a.length;i++)o(a[i]);return n}function lh(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 hh=void 0!==i&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function fh(t){return hh?i.byteLength(t):new Blob([t]).size}function ph(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 dh(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function vh(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:fh(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:fh(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var mh=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}(),gh="://",yh=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){I(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(gh)&&(e=e.slice(0,e.indexOf(gh))),I(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();I(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 xh(t){if(-1===t.indexOf(gh))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+yh.getSchemes().join(","));return{scheme:t.split(gh)[0],path:t.split(gh)[1]}}function bh(t,e,n){return void 0===n&&(n=!1),u(this,void 0,void 0,(function(){var r,o,i,a,s,u,l,h,f;return c(this,(function(c){switch(c.label){case 0:return I(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),I((r=mh.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),I(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."})),o=r[0],I((i=mh.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),I(i.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."})),a=i[0],s=xh(t).scheme,u=xh(t).path,l=s===xh(t).scheme,[4,o.load()];case 1:return h=c.sent(),n&&l?[4,yh.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,a.save(h)];case 4:return f=c.sent(),!n||l?[3,6]:[4,yh.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,f.modelArtifactsInfo]}}))}))}var wh="models_store",Ch="model_info_store";function Eh(){if(!f().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 _h(t){var e=t.result;e.createObjectStore(wh,{keyPath:"modelPath"}),e.createObjectStore(Ch,{keyPath:"modelPath"})}var Ih=function(){function t(t){if(this.indexedDB=Eh(),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 u(this,void 0,void 0,(function(){return c(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 u(this,void 0,void 0,(function(){return c(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 _h(o)},o.onsuccess=function(){var i=o.result;if(null==e){var a=i.transaction(wh,"readonly"),s=a.objectStore(wh).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return i.close(),r(s.error)},a.oncomplete=function(){return i.close()}}else{var u,c=vh(e),l=i.transaction(Ch,"readwrite"),h=l.objectStore(Ch),f=h.put({modelPath:n.modelPath,modelArtifactsInfo:c});f.onsuccess=function(){var o=(u=i.transaction(wh,"readwrite")).objectStore(wh).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(h=l.objectStore(Ch)).delete(n.modelPath);e.onsuccess=function(){return i.close(),r(o.error)},e.onerror=function(t){return i.close(),r(o.error)}}},f.onerror=function(t){return i.close(),r(f.error)},l.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},o.onerror=function(t){return r(o.error)}}))},t.URL_SCHEME="indexeddb://",t}(),Rh=function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Ih.URL_SCHEME)?(e=t.slice(Ih.URL_SCHEME.length),new Ih(e)):null;var e};mh.registerSaveRouter(Rh),mh.registerLoadRouter(Rh);var Sh=function(){function t(){this.indexedDB=Eh()}return t.prototype.listModels=function(){return u(this,void 0,void 0,(function(){var t=this;return c(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return _h(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(Ch,"readonly"),i=o.objectStore(Ch).getAll();i.onsuccess=function(){for(var t={},n=0,r=i.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo}e(t)},i.onerror=function(e){return t.close(),n(i.error)},o.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}}))]}))}))},t.prototype.removeModel=function(t){return u(this,void 0,void 0,(function(){var e=this;return c(this,(function(n){var r;return t=(r=t).startsWith(Ih.URL_SCHEME)?r.slice(Ih.URL_SCHEME.length):r,[2,new Promise((function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return _h(o)},o.onsuccess=function(){var e,i=o.result,a=i.transaction(Ch,"readwrite"),s=a.objectStore(Ch),u=s.get(t);u.onsuccess=function(){if(null==u.result)return i.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),a=function(){var o=(e=i.transaction(wh,"readwrite")).objectStore(wh).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo)},o.onerror=function(t){return r(u.error)}};o.onsuccess=a,o.onerror=function(t){return a(),i.close(),r(u.error)}},u.onerror=function(t){return i.close(),r(u.error)},a.oncomplete=function(){null==e?i.close():e.oncomplete=function(){return i.close()}}},o.onerror=function(t){return r(o.error)}}))]}))}))},t}();if(f().getBool("IS_BROWSER"))try{yh.registerManager(Ih.URL_SCHEME,new Sh)}catch(a){}var kh="/",Dh="tensorflowjs_models",Ah="info",Th="model_topology",Nh="weight_specs",Fh="weight_data",Mh="model_metadata";function Oh(t){return{info:[Dh,t,Ah].join(kh),topology:[Dh,t,Th].join(kh),weightSpecs:[Dh,t,Nh].join(kh),weightData:[Dh,t,Fh].join(kh),modelMetadata:[Dh,t,Mh].join(kh)}}function Ph(t){var e=t.split(kh);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(kh)}var Bh=function(){function t(t){if(!f().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=Oh(this.modelPath)}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){var e,n,r;return c(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=vh(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(hh)return i.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 u(this,void 0,void 0,(function(){var t,e,n,r,o,a,s;return c(this,(function(u){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!=(o=this.LS.getItem(this.keys.modelMetadata))&&(a=JSON.parse(o),e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy,e.userDefinedMetadata=a.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(hh){var e=i.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}(),Lh=function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Bh.URL_SCHEME)?(e=t.slice(Bh.URL_SCHEME.length),new Bh(e)):null;var e};mh.registerSaveRouter(Lh),mh.registerLoadRouter(Lh);var Wh=function(){function t(){I(f().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),I("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 u(this,void 0,void 0,(function(){var t,e,n,r,o,i;return c(this,(function(a){for(t={},e=Dh+kh,n=kh+Ah,r=0;r<this.LS.length;++r)(o=this.LS.key(r)).startsWith(e)&&o.endsWith(n)&&(i=Ph(o),t[i]=JSON.parse(this.LS.getItem(o)));return[2,t]}))}))},t.prototype.removeModel=function(t){return u(this,void 0,void 0,(function(){var e,n;return c(this,(function(r){var o;if(t=(o=t).startsWith(Bh.URL_SCHEME)?o.slice(Bh.URL_SCHEME.length):o,e=Oh(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(f().getBool("IS_BROWSER"))try{yh.registerManager(Bh.URL_SCHEME,new Wh)}catch(a){}function zh(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var Uh=function(){function t(e){if(!f().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="model"),this.modelTopologyFileName=e+".json",this.weightDataFileName=e+".weights.bin"}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){var e,n,r,o,i,a;return c(this,(function(s){switch(s.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},o=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=o,[4,zh((function(){return i.dispatchEvent(new MouseEvent("click"))}))];case 2:return s.sent(),null==t.weightData?[3,4]:((a=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,a.href=e,[4,zh((function(){return a.dispatchEvent(new MouseEvent("click"))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:vh(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),Vh=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 u(this,void 0,void 0,(function(){var t,e,n=this;return c(this,(function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(r,o){var i=new FileReader;i.onload=function(i){var a=JSON.parse(i.target.result),s=a.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=a.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var l=[],h=[],f=[];u.forEach((function(t){t.paths.forEach((function(t){h.push(t),f.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);f[o]=n,-1===f.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:ph(f),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.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))},i.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.")},i.readAsText(t)}))]}))}))},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map((function(t){return dh(t.name)})),o={},i=0,a=t;i<a.length;i++)a[i].paths.forEach((function(t){var i=dh(t);if(-1!==n.indexOf(i))throw new Error("Duplicate file basename found in weights manifest: '"+i+"'");if(n.push(i),-1===r.indexOf(i))throw new Error("Weight file with basename '"+i+"' is not provided.");o[t]=e[r.indexOf(i)]}));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 Gh(t,e,n,r){!function(t){I(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){I(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),I(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),I(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(i){return i.then((function(i){var a=n+ ++o/t.length*(r-n);return e(a),i})),i})))}function Hh(t,e){return u(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,l,h;return c(this,(function(c){switch(c.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?f().platform.fetch:e.fetchFunc,r=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),o=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return a=c.sent(),[3,4];case 2:return[4,Gh(r,e.onProgress,o,i)];case 3:a=c.sent(),c.label=4;case 4:return s=a.map((function(t){return t.arrayBuffer()})),u=.5,l=1,null!=e.onProgress?[3,6]:[4,Promise.all(s)];case 5:return h=c.sent(),[3,8];case 6:return[4,Gh(s,e.onProgress,u,l)];case 7:h=c.sent(),c.label=8;case 8:return[2,h]}}))}))}function qh(t){var e=this;return function(n,r,o){return void 0===r&&(r=""),u(e,void 0,void 0,(function(){var e,i,a,s,u,l,h,f,p,d;return c(this,(function(c){switch(c.label){case 0:if(e=n.map((function(){return!1})),i={},a=null!=o?o.map((function(){return!1})):[],s=[],n.forEach((function(t,n){var r=0;t.weights.forEach((function(t){var u="quantization"in t?t.quantization.dtype:t.dtype,c=uh[u]*D(t.shape),l=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=o?o.forEach((function(e,n){e===t.name&&(l(),a[n]=!0)})):l(),s.push(t.name),r+=c}))})),!a.every((function(t){return t})))throw u=o.filter((function(t,e){return!a[e]})),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.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=r+(r.endsWith("/")?"":"/")+t;h.push(e)}))})),[4,t(h)];case 1:return f=c.sent(),p={},d=0,l.forEach((function(t){for(var e=n[t].paths.length,r=0,o=0;o<e;o++)r+=f[d+o].byteLength;for(var a=new ArrayBuffer(r),s=new Uint8Array(a),u=0,c=0;c<e;c++){var l=new Uint8Array(f[d+c]);s.set(l,u),u+=l.byteLength}i[t].forEach((function(t){var e=ch(a.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)p[n]=e[n]})),d+=e})),[2,p]}}))}))}}mh.registerSaveRouter((function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Uh.URL_SCHEME)?function(t){return void 0===t&&(t="model"),new Uh(t)}(t.slice(Uh.URL_SCHEME.length)):null}));var jh=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(I("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=f().platform.fetch,I(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&I(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 u(this,void 0,void 0,(function(){var e,n,r,o;return c(this,(function(i){switch(i.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((o=i.sent()).ok)return[2,{modelArtifactsInfo:vh(t),responses:[o]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}}))}))},t.prototype.load=function(){return u(this,void 0,void 0,(function(){var t,e,n,r,o,i,a,s,u,l,h,f;return c(this,(function(c){switch(c.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=c.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.");c.label=2;case 2:return c.trys.push([2,4,,5]),[4,t.json()];case 3:return e=c.sent(),[3,5];case 4:throw c.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,o=e.weightsManifest,i=e.generatedBy,a=e.convertedBy,s=e.format,u=e.userDefinedMetadata,null==r&&null==o)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==o?[3,7]:[4,this.loadWeights(o)];case 6:f=c.sent(),l=f[0],h=f[1],c.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:h,userDefinedMetadata:u,generatedBy:i,convertedBy:a,format:s}]}}))}))},t.prototype.loadWeights=function(t){return u(this,void 0,void 0,(function(){var e,n,r,o,i,a,s,u,l,h,f;return c(this,(function(c){switch(c.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],o=n[1],i=this.weightPathPrefix||r,a=[],s=0,u=t;s<u.length;s++)l=u[s],a.push.apply(a,l.weights);return h=[],t.forEach((function(t){t.paths.forEach((function(t){h.push(i+t+o)}))})),[4,Hh(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=c.sent(),[2,[a,ph(f)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function Kh(t){return null!=t.match(jh.URL_SCHEME_REGEX)}var Xh=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every((function(t){return Kh(t)})):Kh(t))?Yh(t,{onProgress:e}):null};function Yh(t,e){return new jh(t,e)}mh.registerSaveRouter(Xh),mh.registerLoadRouter(Xh);var $h,Jh=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){return[2,this.modelArtifacts]}))}))},t}(),Qh=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(e){return[2,this.saveHandler(t)]}))}))},t}(),Zh=Object.freeze({browserFiles:function(t){return new Vh(t)},browserHTTPRequest:function(t,e){return Yh(t,e)},concatenateArrayBuffers:ph,decodeWeights:ch,encodeWeights:function(t,e){return u(this,void 0,void 0,(function(){var n,r,o,i,a,s=this;return c(this,(function(l){switch(l.label){case 0:for(n=[],r=[],o=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t),i=function(i){var a=o[i],l=Array.isArray(t)?t[i].tensor:t[a];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+a+"': "+l.dtype);var h={name:a,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var f=new Promise((function(t){return u(s,void 0,void 0,(function(){var e,n,r,o,i,a,s;return c(this,(function(u){switch(u.label){case 0:return[4,l.bytes()];case 1:for(e=u.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+4*e.length,r=new Uint8Array(n),o=0,i=0;i<e.length;i++)a=e[i],s=new Uint8Array(new Uint32Array([a.length]).buffer),r.set(s,o),o+=4,r.set(a,o),o+=a.length;return t(r),[2]}}))}))}));r.push(f)}else r.push(l.data());null!=e&&(h.group=e),n.push(h)},a=0;a<o.length;++a)i(a);return[4,Promise.all(r)];case 1:return[2,{data:lh(l.sent()),specs:n}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Jh(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 Jh({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 Jh({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return mh.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:vh,getSaveHandlers:function(t){return mh.getSaveHandlers(t)},http:Yh,isHTTPScheme:Kh,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),u(this,void 0,void 0,(function(){return c(this,(function(o){return[2,qh((function(t){return Hh(t,{requestInit:r})}))(t,e,n)]}))}))},registerLoadRouter:function(t){return mh.registerLoadRouter(t)},registerSaveRouter:function(t){return mh.registerSaveRouter(t)},weightsLoaderFactory:qh,withSaveHandler:function(t){return new Qh(t)},copyModel:function(t,e){return u(this,void 0,void 0,(function(){return c(this,(function(n){return[2,bh(t,e,!1)]}))}))},listModels:function(){return u(this,void 0,void 0,(function(){var t,e,n,r,o,i,a;return c(this,(function(s){switch(s.label){case 0:t=yh.getSchemes(),e={},n=0,r=t,s.label=1;case 1:return n<r.length?(o=r[n],[4,yh.getManager(o).listModels()]):[3,4];case 2:for(a in i=s.sent())e[o+gh+a]=i[a];s.label=3;case 3:return n++,[3,1];case 4:return[2,e]}}))}))},moveModel:function(t,e){return u(this,void 0,void 0,(function(){return c(this,(function(n){return[2,bh(t,e,!0)]}))}))},removeModel:function(t){return u(this,void 0,void 0,(function(){var e;return c(this,(function(n){return e=xh(t),[2,yh.getManager(e.scheme).removeModel(e.path)]}))}))}}),tf=on({confusionMatrix_:function(t,e,n){var r=je(t,"labels","confusionMatrix"),o=je(e,"predictions","confusionMatrix");I(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),I(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),I(1===o.rank,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),I(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."})),I(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var i=$n(r.asType("int32"),n),a=$n(o.asType("int32"),n);return i.transpose().matMul(a).asType("int32")}}),ef=(Object.freeze({confusionMatrix:tf}),on({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,i=!1,a=!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)i=!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);a=!0}if(o&&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!=m("FromPixels",Ot.backendName))return Ot.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,c=o?[t.videoWidth,t.videoHeight]:[t.width,t.height],l=c[0],h=c[1];if(a?s=t.getContext("2d").getImageData(0,0,l,h).data:r||n?s=t.data:(i||o)&&(null==$h&&($h=document.createElement("canvas").getContext("2d")),$h.canvas.width=l,$h.canvas.height=h,$h.drawImage(t,0,0,l,h),s=$h.getImageData(0,0,l,h).data),4===e)u=new Int32Array(s);else{var f=l*h;u=new Int32Array(f*e);for(var p=0;p<f;p++)for(var d=0;d<e;++d)u[p*e+d]=s[4*p+d]}return dn(u,[h,l,e],"int32")}})),nf=Object.freeze({toPixels:function(t,e){return u(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,l,h,f,p,d,v,m,g,y,x,b,w,C,E,_,I;return c(this,(function(c){switch(c.label){case 0:if(n=je(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),o=r[0],i=r[1],(a=2===n.rank?1:n.shape[2])>4||2===a)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+a);return[4,n.data()];case 1:return s=c.sent(),u=n.min(),l=n.max(),[4,Promise.all([u.data(),l.data()])];case 2:if(h=c.sent(),f=h[0],p=h[1],d=f[0],v=p[0],u.dispose(),l.dispose(),"float32"===n.dtype){if(d<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*o*4),y=0;y<o*i;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===a?(x=s[y]*m,b=s[y]*m,w=s[y]*m,C=255):3===a?(x=s[3*y]*m,b=s[3*y+1]*m,w=s[3*y+2]*m,C=255):4===a&&(x=s[4*y]*m,b=s[4*y+1]*m,w=s[4*y+2]*m,C=s[4*y+3]*m),g[0+(E=4*y)]=Math.round(x),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=i,e.height=o,_=e.getContext("2d"),I=new ImageData(g,i,o),_.putImageData(I,0,0)),n!==t&&n.dispose(),[2,g]}}))}))},fromPixels:ef}),rf=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),of=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 af(t){I(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),I("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),I(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),of.register(t)}Object.freeze({Serializable:rf,SerializationMap:of,registerClass:af});function sf(){return 32===Ot.backend.floatPrecision()?.001:.1}function uf(t,e,n){var r=!0;if((H(t)||H(e))&&(r=!1),H(t)&&H(e)&&(r=!0),r){var o=t.constructor.name,i=e.constructor.name;if(o!==i)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+i)}if(Array.isArray(t)&&Array.isArray(e)){var a=He(t),s=He(e);if(!A(a,s))throw new Error("Arrays have different shapes. Actual: ["+a+"]. Expected: ["+s+"]")}var u=H(t)?t:k(t),c=H(e)?e:k(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],f=c[l];if(!n(h,f))throw new Error("Arrays differ: actual["+l+"] = "+h+", expected["+l+"] = "+f+".\nActual: "+u+".\nExpected: "+c+".")}}function cf(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}Object.freeze({TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(t,e,n){return null==n&&(n=sf()),uf(t,e,(function(t,e){return cf(t,e,n)}))},testEpsilon:sf,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 K(t)||K(t[0])||K(e)||K(e[0])?uf(t,n,(function(t,e){return t==e})):uf(t,e,(function(t,e){return cf(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=sf()),!cf(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))}}),Object.freeze({gpgpu_util:qi,webgl_util:Le,forceHalfFloat:function(){f().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:as,setWebGLContext:Gt,GPGPUContext:ji});var lf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,i=r.grads;if(null!=n){var a=n.map((function(t){return{name:t.name,tensor:i[t.name]}}));this.applyGradients(a)}else this.applyGradients(i);return Ve(i),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 function(t,e){I(J(t),(function(){return"The f passed in variableGrads(f) must be a function"})),I(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=[],Ot.registeredVariables)e.push(Ot.registeredVariables[r]);var o=n?e.filter((function(t){return!t.trainable})):null,i=e.length;I((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 "+i+" variables is trainable."}));var a=Ot.gradients(t,e,null,!0),s=a.value,u=a.grads;I(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()."})),I(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}}(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Ve(this.iterations_)},e.prototype.saveIterations=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:hn(this.iterations_,"int32")}]}))}))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},e.prototype.extractIterations=function(t){return u(this,void 0,void 0,(function(){var e;return c(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}(rf);Object.defineProperty(lf,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var hf=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=Ot.backend.epsilon()),o}return s(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=Ot.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Ue((function(){return wn(o).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Ue((function(){return wn(o).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Ue((function(){var t=a.mul(e.rho).add(i.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(a.add(e.epsilon).sqrt()).mul(i),r=s.mul(e.rho).add(n.square().mul(1-e.rho));a.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&&(Ve(this.accumulatedGrads.map((function(t){return t.variable}))),Ve(this.accumulatedUpdates.map((function(t){return t.variable}))))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(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 u(this,void 0,void 0,(function(){var e;return c(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,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}(lf);af(hf);var ff=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 s(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=Ot.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Ue((function(){return yn(o.shape,e.initialAccumulatorValue).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedGrads[r].variable;Ue((function(){var t=a.add(i.square());a.assign(t);var n=i.div(t.add(Ot.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Ve(this.accumulatedGrads.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(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 u(this,void 0,void 0,(function(){return c(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),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}(lf);af(ff);var pf=function(t){function e(e,n,r,o){void 0===o&&(o=null);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],Ue((function(){i.accBeta1=hn(n).variable(),i.accBeta2=hn(r).variable()})),null==o&&(i.epsilon=Ot.backend.epsilon()),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ue((function(){var r=Du(1,e.accBeta1),o=Du(1,e.accBeta2);n.forEach((function(n,i){var a=Ot.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:Ue((function(){return wn(a).variable(!1)}))}),null==e.accumulatedSecondMoment[i]&&(e.accumulatedSecondMoment[i]={originalName:n+"/v",variable:Ue((function(){return wn(a).variable(!1)}))});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,c=e.accumulatedSecondMoment[i].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),f=l.div(r),p=h.div(o);u.assign(l),c.assign(h);var d=f.div(p.sqrt().add(e.epsilon)).mul(-e.learningRate).add(a);a.assign(d)}})),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&&Ve(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&Ve(this.accumulatedSecondMoment.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(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 u(this,void 0,void 0,(function(){var e,n=this;return c(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Ue((function(){n.accBeta1.assign(Ru(n.beta1,n.iterations_+1)),n.accBeta2.assign(Ru(n.beta2,n.iterations_+1))})),e=t.length/2,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}(lf);af(pf);var df=function(t){function e(e,n,r,o,i){void 0===o&&(o=null),void 0===i&&(i=0);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.decay=i,a.accumulatedFirstMoment=[],a.accumulatedWeightedInfNorm=[],Ue((function(){a.iteration=hn(0).variable(),a.accBeta1=hn(n).variable()})),null==o&&(a.epsilon=Ot.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ue((function(){var r=Du(1,e.accBeta1),o=du(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,i){var a=Ot.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:wn(a).variable(!1)}),null==e.accumulatedWeightedInfNorm[i]&&(e.accumulatedWeightedInfNorm[i]={originalName:n+"/v",variable:wn(a).variable(!1)});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,c=e.accumulatedWeightedInfNorm[i].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2),f=s.abs(),p=h.maximum(f);u.assign(l),c.assign(p);var d=o.div(r).mul(l.div(p.add(e.epsilon))).add(a);a.assign(d)}})),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&&Ve(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&Ve(this.accumulatedWeightedInfNorm.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(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}(lf);af(df);var vf=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return s(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 i=Ot.registeredVariables[n];Ue((function(){var t=e.c.mul(o).add(i);i.assign(t)}))}})),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=function(t){return Ot.keep(t)}(hn(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}}))}))},e.prototype.setWeights=function(t){return u(this,void 0,void 0,(function(){return c(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}(lf);af(vf);var mf=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=hn(o.momentum),o}return s(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=Ot.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:Ue((function(){return wn(o).variable(!1)}))});var i=e.accumulations[r].variable,a=Array.isArray(t)?t[r].tensor:t[n];null!=a&&Ue((function(){var t,n=e.m.mul(i).add(a);t=e.useNesterov?e.c.mul(a.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),i.assign(n),o.assign(t)}))})),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Ve(this.accumulations.map((function(t){return t.variable})))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return c(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 u(this,void 0,void 0,(function(){return c(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),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}(vf);af(mf);var gf=function(t){function e(e,n,r,o,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===i&&(i=!1);var a=t.call(this)||this;if(a.learningRate=e,a.decay=n,a.momentum=r,a.epsilon=o,a.accumulatedMeanSquares=[],a.accumulatedMoments=[],a.accumulatedMeanGrads=[],a.centered=i,null==o&&(a.epsilon=Ot.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.");return a}return s(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=Ot.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Ue((function(){return wn(o).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Ue((function(){return wn(o).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Ue((function(){return wn(o).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Ue((function(){var t=a.mul(e.decay).add(i.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(i.mul(1-e.decay)),c=s.mul(e.momentum).add(i.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));a.assign(t),n.assign(u),s.assign(c);var l=o.sub(c);o.assign(l)}else{var h=a.mul(e.decay).add(i.square().mul(1-e.decay));c=s.mul(e.momentum).add(i.mul(e.learningRate).div(h.add(e.epsilon).sqrt())),a.assign(h),s.assign(c),l=o.sub(c),o.assign(l)}}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Ve(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&Ve(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&Ve(this.accumulatedMoments.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var t;return c(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 u(this,void 0,void 0,(function(){var e;return c(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,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}(lf);af(gf);var yf=function(){function t(){}return t.sgd=function(t){return new vf(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new mf(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 gf(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 pf(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 hf(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 df(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new ff(t,e)},t}();yf.sgd,yf.momentum,yf.adadelta,yf.adagrad,yf.rmsprop,yf.adamax,yf.adam,"undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate&&setImmediate;function xf(t,e,n){if(void 0===n&&(n=!1),t.beginPath(),e.slice(1).forEach((function(n,r){var o=n.x,i=n.y,a=e[r];t.moveTo(a.x,a.y),t.lineTo(o,i)})),n){var r=e[e.length-1],o=e[0];if(!r||!o)return;t.moveTo(r.x,r.y),t.lineTo(o.x,o.y)}t.stroke()}xt.prototype.squaredDifference=function(t){return cs(this,t)},gt=jl;n(31468);var bf=function(t,e){return bf=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])},bf(t,e)};function wf(t,e){function n(){this.constructor=t}bf(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var Cf=function(){return Cf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},Cf.apply(this,arguments)};function Ef(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}u((r=r.apply(t,e||[])).next())}))}function _f(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=e.call(t,a)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function If(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;var r=Array(t),o=0;for(e=0;e<n;e++)for(var i=arguments[e],a=0,s=i.length;a<s;a++,o++)r[o]=i[a];return r}var Rf=function(){function t(t,e){if(!Of(t)||!Of(e))throw new Error("Dimensions.constructor - expected width and height to be valid numbers, instead have "+JSON.stringify({width:t,height:e}));this._width=t,this._height=e}return Object.defineProperty(t.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),t.prototype.reverse=function(){return new t(1/this.width,1/this.height)},t}();function Sf(t,e){return t instanceof xt&&t.shape.length===e}function kf(t){return Sf(t,3)}function Df(t){return Sf(t,4)}function Af(t){return t%2==0}function Tf(t,e){void 0===e&&(e=2);var n=Math.pow(10,e);return Math.floor(t*n)/n}function Nf(t){return t&&t.width&&t.height}function Ff(t){return t.reduce((function(t,e){return t.add(e)}),new Bf(0,0)).div(new Bf(t.length,t.length))}function Mf(t,e,n){return Array(t).fill(0).map((function(t,r){return e+r*n}))}function Of(t){return!!t&&t!==1/0&&t!==-1/0&&!isNaN(t)||0===t}function Pf(t){return Of(t)&&0<=t&&t<=1}var Bf=function(){function t(t,e){this._x=t,this._y=e}return Object.defineProperty(t.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),t.prototype.add=function(e){return new t(this.x+e.x,this.y+e.y)},t.prototype.sub=function(e){return new t(this.x-e.x,this.y-e.y)},t.prototype.mul=function(e){return new t(this.x*e.x,this.y*e.y)},t.prototype.div=function(e){return new t(this.x/e.x,this.y/e.y)},t.prototype.abs=function(){return new t(Math.abs(this.x),Math.abs(this.y))},t.prototype.magnitude=function(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))},t.prototype.floor=function(){return new t(Math.floor(this.x),Math.floor(this.y))},t}(),Lf=function(){function t(e,n){void 0===n&&(n=!0);var r=e||{},o=[r.left,r.top,r.right,r.bottom].every(Of),i=[r.x,r.y,r.width,r.height].every(Of);if(!i&&!o)throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have "+JSON.stringify(r));var a=i?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top],s=a[0],u=a[1],c=a[2],l=a[3];t.assertIsValidBox({x:s,y:u,width:c,height:l},"Box.constructor",n),this._x=s,this._y=u,this._width=c,this._height=l}return t.isRect=function(t){return!!t&&[t.x,t.y,t.width,t.height].every(Of)},t.assertIsValidBox=function(e,n,r){if(void 0===r&&(r=!1),!t.isRect(e))throw new Error(n+" - invalid box: "+JSON.stringify(e)+", expected object with properties x, y, width, height");if(!r&&(e.width<0||e.height<0))throw new Error(n+" - width ("+e.width+") and height ("+e.height+") must be positive numbers")},Object.defineProperty(t.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"top",{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottom",{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"area",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topLeft",{get:function(){return new Bf(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"topRight",{get:function(){return new Bf(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottomLeft",{get:function(){return new Bf(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bottomRight",{get:function(){return new Bf(this.right,this.bottom)},enumerable:!0,configurable:!0}),t.prototype.round=function(){var e=[this.x,this.y,this.width,this.height].map((function(t){return Math.round(t)}));return new t({x:e[0],y:e[1],width:e[2],height:e[3]})},t.prototype.floor=function(){var e=[this.x,this.y,this.width,this.height].map((function(t){return Math.floor(t)}));return new t({x:e[0],y:e[1],width:e[2],height:e[3]})},t.prototype.toSquare=function(){var e=this,n=e.x,r=e.y,o=e.width,i=e.height,a=Math.abs(o-i);return o<i&&(n-=a/2,o+=a),i<o&&(r-=a/2,i+=a),new t({x:n,y:r,width:o,height:i})},t.prototype.rescale=function(e){var n=Nf(e)?e.width:e,r=Nf(e)?e.height:e;return new t({x:this.x*n,y:this.y*r,width:this.width*n,height:this.height*r})},t.prototype.pad=function(e,n){var r=[this.x-e/2,this.y-n/2,this.width+e,this.height+n];return new t({x:r[0],y:r[1],width:r[2],height:r[3]})},t.prototype.clipAtImageBorders=function(e,n){var r=this,o=r.x,i=r.y,a=r.right,s=r.bottom,u=Math.max(o,0),c=Math.max(i,0),l=a-u,h=s-c;return new t({x:u,y:c,width:Math.min(l,e-u),height:Math.min(h,n-c)}).floor()},t.prototype.shift=function(e,n){var r=this.width,o=this.height;return new t({x:this.x+e,y:this.y+n,width:r,height:o})},t.prototype.padAtBorders=function(t,e){var n=this.width+1,r=this.height+1,o=n,i=r,a=this.left,s=this.top,u=this.right,c=this.bottom;return u>e&&(o=-u+e+n,u=e),c>t&&(i=-c+t+r,c=t),a<1&&(i=2-a,a=1),s<1&&(i=2-s,s=1),{dy:1,edy:i,dx:1,edx:o,y:s,ey:c,x:a,ex:u,w:n,h:r}},t.prototype.calibrate=function(e){return new t({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()},t}(),Wf=function(t){function e(e,n,r,o,i){return void 0===i&&(i=!1),t.call(this,{left:e,top:n,right:r,bottom:o},i)||this}return wf(e,t),e}(Lf),zf=function(){function t(t,e,n,r,o){this._imageDims=new Rf(o.width,o.height),this._score=t,this._classScore=e,this._className=n,this._box=new Lf(r).rescale(this._imageDims)}return Object.defineProperty(t.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"box",{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageDims",{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageWidth",{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageHeight",{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relativeBox",{get:function(){return new Lf(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),t.prototype.forSize=function(e,n){return new t(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:n})},t}(),Uf=function(t){function e(e,n,r){return t.call(this,e,e,"",n,r)||this}return wf(e,t),e.prototype.forSize=function(n,r){var o=t.prototype.forSize.call(this,n,r);return new e(o.score,o.relativeBox,o.imageDims)},e}(zf);function Vf(t,e,n){void 0===n&&(n=!0);var r=Math.max(0,Math.min(t.right,e.right)-Math.max(t.left,e.left))*Math.max(0,Math.min(t.bottom,e.bottom)-Math.max(t.top,e.top));return n?r/(t.area+e.area-r):r/Math.min(t.area,e.area)}function Gf(t,e,n,r){void 0===r&&(r=!0);for(var o=e.map((function(t,e){return{score:t,boxIndex:e}})).sort((function(t,e){return t.score-e.score})).map((function(t){return t.boxIndex})),i=[],a=function(){var e=o.pop();i.push(e);for(var a=o,s=[],u=0;u<a.length;u++){var c=a[u],l=t[e],h=t[c];s.push(Vf(l,h,r))}o=o.filter((function(t,e){return s[e]<=n}))};o.length>0;)a();return i}function Hf(t,e){return Ue((function(){var n=e[0],r=e[1],o=e[2],i=yn(If(t.shape.slice(0,3),[1]),n),a=yn(If(t.shape.slice(0,3),[1]),r),s=yn(If(t.shape.slice(0,3),[1]),o),u=Cn([i,a,s],3);return Du(t,u)}))}function qf(t){return 1/(1+Math.exp(-t))}var jf=function(t){function e(e,n,r,o,i){return void 0===i&&(i=!1),t.call(this,{x:e,y:n,width:r,height:o},i)||this}return wf(e,t),e}(Lf),Kf=function(){function t(t,e,n){void 0===n&&(n=new Bf(0,0));var r=e.width,o=e.height;this._imgDims=new Rf(r,o),this._shift=n,this._positions=t.map((function(t){return t.mul(new Bf(r,o)).add(n)}))}return Object.defineProperty(t.prototype,"shift",{get:function(){return new Bf(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageWidth",{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageHeight",{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positions",{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relativePositions",{get:function(){var t=this;return this._positions.map((function(e){return e.sub(t._shift).div(new Bf(t.imageWidth,t.imageHeight))}))},enumerable:!0,configurable:!0}),t.prototype.forSize=function(t,e){return new this.constructor(this.relativePositions,{width:t,height:e})},t.prototype.shiftBy=function(t,e){return new this.constructor(this.relativePositions,this._imgDims,new Bf(t,e))},t.prototype.shiftByPoint=function(t){return this.shiftBy(t.x,t.y)},t.prototype.align=function(t,e){if(void 0===e&&(e={}),t){var n=t instanceof Uf?t.box.floor():new Lf(t);return this.shiftBy(n.x,n.y).align(null,e)}var r=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},e),o=r.useDlibAlignment,i=r.minBoxPadding;return o?this.alignDlib():this.alignMinBbox(i)},t.prototype.alignDlib=function(){var t=this.getRefPointsForAlignment(),e=t[0],n=t[1],r=t[2],o=function(t){return r.sub(t).magnitude()},i=(o(e)+o(n))/2,a=Math.floor(i/.45),s=Ff(t),u=Math.floor(Math.max(0,s.x-.5*a)),c=Math.floor(Math.max(0,s.y-.43*a));return new jf(u,c,Math.min(a,this.imageWidth+u),Math.min(a,this.imageHeight+c))},t.prototype.alignMinBbox=function(t){var e=function(t){var e=t.map((function(t){return t.x})),n=t.map((function(t){return t.y})),r=e.reduce((function(t,e){return e<t?e:t}),1/0),o=n.reduce((function(t,e){return e<t?e:t}),1/0),i=e.reduce((function(t,e){return t<e?e:t}),0),a=n.reduce((function(t,e){return t<e?e:t}),0);return new Wf(r,o,i,a)}(this.positions);return e.pad(e.width*t,e.height*t)},t.prototype.getRefPointsForAlignment=function(){throw new Error("getRefPointsForAlignment not implemented by base class")},t}(),Xf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.getRefPointsForAlignment=function(){var t=this.positions;return[t[0],t[1],Ff([t[3],t[4]])]},e}(Kf),Yf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.getJawOutline=function(){return this.positions.slice(0,17)},e.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},e.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},e.prototype.getNose=function(){return this.positions.slice(27,36)},e.prototype.getLeftEye=function(){return this.positions.slice(36,42)},e.prototype.getRightEye=function(){return this.positions.slice(42,48)},e.prototype.getMouth=function(){return this.positions.slice(48,68)},e.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Ff)},e}(Kf),$f=function(){function t(t,e){this._label=t,this._distance=e}return Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distance",{get:function(){return this._distance},enumerable:!0,configurable:!0}),t.prototype.toString=function(t){return void 0===t&&(t=!0),this.label+(t?" ("+Tf(this.distance)+")":"")},t}(),Jf=function(t){function e(e,n){var r=t.call(this,e)||this;return r._label=n,r}return wf(e,t),e.assertIsValidLabeledBox=function(t,e){if(Lf.assertIsValidBox(t,e),!Of(t.label))throw new Error(e+" - expected property label ("+t.label+") to be a number")},Object.defineProperty(e.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),e}(Lf),Qf=function(){function t(t,e){if("string"!=typeof t)throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(e)||e.some((function(t){return!(t instanceof Float32Array)})))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=e}return Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"descriptors",{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),t.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map((function(t){return Array.from(t)}))}},t.fromJSON=function(e){var n=e.descriptors.map((function(t){return new Float32Array(t)}));return new t(e.label,n)},t}();!function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i._score=r,i._classScore=o,i}wf(e,t),e.assertIsValidPredictedBox=function(t,e){if(Jf.assertIsValidLabeledBox(t,e),!Pf(t.score)||!Pf(t.classScore))throw new Error(e+" - expected properties score ("+t.score+") and ("+t.classScore+") to be a number between [0, 1]")},Object.defineProperty(e.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0})}(Jf);function Zf(t){return t.detection instanceof Uf}function tp(t,e){var n={detection:e};return Object.assign({},t,n)}function ep(){var t=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D:CanvasRenderingContext2D,Image:HTMLImageElement,ImageData:ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement("canvas")},createImageElement:function(){return document.createElement("img")},fetch:t,readFile:function(){throw new Error("readFile - filesystem not available for browser environment")}}}function np(t){var e="";if(!t)try{t=n(90872)}catch(t){e=t.toString()}return{readFile:t?function(e){return new Promise((function(n,r){t.readFile(e,(function(t,e){return t?r(t):n(e)}))}))}:function(){throw new Error("readFile - failed to require fs in nodejs environment with error: "+e)}}}function rp(){var t=n.g.Canvas||n.g.HTMLCanvasElement,e=n.g.Image||n.g.HTMLImageElement,r=n.g.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},o=np();return Cf({Canvas:t||function(){},CanvasRenderingContext2D:n.g.CanvasRenderingContext2D||function(){},Image:e||function(){},ImageData:n.g.ImageData||function(){},Video:n.g.HTMLVideoElement||function(){},createCanvasElement:function(){if(t)return new t;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},createImageElement:function(){if(e)return new e;throw new Error("createImageElement - missing Image implementation for nodejs environment")},fetch:r},o)}function op(){return"object"==typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLImageElement&&"undefined"!=typeof HTMLCanvasElement&&"undefined"!=typeof HTMLVideoElement&&"undefined"!=typeof ImageData&&"undefined"!=typeof CanvasRenderingContext2D}var ip,ap=n(97671);function sp(){return"object"==typeof n.g&&void 0!==ap&&!!ap.version}function up(t){ip=t}function cp(){op()&&up(ep()),sp()&&up(rp())}var lp,hp={getEnv:function(){if(!ip)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return ip},setEnv:up,initialize:cp,createBrowserEnv:ep,createFileSystem:np,createNodejsEnv:rp,monkeyPatch:function(t){if(ip||cp(),!ip)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");var e=t.Canvas,n=void 0===e?ip.Canvas:e,r=t.Image,o=void 0===r?ip.Image:r;ip.Canvas=n,ip.Image=o,ip.createCanvasElement=t.createCanvasElement||function(){return new n},ip.createImageElement=t.createImageElement||function(){return new o},ip.ImageData=t.ImageData||ip.ImageData,ip.Video=t.Video||ip.Video,ip.fetch=t.fetch||ip.fetch,ip.readFile=t.readFile||ip.readFile},isBrowser:op,isNodejs:sp};function fp(t){return hp.isNodejs()||"string"!=typeof t?t:document.getElementById(t)}function pp(t){var e=hp.getEnv(),n=e.Canvas;if(t instanceof e.CanvasRenderingContext2D)return t;var r=fp(t);if(!(r instanceof n))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");var o=r.getContext("2d");if(!o)throw new Error("resolveContext2d - canvas 2d context is null");return o}cp(),function(t){t.TOP_LEFT="TOP_LEFT",t.TOP_RIGHT="TOP_RIGHT",t.BOTTOM_LEFT="BOTTOM_LEFT",t.BOTTOM_RIGHT="BOTTOM_RIGHT"}(lp||(lp={}));var dp=function(t){void 0===t&&(t={});var e=t.anchorPosition,n=t.backgroundColor,r=t.fontColor,o=t.fontSize,i=t.fontStyle,a=t.padding;this.anchorPosition=e||lp.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=o||14,this.fontStyle=i||"Georgia",this.padding=a||4},vp=function(){function t(e,n,r){void 0===r&&(r={}),this.text="string"==typeof e?[e]:e instanceof t?e.text:e,this.anchor=n,this.options=new dp(r)}return t.prototype.measureWidth=function(t){var e=this.options.padding;return this.text.map((function(e){return t.measureText(e).width})).reduce((function(t,e){return t<e?e:t}),0)+2*e},t.prototype.measureHeight=function(){var t=this.options,e=t.fontSize,n=t.padding;return this.text.length*e+2*n},t.prototype.getUpperLeft=function(t,e){var n=this.options.anchorPosition,r=n===lp.BOTTOM_RIGHT||n===lp.TOP_RIGHT,o=n===lp.BOTTOM_LEFT||n===lp.BOTTOM_RIGHT,i=this.measureWidth(t),a=this.measureHeight(),s=r?this.anchor.x-i:this.anchor.x,u=o?this.anchor.y-a:this.anchor.y;if(e){var c=e.width,l=e.height;return{x:Math.max(Math.min(s,c-i),0),y:Math.max(Math.min(u,l-a),0)}}return{x:s,y:u}},t.prototype.draw=function(t){var e=fp(t),n=pp(e),r=this.options,o=r.backgroundColor,i=r.fontColor,a=r.fontSize,s=r.fontStyle,u=r.padding;n.font=a+"px "+s;var c=this.measureWidth(n),l=this.measureHeight();n.fillStyle=o;var h=this.getUpperLeft(n,e);n.fillRect(h.x,h.y,c,l),n.fillStyle=i,this.text.forEach((function(t,e){var r=u+h.x,o=u+h.y+(e+1)*a;n.fillText(t,r,o)}))},t}(),mp=function(t){void 0===t&&(t={});var e=t.boxColor,n=t.lineWidth,r=t.label,o=t.drawLabelOptions;this.boxColor=e||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=r;var i={anchorPosition:lp.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new dp(Object.assign({},i,o))},gp=function(){function t(t,e){void 0===e&&(e={}),this.box=new Lf(t),this.options=new mp(e)}return t.prototype.draw=function(t){var e=pp(t),n=this.options,r=n.boxColor,o=n.lineWidth,i=this.box,a=i.x,s=i.y,u=i.width,c=i.height;e.strokeStyle=r,e.lineWidth=o,e.strokeRect(a,s,u,c);var l=this.options.label;l&&new vp([l],{x:a-o/2,y:s},this.options.drawLabelOptions).draw(t)},t}();function yp(t,e){(Array.isArray(e)?e:[e]).forEach((function(e){var n=e instanceof Uf?e.score:Zf(e)?e.detection.score:void 0,r=e instanceof Uf?e.box:Zf(e)?e.detection.box:new Lf(e),o=n?""+Tf(n):void 0;new gp(r,{label:o}).draw(t)}))}function xp(t){var e=hp.getEnv(),n=e.Image,r=e.Video;return t instanceof n&&t.complete||t instanceof r&&t.readyState>=3}function bp(t){var e=hp.getEnv(),n=e.Image,r=e.Video;return t instanceof n?new Rf(t.naturalWidth,t.naturalHeight):t instanceof r?new Rf(t.videoWidth,t.videoHeight):new Rf(t.width,t.height)}function wp(t){var e=t.width,n=t.height,r=(0,hp.getEnv().createCanvasElement)();return r.width=e,r.height=n,r}function Cp(t,e){var n=hp.getEnv().ImageData;if(!(t instanceof n||xp(t)))throw new Error("createCanvasFromMedia - media has not finished loading yet");var r=e||bp(t),o=r.width,i=r.height,a=wp({width:o,height:i});return t instanceof n?pp(a).putImageData(t,0,0):pp(a).drawImage(t,0,0,o,i),a}function Ep(t,e){return Ef(this,void 0,void 0,(function(){var n,r,o,i,a,s;return _f(this,(function(u){switch(u.label){case 0:return n=e||hp.getEnv().createCanvasElement(),r=t.shape.slice(Df(t)?1:0),o=r[0],i=r[1],a=r[2],s=Ue((function(){return t.as3D(o,i,a).toInt()})),[4,nf.toPixels(s,n)];case 1:return u.sent(),s.dispose(),[2,n]}}))}))}function _p(t){var e=hp.getEnv(),n=e.Image,r=e.Canvas,o=e.Video;return t instanceof n||t instanceof r||t instanceof o}var Ip=function(){function t(t,e){var n=this;if(void 0===e&&(e=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(t))throw new Error("NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have "+t);this._treatAsBatchInput=e,this._batchSize=t.length,t.forEach((function(t,e){if(kf(t))return n._imageTensors[e]=t,void(n._inputDimensions[e]=t.shape);if(Df(t)){var r=t.shape[0];if(1!==r)throw new Error("NetInput - tf.Tensor4D with batchSize "+r+" passed, but not supported in input array");return n._imageTensors[e]=t,void(n._inputDimensions[e]=t.shape.slice(1))}var o=t instanceof hp.getEnv().Canvas?t:Cp(t);n._canvases[e]=o,n._inputDimensions[e]=[o.height,o.width,3]}))}return Object.defineProperty(t.prototype,"imageTensors",{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canvases",{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBatchInput",{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"batchSize",{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputDimensions",{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reshapedInputDimensions",{get:function(){var t=this;return Mf(this.batchSize,0,1).map((function(e,n){return t.getReshapedInputDimensions(n)}))},enumerable:!0,configurable:!0}),t.prototype.getInput=function(t){return this.canvases[t]||this.imageTensors[t]},t.prototype.getInputDimensions=function(t){return this._inputDimensions[t]},t.prototype.getInputHeight=function(t){return this._inputDimensions[t][0]},t.prototype.getInputWidth=function(t){return this._inputDimensions[t][1]},t.prototype.getReshapedInputDimensions=function(t){if("number"!=typeof this.inputSize)throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");return function(t,e){var n=t.width,r=t.height,o=e/Math.max(r,n);return new Rf(Math.round(n*o),Math.round(r*o))}({width:this.getInputWidth(t),height:this.getInputHeight(t)},this.inputSize)},t.prototype.toBatchTensor=function(t,e){var n=this;return void 0===e&&(e=!0),this._inputSize=t,Ue((function(){var r=Mf(n.batchSize,0,1).map((function(r){var o=n.getInput(r);if(o instanceof xt){var i=Df(o)?o:o.expandDims();return i=function(t,e){return void 0===e&&(e=!1),Ue((function(){var n=t.shape.slice(1),r=n[0],o=n[1];if(r===o)return t;var i=Math.abs(r-o),a=Math.round(i*(e?.5:1)),s=r>o?2:1,u=function(e){var n=t.shape.slice();return n[s]=e,yn(n,0)},c=u(a),l=i-c.shape[s],h=[e&&l?u(l):null,t,c].filter((function(t){return!!t})).map((function(t){return t.toFloat()}));return Cn(h,s)}))}(i,e),i.shape[1]===t&&i.shape[2]===t||(i=Bl.resizeBilinear(i,[t,t])),i.as3D(t,t,3)}if(o instanceof hp.getEnv().Canvas)return nf.fromPixels(function(t,e,n){void 0===n&&(n=!1);var r=hp.getEnv(),o=r.Image,i=r.Canvas;if(!(t instanceof o||t instanceof i))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");var a=bp(t),s=e/Math.max(a.height,a.width),u=s*a.width,c=s*a.height,l=wp({width:e,height:e}),h=t instanceof i?t:Cp(t),f=Math.abs(u-c)/2,p=n&&u<c?f:0,d=n&&c<u?f:0;return pp(l).drawImage(h,p,d,u,c),l}(o,t,e));throw new Error("toBatchTensor - at batchIdx "+r+", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have "+o)})),o=cr(r.map((function(t){return t.toFloat()}))).as4D(n.batchSize,t,t,3);return o}))},t}();function Rp(t){return Ef(this,void 0,void 0,(function(){var e,n,r;return _f(this,(function(o){switch(o.label){case 0:if(t instanceof Ip)return[2,t];if(!(e=Array.isArray(t)?t:[t]).length)throw new Error("toNetInput - empty array passed as input");return n=function(e){return Array.isArray(t)?" at input index "+e+":":""},(r=e.map(fp)).forEach((function(t,r){if(!_p(t)&&!kf(t)&&!Df(t)){if("string"==typeof e[r])throw new Error("toNetInput -"+n(r)+" string passed, but could not resolve HTMLElement for element id "+e[r]);throw new Error("toNetInput -"+n(r)+" expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id")}if(Df(t)){var o=t.shape[0];if(1!==o)throw new Error("toNetInput -"+n(r)+" tf.Tensor4D with batchSize "+o+" passed, but not supported in input array")}})),[4,Promise.all(r.map((function(t){return _p(t)&&(e=t,new Promise((function(t,n){if(e instanceof hp.getEnv().Canvas||xp(e))return t();function r(e){e.currentTarget&&(e.currentTarget.removeEventListener("load",r),e.currentTarget.removeEventListener("error",o),t(e))}function o(t){t.currentTarget&&(t.currentTarget.removeEventListener("load",r),t.currentTarget.removeEventListener("error",o),n(t))}e.addEventListener("load",r),e.addEventListener("error",o)})));var e})))];case 1:return o.sent(),[2,new Ip(r,Array.isArray(t))]}}))}))}function Sp(t,e){return Ef(this,void 0,void 0,(function(){var n,r,o,i,a,s;return _f(this,(function(u){switch(u.label){case 0:return n=hp.getEnv().Canvas,r=t,t instanceof n?[3,5]:[4,Rp(t)];case 1:if((o=u.sent()).batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");return(i=o.getInput(0))instanceof n?(a=i,[3,4]):[3,2];case 2:return[4,Ep(i)];case 3:a=u.sent(),u.label=4;case 4:r=a,u.label=5;case 5:return s=pp(r),[2,e.map((function(t){return t instanceof Uf?t.forSize(r.width,r.height).box.floor():t})).map((function(t){return t.clipAtImageBorders(r.width,r.height)})).map((function(t){var e=t.x,n=t.y,r=t.width,o=t.height,i=wp({width:r,height:o});return pp(i).putImageData(s.getImageData(e,n,r,o),0,0),i}))]}}))}))}function kp(t,e){return Ef(this,void 0,void 0,(function(){return _f(this,(function(n){if(!kf(t)&&!Df(t))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Df(t)&&t.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return[2,Ue((function(){var n=t.shape.slice(Df(t)?1:0),r=n[0],o=n[1],i=n[2],a=e.map((function(t){return t instanceof Uf?t.forSize(o,r).box:t})).map((function(t){return t.clipAtImageBorders(o,r)})).map((function(e){var n=e.x,a=e.y,s=e.width,u=e.height;return Ic(t.as3D(r,o,i),[a,n,0],[u,s,i])}));return a}))]}))}))}function Dp(t,e){return Ef(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return[4,(0,hp.getEnv().fetch)(t,e)];case 1:if(!((n=r.sent()).status<400))throw new Error("failed to fetch: ("+n.status+") "+n.statusText+", from url: "+n.url);return[2,n]}}))}))}function Ap(t){return Ef(this,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return[4,Dp(t)];case 1:return[2,e.sent().json()]}}))}))}function Tp(t,e){var n=e+"-weights_manifest.json";if(!t)return{modelBaseUri:"",manifestUri:n};if("/"===t)return{modelBaseUri:"/",manifestUri:"/"+n};var r=t.startsWith("http://")?"http://":t.startsWith("https://")?"https://":"",o=(t=t.replace(r,"")).split("/").filter((function(t){return t})),i=t.endsWith(".json")?o[o.length-1]:n,a=r+(t.endsWith(".json")?o.slice(0,o.length-1):o).join("/");return{modelBaseUri:a=t.startsWith("/")?"/"+a:a,manifestUri:"/"===a?"/"+i:a+"/"+i}}function Np(t,e){return Ef(this,void 0,void 0,(function(){var n,r,o,i;return _f(this,(function(a){switch(a.label){case 0:return n=Tp(t,e),r=n.manifestUri,o=n.modelBaseUri,[4,Ap(r)];case 1:return i=a.sent(),[2,Zh.loadWeights(i,o)]}}))}))}var Fp=function(){function t(t){this._name=t,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(t.prototype,"params",{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paramMappings",{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLoaded",{get:function(){return!!this.params},enumerable:!0,configurable:!0}),t.prototype.getParamFromPath=function(t){var e=this.traversePropertyPath(t);return e.obj[e.objProp]},t.prototype.reassignParamFromPath=function(t,e){var n=this.traversePropertyPath(t),r=n.obj,o=n.objProp;r[o].dispose(),r[o]=e},t.prototype.getParamList=function(){var t=this;return this._paramMappings.map((function(e){var n=e.paramPath;return{path:n,tensor:t.getParamFromPath(n)}}))},t.prototype.getTrainableParams=function(){return this.getParamList().filter((function(t){return t.tensor instanceof It}))},t.prototype.getFrozenParams=function(){return this.getParamList().filter((function(t){return!(t.tensor instanceof It)}))},t.prototype.variable=function(){var t=this;this.getFrozenParams().forEach((function(e){var n=e.path,r=e.tensor;t.reassignParamFromPath(n,r.variable())}))},t.prototype.freeze=function(){var t=this;this.getTrainableParams().forEach((function(e){var n=e.path,r=e.tensor,o=cn(r.dataSync());r.dispose(),t.reassignParamFromPath(n,o)}))},t.prototype.dispose=function(t){void 0===t&&(t=!0),this.getParamList().forEach((function(e){if(t&&e.tensor.isDisposed)throw new Error("param tensor has already been disposed for path "+e.path);e.tensor.dispose()})),this._params=void 0},t.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map((function(t){var e=t.tensor;return Array.from(e.dataSync())})).reduce((function(t,e){return t.concat(e)})))},t.prototype.load=function(t){return Ef(this,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return t instanceof Float32Array?(this.extractWeights(t),[2]):[4,this.loadFromUri(t)];case 1:return e.sent(),[2]}}))}))},t.prototype.loadFromUri=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:if(t&&"string"!=typeof t)throw new Error(this._name+".loadFromUri - expected model uri");return[4,Np(t,this.getDefaultModelName())];case 1:return e=n.sent(),this.loadFromWeightMap(e),[2]}}))}))},t.prototype.loadFromDisk=function(t){return Ef(this,void 0,void 0,(function(){var e,n,r,o,i,a,s,u,c,l;return _f(this,(function(h){switch(h.label){case 0:if(t&&"string"!=typeof t)throw new Error(this._name+".loadFromDisk - expected model file path");return e=hp.getEnv().readFile,n=Tp(t,this.getDefaultModelName()),r=n.manifestUri,o=n.modelBaseUri,i=function(t){return Promise.all(t.map((function(t){return e(t).then((function(t){return t.buffer}))})))},a=Zh.weightsLoaderFactory(i),c=(u=JSON).parse,[4,e(r)];case 1:return s=c.apply(u,[h.sent().toString()]),[4,a(s,o)];case 2:return l=h.sent(),this.loadFromWeightMap(l),[2]}}))}))},t.prototype.loadFromWeightMap=function(t){var e=this.extractParamsFromWeigthMap(t),n=e.paramMappings,r=e.params;this._paramMappings=n,this._params=r},t.prototype.extractWeights=function(t){var e=this.extractParams(t),n=e.paramMappings,r=e.params;this._paramMappings=n,this._params=r},t.prototype.traversePropertyPath=function(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");var e=t.split("/").reduce((function(e,n){if(!e.nextObj.hasOwnProperty(n))throw new Error("traversePropertyPath - object does not have property "+n+", for path "+t);return{obj:e.nextObj,objProp:n,nextObj:e.nextObj[n]}}),{nextObj:this.params}),n=e.obj,r=e.objProp;if(!(n&&r&&n[r]instanceof xt))throw new Error("traversePropertyPath - parameter is not a tensor, for path "+t);return{obj:n,objProp:r}},t}();function Mp(t,e,n){return Ue((function(){var r=oc(t,e.depthwise_filter,e.pointwise_filter,n,"same");return r=lu(r,e.bias)}))}function Op(t,e,n){return void 0===n&&(n=!1),Ue((function(){var r=Vc(n?lu(Ju(t,e.conv0.filters,[2,2],"same"),e.conv0.bias):Mp(t,e.conv0,[2,2])),o=Mp(r,e.conv1,[1,1]),i=Mp(Vc(lu(r,o)),e.conv2,[1,1]);return Vc(lu(r,lu(o,i)))}))}function Pp(t,e,n,r){return void 0===n&&(n=!1),void 0===r&&(r=!0),Ue((function(){var o=Vc(n?lu(Ju(t,e.conv0.filters,r?[2,2]:[1,1],"same"),e.conv0.bias):Mp(t,e.conv0,r?[2,2]:[1,1])),i=Mp(o,e.conv1,[1,1]),a=Mp(Vc(lu(o,i)),e.conv2,[1,1]),s=Mp(Vc(lu(o,lu(i,a))),e.conv3,[1,1]);return Vc(lu(o,lu(i,lu(a,s))))}))}function Bp(t,e,n,r){return void 0===n&&(n="same"),void 0===r&&(r=!1),Ue((function(){var o=lu(Ju(t,e.filters,[1,1],n),e.bias);return r?Vc(o):o}))}function Lp(t,e){Object.keys(t).forEach((function(n){e.some((function(t){return t.originalPath===n}))||t[n].dispose()}))}function Wp(t,e){return function(n,r,o,i){var a=vn(t(n*r*o*o),[o,o,n,r]),s=fn(t(r));return e.push({paramPath:i+"/filters"},{paramPath:i+"/bias"}),{filters:a,bias:s}}}function zp(t,e){return function(n,r,o){var i=pn(t(n*r),[n,r]),a=fn(t(r));return e.push({paramPath:o+"/weights"},{paramPath:o+"/bias"}),{weights:i,bias:a}}}var Up=function(t,e,n){this.depthwise_filter=t,this.pointwise_filter=e,this.bias=n};function Vp(t,e){return function(n,r,o){var i=vn(t(9*n),[3,3,n,1]),a=vn(t(n*r),[1,1,n,r]),s=fn(t(r));return e.push({paramPath:o+"/depthwise_filter"},{paramPath:o+"/pointwise_filter"},{paramPath:o+"/bias"}),new Up(i,a,s)}}function Gp(t){return function(e){var n=t(e+"/depthwise_filter",4),r=t(e+"/pointwise_filter",4),o=t(e+"/bias",1);return new Up(n,r,o)}}function Hp(t,e){return function(n,r,o){var i=t[n];if(!Sf(i,r))throw new Error("expected weightMap["+n+"] to be a Tensor"+r+"D, instead have "+i);return e.push({originalPath:n,paramPath:o||n}),i}}function qp(t){var e=t;return{extractWeights:function(t){var n=e.slice(0,t);return e=e.slice(t),n},getRemainingWeights:function(){return e}}}function jp(t,e){var n=Wp(t,e),r=Vp(t,e);function o(t,e,o,i){return void 0===i&&(i=!1),{conv0:i?n(t,e,3,o+"/conv0"):r(t,e,o+"/conv0"),conv1:r(e,e,o+"/conv1"),conv2:r(e,e,o+"/conv2")}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:function(t,e,n,i){void 0===i&&(i=!1);var a=o(t,e,n,i);return{conv0:a.conv0,conv1:a.conv1,conv2:a.conv2,conv3:r(e,e,n+"/conv3")}}}}function Kp(t){return function(e){return{filters:t(e+"/filters",4),bias:t(e+"/bias",1)}}}function Xp(t,e){var n=Hp(t,e),r=Kp(n),o=Gp(n);return{extractDenseBlock3Params:function(t,e){return void 0===e&&(e=!1),{conv0:e?r(t+"/conv0"):o(t+"/conv0"),conv1:o(t+"/conv1"),conv2:o(t+"/conv2")}},extractDenseBlock4Params:function(t,e){return void 0===e&&(e=!1),{conv0:e?r(t+"/conv0"):o(t+"/conv0"),conv1:o(t+"/conv1"),conv2:o(t+"/conv2"),conv3:o(t+"/conv3")}}}}var Yp=function(t){function e(){return t.call(this,"FaceFeatureExtractor")||this}return wf(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("FaceFeatureExtractor - load model before inference");return Ue((function(){var n=Pp(Hf(t.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(hn(255)),e.dense0,!0);return n=Pp(n,e.dense1),n=Pp(n,e.dense2),n=Pp(n,e.dense3),n=yc(n,[7,7],[2,2],"valid")}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.getDefaultModelName=function(){return"face_feature_extractor_model"},e.prototype.extractParamsFromWeigthMap=function(t){return function(t){var e=[],n=Xp(t,e).extractDenseBlock4Params,r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Lp(t,e),{params:r,paramMappings:e}}(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=qp(t),r=n.extractWeights,o=n.getRemainingWeights,i=jp(r,e).extractDenseBlock4Params,a=i(3,32,"dense0",!0),s=i(32,64,"dense1"),u=i(64,128,"dense2"),c=i(128,256,"dense3");if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:e,params:{dense0:a,dense1:s,dense2:u,dense3:c}}}(t)},e}(Fp);function $p(t,e){return Ue((function(){return lu(sc(t,e.weights),e.bias)}))}function Jp(t){var e={},n={};return Object.keys(t).forEach((function(r){(r.startsWith("fc")?n:e)[r]=t[r]})),{featureExtractorMap:e,classifierMap:n}}var Qp=function(t){function e(e,n){var r=t.call(this,e)||this;return r._faceFeatureExtractor=n,r}return wf(e,t),Object.defineProperty(e.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),e.prototype.runNet=function(t){var e=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Ue((function(){var r=t instanceof Ip?e.faceFeatureExtractor.forwardInput(t):t;return $p(r.as2D(r.shape[0],-1),n.fc)}))},e.prototype.dispose=function(e){void 0===e&&(e=!0),this.faceFeatureExtractor.dispose(e),t.prototype.dispose.call(this,e)},e.prototype.loadClassifierParams=function(t){var e=this.extractClassifierParams(t),n=e.params,r=e.paramMappings;this._params=n,this._paramMappings=r},e.prototype.extractClassifierParams=function(t){return function(t,e,n){var r=[],o=qp(t),i=o.extractWeights,a=o.getRemainingWeights,s=zp(i,r)(e,n,"fc");if(0!==a().length)throw new Error("weights remaing after extract: "+a().length);return{paramMappings:r,params:{fc:s}}}(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},e.prototype.extractParamsFromWeigthMap=function(t){var e=Jp(t),n=e.featureExtractorMap,r=e.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(t){var e,n=[],r=Hp(t,n),o={fc:(e="fc",{weights:r(e+"/weights",2),bias:r(e+"/bias",1)})};return Lp(t,n),{params:o,paramMappings:n}}(r)},e.prototype.extractParams=function(t){var e=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*e+n,o=t.slice(0,t.length-r),i=t.slice(t.length-r);return this.faceFeatureExtractor.extractWeights(o),this.extractClassifierParams(i)},e}(Fp),Zp=["neutral","happy","sad","angry","fearful","disgusted","surprised"],td=function(){function t(t){var e=this;if(7!==t.length)throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: "+t.length);Zp.forEach((function(n,r){e[n]=t[r]}))}return t.prototype.asSortedArray=function(){var t=this;return Zp.map((function(e){return{expression:e,probability:t[e]}})).sort((function(t,e){return e.probability-t.probability}))},t}(),ed=function(t){function e(e){return void 0===e&&(e=new Yp),t.call(this,"FaceExpressionNet",e)||this}return wf(e,t),e.prototype.forwardInput=function(t){var e=this;return Ue((function(){return Tr(e.runNet(t))}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.predictExpressions=function(t){return Ef(this,void 0,void 0,(function(){var e,n,r,o,i=this;return _f(this,(function(a){switch(a.label){case 0:return[4,Rp(t)];case 1:return e=a.sent(),[4,this.forwardInput(e)];case 2:return n=a.sent(),[4,Promise.all(fr(n).map((function(t){return Ef(i,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return[4,t.data()];case 1:return e=n.sent(),t.dispose(),[2,e]}}))}))})))];case 3:return r=a.sent(),n.dispose(),o=r.map((function(t){return new td(t)})),[2,e.isBatchInput?o:o[0]]}}))}))},e.prototype.getDefaultModelName=function(){return"face_expression_model"},e.prototype.getClassifierChannelsIn=function(){return 256},e.prototype.getClassifierChannelsOut=function(){return 7},e}(Qp);function nd(t,e){var n={expressions:e};return Object.assign({},t,n)}function rd(t,e,n,r){void 0===n&&(n=.1),(Array.isArray(e)?e:[e]).forEach((function(e){var o=e instanceof td?e:e.expressions instanceof td?e.expressions:void 0;if(!o)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");var i=o.asSortedArray().filter((function(t){return t.probability>n})),a=Zf(e)?e.detection.box.bottomLeft:r||new Bf(0,0),s=new vp(i.map((function(t){return t.expression+" ("+Tf(t.probability)+")"})),a);s.draw(t)}))}function od(t){return Zf(t)&&t.landmarks instanceof Kf&&t.unshiftedLandmarks instanceof Kf&&t.alignedRect instanceof Uf}function id(t,e){var n=t.detection.box,r=e.shiftBy(n.x,n.y),o=r.align(),i=t.detection.imageDims,a={landmarks:r,unshiftedLandmarks:e,alignedRect:new Uf(t.detection.score,o.rescale(i.reverse()),i)};return Object.assign({},t,a)}var ad=function(t){void 0===t&&(t={});var e=t.drawLines,n=void 0===e||e,r=t.drawPoints,o=void 0===r||r,i=t.lineWidth,a=t.lineColor,s=t.pointSize,u=t.pointColor;this.drawLines=n,this.drawPoints=o,this.lineWidth=i||1,this.pointSize=s||2,this.lineColor=a||"rgba(0, 255, 255, 1)",this.pointColor=u||"rgba(255, 0, 255, 1)"},sd=function(){function t(t,e){void 0===e&&(e={}),this.faceLandmarks=t,this.options=new ad(e)}return t.prototype.draw=function(t){var e=pp(t),n=this.options,r=n.drawLines,o=n.drawPoints,i=n.lineWidth,a=n.lineColor,s=n.pointSize,u=n.pointColor;if(r&&this.faceLandmarks instanceof Yf&&(e.strokeStyle=a,e.lineWidth=i,xf(e,this.faceLandmarks.getJawOutline()),xf(e,this.faceLandmarks.getLeftEyeBrow()),xf(e,this.faceLandmarks.getRightEyeBrow()),xf(e,this.faceLandmarks.getNose()),xf(e,this.faceLandmarks.getLeftEye(),!0),xf(e,this.faceLandmarks.getRightEye(),!0),xf(e,this.faceLandmarks.getMouth(),!0)),o){e.strokeStyle=u,e.fillStyle=u;this.faceLandmarks.positions.forEach((function(t){e.beginPath(),e.arc(t.x,t.y,s,0,2*Math.PI),e.fill()}))}},t}();function ud(t,e){(Array.isArray(e)?e:[e]).forEach((function(e){var n=e instanceof Kf?e:od(e)?e.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new sd(n).draw(t)}))}function cd(t,e){var n=[],r=qp(t),o=r.extractWeights,i=r.getRemainingWeights,a=function(t,e){var n=Wp(t,e),r=Vp(t,e);return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:function(t,e,o){return{separable_conv0:r(t,e,o+"/separable_conv0"),separable_conv1:r(e,e,o+"/separable_conv1"),expansion_conv:n(t,e,1,o+"/expansion_conv")}},extractMainBlockParams:function(t,e){return{separable_conv0:r(t,t,e+"/separable_conv0"),separable_conv1:r(t,t,e+"/separable_conv1"),separable_conv2:r(t,t,e+"/separable_conv2")}}}}(o,n),s=a.extractConvParams,u=a.extractSeparableConvParams,c=a.extractReductionBlockParams,l=a.extractMainBlockParams,h={conv_in:s(3,32,3,"entry_flow/conv_in"),reduction_block_0:c(32,64,"entry_flow/reduction_block_0"),reduction_block_1:c(64,128,"entry_flow/reduction_block_1")},f={};Mf(e,0,1).forEach((function(t){f["main_block_"+t]=l(128,"middle_flow/main_block_"+t)}));var p={reduction_block:c(128,256,"exit_flow/reduction_block"),separable_conv:u(256,512,"exit_flow/separable_conv")};if(0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:n,params:{entry_flow:h,middle_flow:f,exit_flow:p}}}function ld(t,e){var n=[],r=function(t,e){var n=Hp(t,e),r=Kp(n),o=Gp(n);return{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:function(t){return{separable_conv0:o(t+"/separable_conv0"),separable_conv1:o(t+"/separable_conv1"),expansion_conv:r(t+"/expansion_conv")}},extractMainBlockParams:function(t){return{separable_conv0:o(t+"/separable_conv0"),separable_conv1:o(t+"/separable_conv1"),separable_conv2:o(t+"/separable_conv2")}}}}(t,n),o=r.extractConvParams,i=r.extractSeparableConvParams,a=r.extractReductionBlockParams,s=r.extractMainBlockParams,u={conv_in:o("entry_flow/conv_in"),reduction_block_0:a("entry_flow/reduction_block_0"),reduction_block_1:a("entry_flow/reduction_block_1")},c={};Mf(e,0,1).forEach((function(t){c["main_block_"+t]=s("middle_flow/main_block_"+t)}));var l={reduction_block:a("exit_flow/reduction_block"),separable_conv:i("exit_flow/separable_conv")};return Lp(t,n),{params:{entry_flow:u,middle_flow:c,exit_flow:l},paramMappings:n}}function hd(t,e,n){return lu(Ju(t,e.filters,n,"same"),e.bias)}function fd(t,e,n){void 0===n&&(n=!0);var r=n?Vc(t):t;return r=Mp(r,e.separable_conv0,[1,1]),r=Mp(Vc(r),e.separable_conv1,[1,1]),r=gc(r,[3,3],[2,2],"same"),r=lu(r,hd(t,e.expansion_conv,[2,2]))}var pd,dd=function(t){function e(e){var n=t.call(this,"TinyXception")||this;return n._numMainBlocks=e,n}return wf(e,t),e.prototype.forwardInput=function(t){var e=this,n=this.params;if(!n)throw new Error("TinyXception - load model before inference");return Ue((function(){var r=Hf(t.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(hn(256)),o=Vc(hd(r,n.entry_flow.conv_in,[2,2]));return o=fd(o,n.entry_flow.reduction_block_0,!1),o=fd(o,n.entry_flow.reduction_block_1),Mf(e._numMainBlocks,0,1).forEach((function(t){o=function(t,e){var n=Mp(Vc(t),e.separable_conv0,[1,1]);return n=Mp(Vc(n),e.separable_conv1,[1,1]),n=Mp(Vc(n),e.separable_conv2,[1,1]),lu(n,t)}(o,n.middle_flow["main_block_"+t])})),o=fd(o,n.exit_flow.reduction_block),o=Vc(Mp(o,n.exit_flow.separable_conv,[1,1]))}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.getDefaultModelName=function(){return"tiny_xception_model"},e.prototype.extractParamsFromWeigthMap=function(t){return ld(t,this._numMainBlocks)},e.prototype.extractParams=function(t){return cd(t,this._numMainBlocks)},e}(Fp);!function(t){t.FEMALE="female",t.MALE="male"}(pd||(pd={}));var vd=function(t){function e(e){void 0===e&&(e=new dd(2));var n=t.call(this,"AgeGenderNet")||this;return n._faceFeatureExtractor=e,n}return wf(e,t),Object.defineProperty(e.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),e.prototype.runNet=function(t){var e=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Ue((function(){var r=t instanceof Ip?e.faceFeatureExtractor.forwardInput(t):t,o=yc(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1);return{age:$p(o,n.fc.age).as1D(),gender:$p(o,n.fc.gender)}}))},e.prototype.forwardInput=function(t){var e=this;return Ue((function(){var n=e.runNet(t),r=n.age,o=n.gender;return{age:r,gender:Tr(o)}}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.predictAgeAndGender=function(t){return Ef(this,void 0,void 0,(function(){var e,n,r,o,i,a,s=this;return _f(this,(function(u){switch(u.label){case 0:return[4,Rp(t)];case 1:return e=u.sent(),[4,this.forwardInput(e)];case 2:return n=u.sent(),r=fr(n.age),o=fr(n.gender),i=r.map((function(t,e){return{ageTensor:t,genderTensor:o[e]}})),[4,Promise.all(i.map((function(t){var e=t.ageTensor,n=t.genderTensor;return Ef(s,void 0,void 0,(function(){var t,r,o,i,a;return _f(this,(function(s){switch(s.label){case 0:return[4,e.data()];case 1:return t=s.sent()[0],[4,n.data()];case 2:return r=s.sent()[0],i=(o=r>.5)?pd.MALE:pd.FEMALE,a=o?r:1-r,e.dispose(),n.dispose(),[2,{age:t,gender:i,genderProbability:a}]}}))}))})))];case 3:return a=u.sent(),n.age.dispose(),n.gender.dispose(),[2,e.isBatchInput?a:a[0]]}}))}))},e.prototype.getDefaultModelName=function(){return"age_gender_model"},e.prototype.dispose=function(e){void 0===e&&(e=!0),this.faceFeatureExtractor.dispose(e),t.prototype.dispose.call(this,e)},e.prototype.loadClassifierParams=function(t){var e=this.extractClassifierParams(t),n=e.params,r=e.paramMappings;this._params=n,this._paramMappings=r},e.prototype.extractClassifierParams=function(t){return function(t){var e=[],n=qp(t),r=n.extractWeights,o=n.getRemainingWeights,i=zp(r,e),a=i(512,1,"fc/age"),s=i(512,2,"fc/gender");if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:e,params:{fc:{age:a,gender:s}}}}(t)},e.prototype.extractParamsFromWeigthMap=function(t){var e=Jp(t),n=e.featureExtractorMap,r=e.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(t){var e=[],n=Hp(t,e);function r(t){return{weights:n(t+"/weights",2),bias:n(t+"/bias",1)}}var o={fc:{age:r("fc/age"),gender:r("fc/gender")}};return Lp(t,e),{params:o,paramMappings:e}}(r)},e.prototype.extractParams=function(t){var e=t.slice(0,t.length-1539),n=t.slice(t.length-1539);return this.faceFeatureExtractor.extractWeights(e),this.extractClassifierParams(n)},e}(Fp),md=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.postProcess=function(t,e,n){var r=n.map((function(t){var n=t.width,r=t.height,o=e/Math.max(r,n);return{width:n*o,height:r*o}})),o=r.length;return Ue((function(){var n=function(t,e){return cr([yn([68],t),yn([68],e)],1).as2D(1,136).as1D()},i=function(t,e){var n=r[t],o=n.width,i=n.height;return e(o,i)?Math.abs(o-i)/2:0},a=t.mul(yn([o,136],e)).sub(cr(Array.from(Array(o),(function(t,e){return n(function(t){return i(t,(function(t,e){return t<e}))}(e),function(t){return i(t,(function(t,e){return e<t}))}(e))})))).div(cr(Array.from(Array(o),(function(t,e){return n(r[e].width,r[e].height)}))));return a}))},e.prototype.forwardInput=function(t){var e=this;return Ue((function(){var n=e.runNet(t);return e.postProcess(n,t.inputSize,t.inputDimensions.map((function(t){return{height:t[0],width:t[1]}})))}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.detectLandmarks=function(t){return Ef(this,void 0,void 0,(function(){var e,n,r,o=this;return _f(this,(function(i){switch(i.label){case 0:return[4,Rp(t)];case 1:return e=i.sent(),n=Ue((function(){return fr(o.forwardInput(e))})),[4,Promise.all(n.map((function(t,n){return Ef(o,void 0,void 0,(function(){var r,o,i,a,s;return _f(this,(function(u){switch(u.label){case 0:return i=(o=Array).from,[4,t.data()];case 1:return r=i.apply(o,[u.sent()]),a=r.filter((function(t,e){return Af(e)})),s=r.filter((function(t,e){return!Af(e)})),[2,new Yf(Array(68).fill(0).map((function(t,e){return new Bf(a[e],s[e])})),{height:e.getInputHeight(n),width:e.getInputWidth(n)})]}}))}))})))];case 2:return r=i.sent(),n.forEach((function(t){return t.dispose()})),[2,e.isBatchInput?r:r[0]]}}))}))},e.prototype.getClassifierChannelsOut=function(){return 136},e}(Qp),gd=function(t){function e(e){return void 0===e&&(e=new Yp),t.call(this,"FaceLandmark68Net",e)||this}return wf(e,t),e.prototype.getDefaultModelName=function(){return"face_landmark_68_model"},e.prototype.getClassifierChannelsIn=function(){return 256},e}(md);var yd=function(t){function e(){return t.call(this,"TinyFaceFeatureExtractor")||this}return wf(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Ue((function(){var n=Op(Hf(t.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(hn(255)),e.dense0,!0);return n=Op(n,e.dense1),n=Op(n,e.dense2),n=yc(n,[14,14],[2,2],"valid")}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.getDefaultModelName=function(){return"face_feature_extractor_tiny_model"},e.prototype.extractParamsFromWeigthMap=function(t){return function(t){var e=[],n=Xp(t,e).extractDenseBlock3Params,r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Lp(t,e),{params:r,paramMappings:e}}(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=qp(t),r=n.extractWeights,o=n.getRemainingWeights,i=jp(r,e).extractDenseBlock3Params,a=i(3,32,"dense0",!0),s=i(32,64,"dense1"),u=i(64,128,"dense2");if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:e,params:{dense0:a,dense1:s,dense2:u}}}(t)},e}(Fp),xd=function(t){function e(e){return void 0===e&&(e=new yd),t.call(this,"FaceLandmark68TinyNet",e)||this}return wf(e,t),e.prototype.getDefaultModelName=function(){return"face_landmark_68_tiny_model"},e.prototype.getClassifierChannelsIn=function(){return 128},e}(md);!function(t){function e(){return null!==t&&t.apply(this,arguments)||this}wf(e,t)}(gd);function bd(t,e,n,r,o){void 0===o&&(o="same");var i=e.conv,a=i.filters,s=i.bias,u=Ju(t,a,n,o);return u=function(t,e){return lu(_u(t,e.weights),e.biases)}(u=lu(u,s),e.scale),r?Vc(u):u}function wd(t,e){return bd(t,e,[1,1],!1)}function Cd(t,e){return bd(t,e,[2,2],!0,"valid")}function Ed(t,e){function n(n,r,o,i){var a=function(e,n,r){var o=t(e),i=o.length/(n*r*r);if(i%1!=0)throw new Error("depth has to be an integer: "+i+", weights.length: "+o.length+", numFilters: "+n+", filterSize: "+r);return Ue((function(){return qc(vn(o,[n,i,r,r]),[2,3,1,0])}))}(n,r,o),s=fn(t(r));return e.push({paramPath:i+"/filters"},{paramPath:i+"/bias"}),{filters:a,bias:s}}function r(r,o,i,a){var s=n(r,o,i,a+"/conv"),u=function(n,r){var o=fn(t(n)),i=fn(t(n));return e.push({paramPath:r+"/weights"},{paramPath:r+"/biases"}),{weights:o,biases:i}}(o,a+"/scale");return{conv:s,scale:u}}return{extractConvLayerParams:r,extractResidualLayerParams:function(t,e,n,o,i){return void 0===i&&(i=!1),{conv1:r((i?.5:1)*t,e,n,o+"/conv1"),conv2:r(t,e,n,o+"/conv2")}}}}function _d(t,e){var n=Hp(t,e);function r(t){var e=n(t+"/conv/filters",4),r=n(t+"/conv/bias",1),o=function(t){return{weights:n(t+"/scale/weights",1),biases:n(t+"/scale/biases",1)}}(t);return{conv:{filters:e,bias:r},scale:o}}return{extractConvLayerParams:r,extractResidualLayerParams:function(t){return{conv1:r(t+"/conv1"),conv2:r(t+"/conv2")}}}}function Id(t){var e=[],n=_d(t,e),r=n.extractConvLayerParams,o=n.extractResidualLayerParams,i=r("conv32_down"),a=o("conv32_1"),s=o("conv32_2"),u=o("conv32_3"),c=o("conv64_down"),l=o("conv64_1"),h=o("conv64_2"),f=o("conv64_3"),p=o("conv128_down"),d=o("conv128_1"),v=o("conv128_2"),m=o("conv256_down"),g=o("conv256_1"),y=o("conv256_2"),x=o("conv256_down_out"),b=t.fc;if(e.push({originalPath:"fc",paramPath:"fc"}),!Sf(b,2))throw new Error("expected weightMap[fc] to be a Tensor2D, instead have "+b);var w={conv32_down:i,conv32_1:a,conv32_2:s,conv32_3:u,conv64_down:c,conv64_1:l,conv64_2:h,conv64_3:f,conv128_down:p,conv128_1:d,conv128_2:v,conv256_down:m,conv256_1:g,conv256_2:y,conv256_down_out:x,fc:b};return Lp(t,e),{params:w,paramMappings:e}}function Rd(t,e){var n=function(t,e){return bd(t,e,[1,1],!0)}(t,e.conv1);return n=wd(n,e.conv2),n=lu(n,t),n=Vc(n)}function Sd(t,e){var n=Cd(t,e.conv1);n=wd(n,e.conv2);var r=yc(t,2,2,"valid"),o=gn(r.shape),i=r.shape[3]!==n.shape[3];if(r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2]){var a=If(n.shape);a[1]=1;var s=gn(a),u=If((n=Cn([n,s],1)).shape);u[2]=1;var c=gn(u);n=Cn([n,c],2)}return r=i?Cn([r,o],3):r,n=lu(r,n),n=Vc(n)}var kd=function(t){function e(){return t.call(this,"FaceRecognitionNet")||this}return wf(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("FaceRecognitionNet - load model before inference");return Ue((function(){var n=Cd(Hf(t.toBatchTensor(150,!0).toFloat(),[122.782,117.001,104.298]).div(hn(256)),e.conv32_down);n=Rd(n=gc(n,3,2,"valid"),e.conv32_1),n=Rd(n,e.conv32_2),n=Rd(n,e.conv32_3),n=Rd(n=Sd(n,e.conv64_down),e.conv64_1),n=Rd(n,e.conv64_2),n=Rd(n,e.conv64_3),n=Rd(n=Sd(n,e.conv128_down),e.conv128_1),n=Rd(n,e.conv128_2),n=Rd(n=Sd(n,e.conv256_down),e.conv256_1);var r=(n=Sd(n=Rd(n,e.conv256_2),e.conv256_down_out)).mean([1,2]);return sc(r,e.fc)}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.computeFaceDescriptor=function(t){return Ef(this,void 0,void 0,(function(){var e,n,r,o=this;return _f(this,(function(i){switch(i.label){case 0:return[4,Rp(t)];case 1:return e=i.sent(),n=Ue((function(){return fr(o.forwardInput(e))})),[4,Promise.all(n.map((function(t){return t.data()})))];case 2:return r=i.sent(),n.forEach((function(t){return t.dispose()})),[2,e.isBatchInput?r:r[0]]}}))}))},e.prototype.getDefaultModelName=function(){return"face_recognition_model"},e.prototype.extractParamsFromWeigthMap=function(t){return Id(t)},e.prototype.extractParams=function(t){return function(t){var e=qp(t),n=e.extractWeights,r=e.getRemainingWeights,o=[],i=Ed(n,o),a=i.extractConvLayerParams,s=i.extractResidualLayerParams,u=a(4704,32,7,"conv32_down"),c=s(9216,32,3,"conv32_1"),l=s(9216,32,3,"conv32_2"),h=s(9216,32,3,"conv32_3"),f=s(36864,64,3,"conv64_down",!0),p=s(36864,64,3,"conv64_1"),d=s(36864,64,3,"conv64_2"),v=s(36864,64,3,"conv64_3"),m=s(147456,128,3,"conv128_down",!0),g=s(147456,128,3,"conv128_1"),y=s(147456,128,3,"conv128_2"),x=s(589824,256,3,"conv256_down",!0),b=s(589824,256,3,"conv256_1"),w=s(589824,256,3,"conv256_2"),C=s(589824,256,3,"conv256_down_out"),E=Ue((function(){return qc(pn(n(32768),[128,256]),[1,0])}));if(o.push({paramPath:"fc"}),0!==r().length)throw new Error("weights remaing after extract: "+r().length);return{params:{conv32_down:u,conv32_1:c,conv32_2:l,conv32_3:h,conv64_down:f,conv64_1:p,conv64_2:d,conv64_3:v,conv128_down:m,conv128_1:g,conv128_2:y,conv256_down:x,conv256_1:b,conv256_2:w,conv256_down_out:C,fc:E},paramMappings:o}}(t)},e}(Fp);function Dd(t,e,n){var r={gender:e,genderProbability:n};return Object.assign({},t,r)}var Ad=function(){function t(t){var e=void 0===t?{}:t,n=e.minFaceSize,r=e.scaleFactor,o=e.maxNumScales,i=e.scoreThresholds,a=e.scaleSteps;if(this._name="MtcnnOptions",this._minFaceSize=n||20,this._scaleFactor=r||.709,this._maxNumScales=o||10,this._scoreThresholds=i||[.6,.7,.7],this._scaleSteps=a,"number"!=typeof this._minFaceSize||this._minFaceSize<0)throw new Error(this._name+" - expected minFaceSize to be a number > 0");if("number"!=typeof this._scaleFactor||this._scaleFactor<=0||this._scaleFactor>=1)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if("number"!=typeof this._maxNumScales||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||3!==this._scoreThresholds.length||this._scoreThresholds.some((function(t){return"number"!=typeof t})))throw new Error(this._name+" - expected scoreThresholds to be an array of numbers of length 3");if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some((function(t){return"number"!=typeof t}))))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(t.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),t}();function Td(t,e){function n(n,r,o,i,a){var s=vn(t(n*r*o*o),[o,o,n,r]),u=fn(t(r));return e.push({paramPath:i+"/filters"},{paramPath:i+"/"+(a?"batch_norm_offset":"bias")}),{filters:s,bias:u}}function r(t,e,r,o){var i=n(t,e,r,o,!0);return{filters:i.filters,batch_norm_offset:i.bias}}function o(n,o,i){var a=function(n,r){var o=vn(t(9*n),[3,3,n,1]),i=fn(t(n)),a=fn(t(n)),s=fn(t(n)),u=fn(t(n));return e.push({paramPath:r+"/filters"},{paramPath:r+"/batch_norm_scale"},{paramPath:r+"/batch_norm_offset"},{paramPath:r+"/batch_norm_mean"},{paramPath:r+"/batch_norm_variance"}),{filters:o,batch_norm_scale:i,batch_norm_offset:a,batch_norm_mean:s,batch_norm_variance:u}}(n,i+"/depthwise_conv");return{depthwise_conv:a,pointwise_conv:r(n,o,1,i+"/pointwise_conv")}}return{extractMobilenetV1Params:function(){return{conv_0:r(3,32,3,"mobilenetv1/conv_0"),conv_1:o(32,64,"mobilenetv1/conv_1"),conv_2:o(64,128,"mobilenetv1/conv_2"),conv_3:o(128,128,"mobilenetv1/conv_3"),conv_4:o(128,256,"mobilenetv1/conv_4"),conv_5:o(256,256,"mobilenetv1/conv_5"),conv_6:o(256,512,"mobilenetv1/conv_6"),conv_7:o(512,512,"mobilenetv1/conv_7"),conv_8:o(512,512,"mobilenetv1/conv_8"),conv_9:o(512,512,"mobilenetv1/conv_9"),conv_10:o(512,512,"mobilenetv1/conv_10"),conv_11:o(512,512,"mobilenetv1/conv_11"),conv_12:o(512,1024,"mobilenetv1/conv_12"),conv_13:o(1024,1024,"mobilenetv1/conv_13")}},extractPredictionLayerParams:function(){return{conv_0:r(1024,256,1,"prediction_layer/conv_0"),conv_1:r(256,512,3,"prediction_layer/conv_1"),conv_2:r(512,128,1,"prediction_layer/conv_2"),conv_3:r(128,256,3,"prediction_layer/conv_3"),conv_4:r(256,128,1,"prediction_layer/conv_4"),conv_5:r(128,256,3,"prediction_layer/conv_5"),conv_6:r(256,64,1,"prediction_layer/conv_6"),conv_7:r(64,128,3,"prediction_layer/conv_7"),box_predictor_0:{box_encoding_predictor:n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),class_predictor:n(512,9,1,"prediction_layer/box_predictor_0/class_predictor")},box_predictor_1:{box_encoding_predictor:n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),class_predictor:n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor")},box_predictor_2:{box_encoding_predictor:n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),class_predictor:n(512,18,1,"prediction_layer/box_predictor_2/class_predictor")},box_predictor_3:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_3/class_predictor")},box_predictor_4:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_4/class_predictor")},box_predictor_5:{box_encoding_predictor:n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),class_predictor:n(128,18,1,"prediction_layer/box_predictor_5/class_predictor")}}}}}function Nd(t){var e=[],n=function(t,e){var n=Hp(t,e);function r(t,e,r){return{filters:n(t+"/Conv2d_"+e+"_pointwise/weights",4,r+"/filters"),batch_norm_offset:n(t+"/Conv2d_"+e+"_pointwise/convolution_bn_offset",1,r+"/batch_norm_offset")}}function o(t){var e="mobilenetv1/conv_"+t,o="MobilenetV1/Conv2d_"+t+"_depthwise",i=e+"/depthwise_conv",a=e+"/pointwise_conv";return{depthwise_conv:{filters:n(o+"/depthwise_weights",4,i+"/filters"),batch_norm_scale:n(o+"/BatchNorm/gamma",1,i+"/batch_norm_scale"),batch_norm_offset:n(o+"/BatchNorm/beta",1,i+"/batch_norm_offset"),batch_norm_mean:n(o+"/BatchNorm/moving_mean",1,i+"/batch_norm_mean"),batch_norm_variance:n(o+"/BatchNorm/moving_variance",1,i+"/batch_norm_variance")},pointwise_conv:r("MobilenetV1",t,a)}}function i(t,e){return{filters:n(t+"/weights",4,e+"/filters"),bias:n(t+"/biases",1,e+"/bias")}}function a(t){return{box_encoding_predictor:i("Prediction/BoxPredictor_"+t+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+t+"/box_encoding_predictor"),class_predictor:i("Prediction/BoxPredictor_"+t+"/ClassPredictor","prediction_layer/box_predictor_"+t+"/class_predictor")}}return{extractMobilenetV1Params:function(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:o(1),conv_2:o(2),conv_3:o(3),conv_4:o(4),conv_5:o(5),conv_6:o(6),conv_7:o(7),conv_8:o(8),conv_9:o(9),conv_10:o(10),conv_11:o(11),conv_12:o(12),conv_13:o(13)}},extractPredictionLayerParams:function(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:a(0),box_predictor_1:a(1),box_predictor_2:a(2),box_predictor_3:a(3),box_predictor_4:a(4),box_predictor_5:a(5)}}}}(t,e),r=n.extractMobilenetV1Params,o=n.extractPredictionLayerParams,i=t["Output/extra_dim"];if(e.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!kf(i))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+i);var a={mobilenetv1:r(),prediction_layer:o(),output_layer:{extra_dim:i}};return Lp(t,e),{params:a,paramMappings:e}}function Fd(t,e,n){return Ue((function(){var r=Ju(t,e.filters,n,"same");return r=lu(r,e.batch_norm_offset),ys(r,0,6)}))}function Md(t,e){return Ue((function(){var n=null,r=Fd(t,e.conv_0,[2,2]);if([e.conv_1,e.conv_2,e.conv_3,e.conv_4,e.conv_5,e.conv_6,e.conv_7,e.conv_8,e.conv_9,e.conv_10,e.conv_11,e.conv_12,e.conv_13].forEach((function(t,e){var o=e+1,i=function(t){return[2,4,6,12].some((function(e){return e===t}))?[2,2]:[1,1]}(o);r=function(t,e,n){return Ue((function(){var r=ec(t,e.filters,n,"same");return r=tu(r,e.batch_norm_mean,e.batch_norm_variance,e.batch_norm_offset,e.batch_norm_scale,.0010000000474974513),ys(r,0,6)}))}(r,t.depthwise_conv,i),r=Fd(r,t.pointwise_conv,[1,1]),11===o&&(n=r)})),null===n)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}}))}function Od(t,e,n){var r=t.arraySync(),o=Math.min(r[e][0],r[e][2]),i=Math.min(r[e][1],r[e][3]),a=Math.max(r[e][0],r[e][2]),s=Math.max(r[e][1],r[e][3]),u=Math.min(r[n][0],r[n][2]),c=Math.min(r[n][1],r[n][3]),l=Math.max(r[n][0],r[n][2]),h=Math.max(r[n][1],r[n][3]),f=(a-o)*(s-i),p=(l-u)*(h-c);if(f<=0||p<=0)return 0;var d=Math.max(o,u),v=Math.max(i,c),m=Math.min(a,l),g=Math.min(s,h),y=Math.max(m-d,0)*Math.max(g-v,0);return y/(f+p-y)}function Pd(t,e){var n=function(t){var e=fr(qc(t,[1,0])),n=[Du(e[2],e[0]),Du(e[3],e[1])];return{sizes:n,centers:[lu(e[0],du(n[0],hn(2))),lu(e[1],du(n[1],hn(2)))]}}(t),r=n.sizes,o=n.centers,i=fr(qc(e,[1,0])),a=du(_u(Cs(du(i[2],hn(5))),r[0]),hn(2)),s=lu(_u(du(i[0],hn(10)),r[0]),o[0]),u=du(_u(Cs(du(i[3],hn(5))),r[1]),hn(2)),c=lu(_u(du(i[1],hn(10)),r[1]),o[1]);return qc(cr([Du(s,a),Du(c,u),lu(s,a),lu(c,u)]),[1,0])}function Bd(t,e){return Ue((function(){var n=t.shape[0];return{boxPredictionEncoding:ar(Bp(t,e.box_encoding_predictor),[n,-1,1,4]),classPrediction:ar(Bp(t,e.class_predictor),[n,-1,3])}}))}var Ld=function(){function t(t){var e=void 0===t?{}:t,n=e.minConfidence,r=e.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=n||.5,this._maxResults=r||100,"number"!=typeof this._minConfidence||this._minConfidence<=0||this._minConfidence>=1)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if("number"!=typeof this._maxResults)throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(t.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),t}(),Wd=function(t){function e(){return t.call(this,"SsdMobilenetv1")||this}return wf(e,t),e.prototype.forwardInput=function(t){var e=this.params;if(!e)throw new Error("SsdMobilenetv1 - load model before inference");return Ue((function(){var n=t.toBatchTensor(512,!1).toFloat(),r=Md(Du(_u(n,hn(.007843137718737125)),hn(1)),e.mobilenetv1),o=function(t,e,n){return Ue((function(){var r=Fd(t,n.conv_0,[1,1]),o=Fd(r,n.conv_1,[2,2]),i=Fd(o,n.conv_2,[1,1]),a=Fd(i,n.conv_3,[2,2]),s=Fd(a,n.conv_4,[1,1]),u=Fd(s,n.conv_5,[2,2]),c=Fd(u,n.conv_6,[1,1]),l=Fd(c,n.conv_7,[2,2]),h=Bd(e,n.box_predictor_0),f=Bd(t,n.box_predictor_1),p=Bd(o,n.box_predictor_2),d=Bd(a,n.box_predictor_3),v=Bd(u,n.box_predictor_4),m=Bd(l,n.box_predictor_5);return{boxPredictions:Cn([h.boxPredictionEncoding,f.boxPredictionEncoding,p.boxPredictionEncoding,d.boxPredictionEncoding,v.boxPredictionEncoding,m.boxPredictionEncoding],1),classPredictions:Cn([h.classPrediction,f.classPrediction,p.classPrediction,d.classPrediction,v.classPrediction,m.classPrediction],1)}}))}(r.out,r.conv11,e.prediction_layer);return function(t,e,n){return Ue((function(){var r=t.shape[0],o=Pd(ar(lr(n.extra_dim,[r,1,1]),[-1,4]),ar(t,[-1,4]));o=ar(o,[r,o.shape[0]/r,4]);var i=Ns(Cc(e,[0,0,1],[-1,-1,-1])),a=Cc(i,[0,0,0],[-1,-1,1]);return a=ar(a,[r,a.shape[1]]),{boxes:fr(o),scores:fr(a)}}))}(o.boxPredictions,o.classPredictions,e.output_layer)}))},e.prototype.forward=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=this.forwardInput,[4,Rp(t)];case 1:return[2,e.apply(this,[n.sent()])]}}))}))},e.prototype.locateFaces=function(t,e){return void 0===e&&(e={}),Ef(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,c,l,h,f,p,d,v,m,g,y,x,b,w;return _f(this,(function(C){switch(C.label){case 0:return n=new Ld(e),r=n.maxResults,o=n.minConfidence,[4,Rp(t)];case 1:for(i=C.sent(),a=this.forwardInput(i),s=a.boxes,u=a.scores,c=s[0],l=u[0],h=1;h<s.length;h++)s[h].dispose(),u[h].dispose();return d=(p=Array).from,[4,l.data()];case 2:return f=d.apply(p,[C.sent()]),.5,v=function(t,e,n,r,o){var i=t.shape[0],a=Math.min(n,i),s=e.map((function(t,e){return{score:t,boxIndex:e}})).filter((function(t){return t.score>o})).sort((function(t,e){return e.score-t.score})),u=function(t){return t<=r?1:0},c=[];return s.forEach((function(e){if(!(c.length>=a)){for(var n=e.score,r=c.length-1;r>=0;--r){var i=Od(t,e.boxIndex,c[r]);if(0!==i&&(e.score*=u(i),e.score<=o))break}n===e.score&&c.push(e.boxIndex)}})),c}(c,f,r,.5,o),m=i.getReshapedInputDimensions(0),g=i.inputSize,y=g/m.width,x=g/m.height,b=c.arraySync(),w=v.map((function(t){var e=[Math.max(0,b[t][0]),Math.min(1,b[t][2])].map((function(t){return t*x})),n=e[0],r=e[1],o=[Math.max(0,b[t][1]),Math.min(1,b[t][3])].map((function(t){return t*y})),a=o[0],s=o[1];return new Uf(f[t],new jf(a,n,s-a,r-n),{height:i.getInputHeight(0),width:i.getInputWidth(0)})})),c.dispose(),l.dispose(),[2,w]}}))}))},e.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},e.prototype.extractParamsFromWeigthMap=function(t){return Nd(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=qp(t),r=n.extractWeights,o=n.getRemainingWeights,i=Td(r,e),a=i.extractMobilenetV1Params,s=i.extractPredictionLayerParams,u=a(),c=s(),l={extra_dim:dn(r(20472),[1,5118,4])};if(e.push({paramPath:"output_layer/extra_dim"}),0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{params:{mobilenetv1:u,prediction_layer:c,output_layer:l},paramMappings:e}}(t)},e}(Fp);!function(t){function e(){return null!==t&&t.apply(this,arguments)||this}wf(e,t)}(Wd);var zd,Ud=[new Bf(.738768,.874946),new Bf(2.42204,2.65704),new Bf(4.30971,7.04493),new Bf(10.246,4.59428),new Bf(12.6868,11.8741)],Vd=[new Bf(1.603231,2.094468),new Bf(6.041143,7.080126),new Bf(2.882459,3.518061),new Bf(4.266906,5.178857),new Bf(9.041765,10.66308)],Gd=[117.001,114.697,97.404],Hd=function(t){return"number"==typeof t};function qd(t){return Ue((function(){var e=_u(t,hn(.10000000149011612));return lu(Vc(Du(t,e)),e)}))}function jd(t,e){return Ue((function(){var n=Jn(t,[[0,0],[1,1],[1,1],[0,0]]);return n=Ju(n,e.conv.filters,[1,1],"valid"),n=Du(n,e.bn.sub),n=_u(n,e.bn.truediv),qd(n=lu(n,e.conv.bias))}))}function Kd(t,e){return Ue((function(){var n=Jn(t,[[0,0],[1,1],[1,1],[0,0]]);return n=oc(n,e.depthwise_filter,e.pointwise_filter,[1,1],"valid"),qd(n=lu(n,e.bias))}))}function Xd(t,e){var n=Wp(t,e);var r=Vp(t,e);return{extractConvParams:n,extractConvWithBatchNormParams:function(r,o,i){var a=n(r,o,3,i+"/conv"),s=function(n,r){var o=fn(t(n)),i=fn(t(n));return e.push({paramPath:r+"/sub"},{paramPath:r+"/truediv"}),{sub:o,truediv:i}}(o,i+"/bn");return{conv:a,bn:s}},extractSeparableConvParams:r}}function Yd(t,e){var n=Hp(t,e);function r(t){return{filters:n(t+"/filters",4),bias:n(t+"/bias",1)}}return{extractConvParams:r,extractConvWithBatchNormParams:function(t){var e=r(t+"/conv"),o=function(t){return{sub:n(t+"/sub",1),truediv:n(t+"/truediv",1)}}(t+"/bn");return{conv:e,bn:o}},extractSeparableConvParams:Gp(n)}}!function(t){t[t.XS=224]="XS",t[t.SM=320]="SM",t[t.MD=416]="MD",t[t.LG=608]="LG"}(zd||(zd={}));var $d=function(){function t(t){var e=void 0===t?{}:t,n=e.inputSize,r=e.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=n||416,this._scoreThreshold=r||.5,"number"!=typeof this._inputSize||this._inputSize%32!=0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if("number"!=typeof this._scoreThreshold||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(t.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),t}(),Jd=function(t){function e(e){var n=t.call(this,"TinyYolov2")||this;return function(t){if(!t)throw new Error("invalid config: "+t);if("boolean"!=typeof t.withSeparableConvs)throw new Error("config.withSeparableConvs has to be a boolean, have: "+t.withSeparableConvs);if(!Hd(t.iouThreshold)||t.iouThreshold<0||t.iouThreshold>1)throw new Error("config.iouThreshold has to be a number between [0, 1], have: "+t.iouThreshold);if(!Array.isArray(t.classes)||!t.classes.length||!t.classes.every((function(t){return"string"==typeof t})))throw new Error("config.classes has to be an array class names: string[], have: "+JSON.stringify(t.classes));if(!Array.isArray(t.anchors)||!t.anchors.length||!t.anchors.map((function(t){return t||{}})).every((function(t){return Hd(t.x)&&Hd(t.y)})))throw new Error("config.anchors has to be an array of { x: number, y: number }, have: "+JSON.stringify(t.anchors));if(t.meanRgb&&(!Array.isArray(t.meanRgb)||3!==t.meanRgb.length||!t.meanRgb.every(Hd)))throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: "+JSON.stringify(t.meanRgb))}(e),n._config=e,n}return wf(e,t),Object.defineProperty(e.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"withClassScores",{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"boxEncodingSize",{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),e.prototype.runTinyYolov2=function(t,e){var n=jd(t,e.conv0);return n=jd(n=gc(n,[2,2],[2,2],"same"),e.conv1),n=jd(n=gc(n,[2,2],[2,2],"same"),e.conv2),n=jd(n=gc(n,[2,2],[2,2],"same"),e.conv3),n=jd(n=gc(n,[2,2],[2,2],"same"),e.conv4),n=jd(n=gc(n,[2,2],[2,2],"same"),e.conv5),n=jd(n=gc(n,[2,2],[1,1],"same"),e.conv6),Bp(n=jd(n,e.conv7),e.conv8,"valid",!1)},e.prototype.runMobilenet=function(t,e){var n=this.config.isFirstLayerConv2d?qd(Bp(t,e.conv0,"valid",!1)):Kd(t,e.conv0);return n=Kd(n=gc(n,[2,2],[2,2],"same"),e.conv1),n=Kd(n=gc(n,[2,2],[2,2],"same"),e.conv2),n=Kd(n=gc(n,[2,2],[2,2],"same"),e.conv3),n=Kd(n=gc(n,[2,2],[2,2],"same"),e.conv4),n=Kd(n=gc(n,[2,2],[2,2],"same"),e.conv5),n=gc(n,[2,2],[1,1],"same"),n=e.conv6?Kd(n,e.conv6):n,Bp(n=e.conv7?Kd(n,e.conv7):n,e.conv8,"valid",!1)},e.prototype.forwardInput=function(t,e){var n=this,r=this.params;if(!r)throw new Error("TinyYolov2 - load model before inference");return Ue((function(){var o=t.toBatchTensor(e,!1).toFloat();return o=(o=n.config.meanRgb?Hf(o,n.config.meanRgb):o).div(hn(256)),n.config.withSeparableConvs?n.runMobilenet(o,r):n.runTinyYolov2(o,r)}))},e.prototype.forward=function(t,e){return Ef(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[4,n.apply(this,[r.sent(),e])];case 2:return[2,r.sent()]}}))}))},e.prototype.detect=function(t,e){return void 0===e&&(e={}),Ef(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,c,l,h,f,p,d,v=this;return _f(this,(function(m){switch(m.label){case 0:return n=new $d(e),r=n.inputSize,o=n.scoreThreshold,[4,Rp(t)];case 1:return i=m.sent(),[4,this.forwardInput(i,r)];case 2:return a=m.sent(),s=Ue((function(){return fr(a)[0].expandDims()})),u={width:i.getInputWidth(0),height:i.getInputHeight(0)},[4,this.extractBoxes(s,i.getReshapedInputDimensions(0),o)];case 3:return c=m.sent(),a.dispose(),s.dispose(),l=c.map((function(t){return t.box})),h=c.map((function(t){return t.score})),f=c.map((function(t){return t.classScore})),p=c.map((function(t){return v.config.classes[t.label]})),d=Gf(l.map((function(t){return t.rescale(r)})),h,this.config.iouThreshold,!0),[2,d.map((function(t){return new zf(h[t],f[t],p[t],l[t],u)}))]}}))}))},e.prototype.getDefaultModelName=function(){return""},e.prototype.extractParamsFromWeigthMap=function(t){return function(t,e){var n,r=[],o=Yd(t,r),i=o.extractConvParams,a=o.extractConvWithBatchNormParams,s=o.extractSeparableConvParams;if(e.withSeparableConvs){var u=e.filterSizes&&e.filterSizes.length||9;n={conv0:e.isFirstLayerConv2d?i("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:u>7?s("conv6"):void 0,conv7:u>8?s("conv7"):void 0,conv8:i("conv8")}}else n={conv0:a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:a("conv6"),conv7:a("conv7"),conv8:i("conv8")};return Lp(t,r),{params:n,paramMappings:r}}(t,this.config)},e.prototype.extractParams=function(t){var n=this.config.filterSizes||e.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(7!==r&&8!==r&&9!==r)throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found "+r+" filterSizes in config");return function(t,e,n,r){var o,i=qp(t),a=i.extractWeights,s=i.getRemainingWeights,u=[],c=Xd(a,u),l=c.extractConvParams,h=c.extractConvWithBatchNormParams,f=c.extractSeparableConvParams;if(e.withSeparableConvs){var p=r[0],d=r[1],v=r[2],m=r[3],g=r[4],y=r[5],x=r[6],b=r[7],w=r[8];o={conv0:e.isFirstLayerConv2d?l(p,d,3,"conv0"):f(p,d,"conv0"),conv1:f(d,v,"conv1"),conv2:f(v,m,"conv2"),conv3:f(m,g,"conv3"),conv4:f(g,y,"conv4"),conv5:f(y,x,"conv5"),conv6:b?f(x,b,"conv6"):void 0,conv7:w?f(b,w,"conv7"):void 0,conv8:l(w||b||x,5*n,1,"conv8")}}else p=r[0],d=r[1],v=r[2],m=r[3],g=r[4],y=r[5],x=r[6],b=r[7],w=r[8],o={conv0:h(p,d,"conv0"),conv1:h(d,v,"conv1"),conv2:h(v,m,"conv2"),conv3:h(m,g,"conv3"),conv4:h(g,y,"conv4"),conv5:h(y,x,"conv5"),conv6:h(x,b,"conv6"),conv7:h(b,w,"conv7"),conv8:l(w,5*n,1,"conv8")};if(0!==s().length)throw new Error("weights remaing after extract: "+s().length);return{params:o,paramMappings:u}}(t,this.config,this.boxEncodingSize,n)},e.prototype.extractBoxes=function(t,e,n){return Ef(this,void 0,void 0,(function(){var r,o,i,a,s,u,c,l,h,f,p,d,v,m,g,y,x,b,w,C,E,_,I,R,S,k,D,A,T,N=this;return _f(this,(function(F){switch(F.label){case 0:return r=e.width,o=e.height,i=Math.max(r,o),a=i/r,s=i/o,u=t.shape[1],c=this.config.anchors.length,l=Ue((function(){var e=t.reshape([u,u,c,N.boxEncodingSize]);return[e.slice([0,0,0,0],[u,u,c,4]),e.slice([0,0,0,4],[u,u,c,1]),N.withClassScores?Tr(e.slice([0,0,0,5],[u,u,c,N.config.classes.length]),3):hn(0)]})),h=l[0],f=l[1],p=l[2],d=[],[4,f.array()];case 1:return v=F.sent(),[4,h.array()];case 2:m=F.sent(),g=0,F.label=3;case 3:if(!(g<u))return[3,12];y=0,F.label=4;case 4:if(!(y<u))return[3,11];x=0,F.label=5;case 5:return x<c?(b=qf(v[g][y][x][0]),!n||b>n?(w=(y+qf(m[g][y][x][0]))/u*a,C=(g+qf(m[g][y][x][1]))/u*s,E=Math.exp(m[g][y][x][2])*this.config.anchors[x].x/u*a,_=Math.exp(m[g][y][x][3])*this.config.anchors[x].y/u*s,I=w-E/2,R=C-_/2,S={row:g,col:y,anchor:x},this.withClassScores?[4,this.extractPredictedClass(p,S)]:[3,7]):[3,9]):[3,10];case 6:return T=F.sent(),[3,8];case 7:T={classScore:1,label:0},F.label=8;case 8:D=(k=T).classScore,A=k.label,d.push(Cf({box:new Wf(I,R,I+E,R+_),score:b,classScore:b*D,label:A},S)),F.label=9;case 9:return x++,[3,5];case 10:return y++,[3,4];case 11:return g++,[3,3];case 12:return h.dispose(),f.dispose(),p.dispose(),[2,d]}}))}))},e.prototype.extractPredictedClass=function(t,e){return Ef(this,void 0,void 0,(function(){var n,r,o,i;return _f(this,(function(a){switch(a.label){case 0:return n=e.row,r=e.col,o=e.anchor,[4,t.array()];case 1:return i=a.sent(),[2,Array(this.config.classes.length).fill(0).map((function(t,e){return i[n][r][o][e]})).map((function(t,e){return{classScore:t,label:e}})).reduce((function(t,e){return t.classScore>e.classScore?t:e}))]}}))}))},e.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],e}(Fp),Qd=function(t){function e(e){void 0===e&&(e=!0);var n=Object.assign({},{withSeparableConvs:e,iouThreshold:.4,classes:["face"]},e?{anchors:Vd,meanRgb:Gd}:{anchors:Ud,withClassScores:!0});return t.call(this,n)||this}return wf(e,t),Object.defineProperty(e.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),e.prototype.locateFaces=function(t,e){return Ef(this,void 0,void 0,(function(){return _f(this,(function(n){switch(n.label){case 0:return[4,this.detect(t,e)];case 1:return[2,n.sent().map((function(t){return new Uf(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})}))]}}))}))},e.prototype.getDefaultModelName=function(){return this.withSeparableConvs?"tiny_yolov2_separable_conv_model":"tiny_yolov2_model"},e.prototype.extractParamsFromWeigthMap=function(e){return t.prototype.extractParamsFromWeigthMap.call(this,e)},e}(Jd);var Zd=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._name="TinyFaceDetectorOptions",e}return wf(e,t),e}($d),tv=function(){function t(){}return t.prototype.then=function(t){return Ef(this,void 0,void 0,(function(){var e;return _f(this,(function(n){switch(n.label){case 0:return e=t,[4,this.run()];case 1:return[2,e.apply(void 0,[n.sent()])]}}))}))},t.prototype.run=function(){return Ef(this,void 0,void 0,(function(){return _f(this,(function(t){throw new Error("ComposableTask - run is not implemented")}))}))},t}();function ev(t,e){var n={descriptor:e};return Object.assign({},t,n)}function nv(t,e,n,r,o){return void 0===o&&(o=function(t){return t.alignedRect}),Ef(this,void 0,void 0,(function(){var i,a,s,u,c;return _f(this,(function(l){switch(l.label){case 0:return i=t.map((function(t){return od(t)?o(t):t.detection})),(s=r)?[3,5]:e instanceof xt?[4,kp(e,i)]:[3,2];case 1:return u=l.sent(),[3,4];case 2:return[4,Sp(e,i)];case 3:u=l.sent(),l.label=4;case 4:s=u,l.label=5;case 5:return[4,n(a=s)];case 6:return c=l.sent(),a.forEach((function(t){return t instanceof xt&&t.dispose()})),[2,c]}}))}))}function rv(t,e,n,r,o){return Ef(this,void 0,void 0,(function(){var i=this;return _f(this,(function(a){return[2,nv([t],e,(function(t){return Ef(i,void 0,void 0,(function(){return _f(this,(function(e){return[2,n(t[0])]}))}))}),r,o)]}))}))}function ov(t){var e=qp(t),n=e.extractWeights,r=e.getRemainingWeights,o=[],i=function(t,e){var n=Wp(t,e),r=zp(t,e);function o(n,r){var o=fn(t(n));return e.push({paramPath:r}),o}function i(t,e,r){return void 0===r&&(r=!1),{conv1:n(t[0],t[1],3,e+"/conv1"),prelu1_alpha:o(t[1],e+"/prelu1_alpha"),conv2:n(t[1],t[2],3,e+"/conv2"),prelu2_alpha:o(t[2],e+"/prelu2_alpha"),conv3:n(t[2],t[3],r?2:3,e+"/conv3"),prelu3_alpha:o(t[3],e+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=i([3,10,16,32],"pnet"),e=n(32,2,1,"pnet/conv4_1"),r=n(32,4,1,"pnet/conv4_2");return Cf(Cf({},t),{conv4_1:e,conv4_2:r})},extractRNetParams:function(){var t=i([3,28,48,64],"rnet",!0),e=r(576,128,"rnet/fc1"),n=o(128,"rnet/prelu4_alpha"),a=r(128,2,"rnet/fc2_1"),s=r(128,4,"rnet/fc2_2");return Cf(Cf({},t),{fc1:e,prelu4_alpha:n,fc2_1:a,fc2_2:s})},extractONetParams:function(){var t=i([3,32,64,64],"onet"),e=n(64,128,2,"onet/conv4"),a=o(128,"onet/prelu4_alpha"),s=r(1152,256,"onet/fc1"),u=o(256,"onet/prelu5_alpha"),c=r(256,2,"onet/fc2_1"),l=r(256,4,"onet/fc2_2"),h=r(256,10,"onet/fc2_3");return Cf(Cf({},t),{conv4:e,prelu4_alpha:a,fc1:s,prelu5_alpha:u,fc2_1:c,fc2_2:l,fc2_3:h})}}}(n,o),a=i.extractPNetParams,s=i.extractRNetParams,u=i.extractONetParams,c=a(),l=s(),h=u();if(0!==r().length)throw new Error("weights remaing after extract: "+r().length);return{params:{pnet:c,rnet:l,onet:h},paramMappings:o}}function iv(t){var e=[],n=function(t,e){var n=Hp(t,e);function r(t){return{filters:n(t+"/weights",4,t+"/filters"),bias:n(t+"/bias",1)}}function o(t){return{weights:n(t+"/weights",2),bias:n(t+"/bias",1)}}function i(t){return n(t,1)}function a(t){return{conv1:r(t+"/conv1"),prelu1_alpha:i(t+"/prelu1_alpha"),conv2:r(t+"/conv2"),prelu2_alpha:i(t+"/prelu2_alpha"),conv3:r(t+"/conv3"),prelu3_alpha:i(t+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=a("pnet"),e=r("pnet/conv4_1"),n=r("pnet/conv4_2");return Cf(Cf({},t),{conv4_1:e,conv4_2:n})},extractRNetParams:function(){var t=a("rnet"),e=o("rnet/fc1"),n=i("rnet/prelu4_alpha"),r=o("rnet/fc2_1"),s=o("rnet/fc2_2");return Cf(Cf({},t),{fc1:e,prelu4_alpha:n,fc2_1:r,fc2_2:s})},extractONetParams:function(){var t=a("onet"),e=r("onet/conv4"),n=i("onet/prelu4_alpha"),s=o("onet/fc1"),u=i("onet/prelu5_alpha"),c=o("onet/fc2_1"),l=o("onet/fc2_2"),h=o("onet/fc2_3");return Cf(Cf({},t),{conv4:e,prelu4_alpha:n,fc1:s,prelu5_alpha:u,fc2_1:c,fc2_2:l,fc2_3:h})}}}(t,e),r=n.extractPNetParams,o=n.extractRNetParams,i=n.extractONetParams,a=r(),s=o(),u=i();return Lp(t,e),{params:{pnet:a,rnet:s,onet:u},paramMappings:e}}function av(t,e){var n=e[0],r=e[1];return{height:Math.floor(n*t),width:Math.floor(r*t)}}var sv=function(t){function e(e,n,r,o){return t.call(this,{left:e,top:n,right:r,bottom:o},!0)||this}return wf(e,t),e}(Lf);function uv(t){return Ue((function(){return _u(Du(t,hn(127.5)),hn(.0078125))}))}function cv(t,e){return Ue((function(){return lu(Vc(t),_u(e,ks(Vc(ks(t)))))}))}function lv(t,e,n){return void 0===n&&(n=!1),Ue((function(){var r=Bp(t,e.conv1,"valid");return r=cv(r,e.prelu1_alpha),r=cv(r=Bp(r=gc(r,n?[2,2]:[3,3],[2,2],"same"),e.conv2,"valid"),e.prelu2_alpha),r=cv(r=Bp(r=n?r:gc(r,[3,3],[2,2],"valid"),e.conv3,"valid"),e.prelu3_alpha)}))}function hv(t,e,n,r,o){o.stage1=[];var i=e.map((function(e){return Ue((function(){var n={scale:e},o=function(t,e){return Ue((function(){var n=av(e,t.shape.slice(1)),r=n.height,o=n.width,i=uv(Bl.resizeBilinear(t,[r,o]));return qc(i,[0,2,1,3])}))}(t,e),i=Date.now(),a=function(t,e){return Ue((function(){var n=lv(t,e,!0),r=Bp(n,e.conv4_1,"valid"),o=Kn(Fc(r,3),3);return{prob:Tr(Du(r,o),3),regions:Bp(n,e.conv4_2,"valid")}}))}(o,r),s=a.prob,u=a.regions;return n.pnet=Date.now()-i,{scoresTensor:fr(fr(s,3)[1])[0],regionsTensor:fr(u)[0],scale:e,statsForScale:n}}))})),a=i.map((function(t){var e=t.scoresTensor,r=t.regionsTensor,i=t.scale,a=t.statsForScale,s=function(t,e,n,r){for(var o=[],i=t.arraySync(),a=0;a<t.shape[0];a++)for(var s=0;s<t.shape[1];s++)i[a][s]>=r&&o.push(new Bf(s,a));return o.map((function(t){var r=new Wf(Math.round((2*t.y+1)/n),Math.round((2*t.x+1)/n),Math.round((2*t.y+12)/n),Math.round((2*t.x+12)/n)),o=i[t.y][t.x],a=e.arraySync();return{cell:r,score:o,region:new sv(a[t.y][t.x][0],a[t.y][t.x][1],a[t.y][t.x][2],a[t.y][t.x][3])}}))}(e,r,i,n);if(e.dispose(),r.dispose(),!s.length)return o.stage1.push(a),[];var u=Date.now(),c=Gf(s.map((function(t){return t.cell})),s.map((function(t){return t.score})),.5);return a.nms=Date.now()-u,a.numBoxes=c.length,o.stage1.push(a),c.map((function(t){return s[t]}))})),s=a.reduce((function(t,e){return t.concat(e)}),[]),u=[],c=[];if(s.length>0){var l=Date.now(),h=Gf(s.map((function(t){return t.cell})),s.map((function(t){return t.score})),.7);o.stage1_nms=Date.now()-l,c=h.map((function(t){return s[t].score})),u=h.map((function(t){return s[t]})).map((function(t){var e=t.cell,n=t.region;return new Wf(e.left+n.left*e.width,e.top+n.top*e.height,e.right+n.right*e.width,e.bottom+n.bottom*e.height).toSquare().round()}))}return{boxes:u,scores:c}}function fv(t,e,n){var r=n.width,o=n.height;return Ef(this,void 0,void 0,(function(){var n,i,a,s=this;return _f(this,(function(u){switch(u.label){case 0:return n=pp(t),[4,Promise.all(e.map((function(e){return Ef(s,void 0,void 0,(function(){var r,o,i,a,s,u,c,l;return _f(this,(function(h){return r=e.padAtBorders(t.height,t.width),o=r.y,i=r.ey,a=r.x,s=r.ex,u=a-1,c=o-1,l=n.getImageData(u,c,s-u,i-c),[2,hp.isNodejs()?Cp(l):createImageBitmap(l)]}))}))})))];case 1:return i=u.sent(),a=[],i.forEach((function(t){var e=pp(wp({width:r,height:o}));e.drawImage(t,0,0,r,o);for(var n=e.getImageData(0,0,r,o).data,i=[],s=0;s<n.length;s+=4)i.push(n[s+2]),i.push(n[s+1]),i.push(n[s]);a.push(i)})),[2,a.map((function(t){return Ue((function(){return uv(qc(vn(t,[1,r,o,3]),[0,2,1,3]).toFloat())}))}))]}}))}))}function pv(t,e,n,r,o){return Ef(this,void 0,void 0,(function(){var i,a,s,u,c,l,h,f,p,d,v,m,g,y;return _f(this,(function(x){switch(x.label){case 0:return i=Date.now(),[4,fv(t,e,{width:24,height:24})];case 1:return a=x.sent(),o.stage2_extractImagePatches=Date.now()-i,i=Date.now(),s=a.map((function(t){var e=function(t,e){return Ue((function(){var n=lv(t,e),r=cv($p(ar(n,[n.shape[0],e.fc1.weights.shape[0]]),e.fc1),e.prelu4_alpha),o=$p(r,e.fc2_1),i=Kn(Fc(o,1),1),a=Tr(Du(o,i),1),s=$p(r,e.fc2_2);return{scores:fr(a,1)[1],regions:s}}))}(t,r);return t.dispose(),e})),o.stage2_rnet=Date.now()-i,u=s.length>1?Cn(s.map((function(t){return t.scores}))):s[0].scores,h=(l=Array).from,[4,u.data()];case 2:return c=h.apply(l,[x.sent()]),u.dispose(),f=c.map((function(t,e){return{score:t,idx:e}})).filter((function(t){return t.score>n})).map((function(t){return t.idx})),p=f.map((function(t){return e[t]})),d=f.map((function(t){return c[t]})),v=[],m=[],p.length>0&&(i=Date.now(),g=Gf(p,d,.7),o.stage2_nms=Date.now()-i,y=g.map((function(t){var e=s[f[t]].regions.arraySync();return new sv(e[0][0],e[0][1],e[0][2],e[0][3])})),m=g.map((function(t){return d[t]})),v=g.map((function(t,e){return p[t].calibrate(y[e])}))),s.forEach((function(t){t.regions.dispose(),t.scores.dispose()})),[2,{boxes:v,scores:m}]}}))}))}function dv(t,e,n,r,o){return Ef(this,void 0,void 0,(function(){var i,a,s,u,c,l,h,f,p,d,v,m,g,y,x;return _f(this,(function(b){switch(b.label){case 0:return i=Date.now(),[4,fv(t,e,{width:48,height:48})];case 1:return a=b.sent(),o.stage3_extractImagePatches=Date.now()-i,i=Date.now(),s=a.map((function(t){var e=function(t,e){return Ue((function(){var n=lv(t,e);n=cv(n=Bp(n=gc(n,[2,2],[2,2],"same"),e.conv4,"valid"),e.prelu4_alpha);var r=cv($p(ar(n,[n.shape[0],e.fc1.weights.shape[0]]),e.fc1),e.prelu5_alpha),o=$p(r,e.fc2_1),i=Kn(Fc(o,1),1),a=Tr(Du(o,i),1),s=$p(r,e.fc2_2),u=$p(r,e.fc2_3);return{scores:fr(a,1)[1],regions:s,points:u}}))}(t,r);return t.dispose(),e})),o.stage3_onet=Date.now()-i,u=s.length>1?Cn(s.map((function(t){return t.scores}))):s[0].scores,h=(l=Array).from,[4,u.data()];case 2:return c=h.apply(l,[b.sent()]),u.dispose(),f=c.map((function(t,e){return{score:t,idx:e}})).filter((function(t){return t.score>n})).map((function(t){return t.idx})),p=f.map((function(t){var e=s[t].regions.arraySync();return new sv(e[0][0],e[0][1],e[0][2],e[0][3])})),d=f.map((function(t,n){return e[t].calibrate(p[n])})),v=f.map((function(t){return c[t]})),m=[],g=[],y=[],d.length>0&&(i=Date.now(),x=Gf(d,v,.7,!1),o.stage3_nms=Date.now()-i,m=x.map((function(t){return d[t]})),g=x.map((function(t){return v[t]})),y=x.map((function(t,e){return Array(5).fill(0).map((function(n,r){var o=s[t].points.arraySync();return new Bf(o[0][r]*(m[e].width+1)+m[e].left,o[0][r+5]*(m[e].height+1)+m[e].top)}))}))),s.forEach((function(t){t.regions.dispose(),t.scores.dispose(),t.points.dispose()})),[2,{boxes:m,scores:g,points:y}]}}))}))}var vv=function(t){function e(){return t.call(this,"Mtcnn")||this}return wf(e,t),e.prototype.load=function(e){return Ef(this,void 0,void 0,(function(){return _f(this,(function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,t.prototype.load.call(this,e)]}))}))},e.prototype.loadFromDisk=function(e){return Ef(this,void 0,void 0,(function(){return _f(this,(function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,t.prototype.loadFromDisk.call(this,e)]}))}))},e.prototype.forwardInput=function(t,e){return void 0===e&&(e={}),Ef(this,void 0,void 0,(function(){var n,r,o,i,a,s,u,c,l,h,f,p,d,v,m,g,y,x,b,w,C;return _f(this,(function(E){switch(E.label){case 0:if(!(n=this.params))throw new Error("Mtcnn - load model before inference");if(!(r=t.canvases[0]))throw new Error("Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.");return o={},i=Date.now(),a=Ue((function(){return t=Kn(nf.fromPixels(r)).toFloat(),Ue((function(){return cr(fr(t,3).reverse(),3)}));var t})),s=function(t){return a.dispose(),o.total=Date.now()-i,t},u=a.shape.slice(1),c=u[0],l=u[1],h=new Ad(e),f=h.minFaceSize,p=h.scaleFactor,d=h.maxNumScales,v=h.scoreThresholds,m=h.scaleSteps,g=(m||function(t,e,n){for(var r=n[0],o=n[1],i=12/t,a=[],s=Math.min(r,o)*i,u=0;s>=12;)a.push(i*Math.pow(e,u)),s*=e,u+=1;return a}(f,p,[c,l])).filter((function(t){var e=av(t,[c,l]);return Math.min(e.width,e.height)>12})).slice(0,d),o.scales=g,o.pyramid=g.map((function(t){return av(t,[c,l])})),y=Date.now(),[4,hv(a,g,v[0],n.pnet,o)];case 1:return x=E.sent(),o.total_stage1=Date.now()-y,x.boxes.length?(o.stage2_numInputBoxes=x.boxes.length,y=Date.now(),[4,pv(r,x.boxes,v[1],n.rnet,o)]):[2,s({results:[],stats:o})];case 2:return b=E.sent(),o.total_stage2=Date.now()-y,b.boxes.length?(o.stage3_numInputBoxes=b.boxes.length,y=Date.now(),[4,dv(r,b.boxes,v[2],n.onet,o)]):[2,s({results:[],stats:o})];case 3:return w=E.sent(),o.total_stage3=Date.now()-y,C=w.boxes.map((function(t,e){return id(tp({},new Uf(w.scores[e],new jf(t.left/l,t.top/c,t.width/l,t.height/c),{height:c,width:l})),new Xf(w.points[e].map((function(e){return e.sub(new Bf(t.left,t.top)).div(new Bf(t.width,t.height))})),{width:t.width,height:t.height}))})),[2,s({results:C,stats:o})]}}))}))},e.prototype.forward=function(t,e){return void 0===e&&(e={}),Ef(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[4,n.apply(this,[r.sent(),e])];case 2:return[2,r.sent().results]}}))}))},e.prototype.forwardWithStats=function(t,e){return void 0===e&&(e={}),Ef(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Rp(t)];case 1:return[2,n.apply(this,[r.sent(),e])]}}))}))},e.prototype.getDefaultModelName=function(){return"mtcnn_model"},e.prototype.extractParamsFromWeigthMap=function(t){return iv(t)},e.prototype.extractParams=function(t){return ov(t)},e}(Fp),mv=[new Bf(1.603231,2.094468),new Bf(6.041143,7.080126),new Bf(2.882459,3.518061),new Bf(4.266906,5.178857),new Bf(9.041765,10.66308)],gv=[117.001,114.697,97.404],yv=function(t){function e(){var e={withSeparableConvs:!0,iouThreshold:.4,classes:["face"],anchors:mv,meanRgb:gv,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return t.call(this,e)||this}return wf(e,t),Object.defineProperty(e.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),e.prototype.locateFaces=function(t,e){return Ef(this,void 0,void 0,(function(){return _f(this,(function(n){switch(n.label){case 0:return[4,this.detect(t,e)];case 1:return[2,n.sent().map((function(t){return new Uf(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})}))]}}))}))},e.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},e.prototype.extractParamsFromWeigthMap=function(e){return t.prototype.extractParamsFromWeigthMap.call(this,e)},e}(Jd),xv={ssdMobilenetv1:new Wd,tinyFaceDetector:new yv,tinyYolov2:new Qd,mtcnn:new vv,faceLandmark68Net:new gd,faceLandmark68TinyNet:new xd,faceRecognitionNet:new kd,faceExpressionNet:new ed,ageGenderNet:new vd},bv=function(t){return xv.tinyFaceDetector.load(t)},wv=function(t){return xv.faceLandmark68Net.load(t)},Cv=function(t){return xv.faceRecognitionNet.load(t)};function Ev(t,e){var n={age:e};return Object.assign({},t,n)}var _v=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.extractedFaces=r,o}return wf(e,t),e}(tv),Iv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n=this;return _f(this,(function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,nv(t=r.sent(),this.input,(function(t){return Ef(n,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return[4,Promise.all(t.map((function(t){return xv.faceExpressionNet.predictExpressions(t)})))];case 1:return[2,e.sent()]}}))}))}),this.extractedFaces)];case 2:return e=r.sent(),[2,t.map((function(t,n){return nd(t,e[n])}))]}}))}))},e.prototype.withAgeAndGender=function(){return new Av(this,this.input)},e}(_v),Rv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e;return _f(this,(function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(t=n.sent())?[4,rv(t,this.input,(function(t){return xv.faceExpressionNet.predictExpressions(t)}),this.extractedFaces)]:[2];case 2:return e=n.sent(),[2,nd(t,e)]}}))}))},e.prototype.withAgeAndGender=function(){return new Tv(this,this.input)},e}(_v),Sv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.withAgeAndGender=function(){return new Nv(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Ov(this,this.input)},e}(Iv),kv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.withAgeAndGender=function(){return new Fv(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Pv(this,this.input)},e}(Rv),Dv=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.extractedFaces=r,o}return wf(e,t),e}(tv),Av=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n=this;return _f(this,(function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,nv(t=r.sent(),this.input,(function(t){return Ef(n,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return[4,Promise.all(t.map((function(t){return xv.ageGenderNet.predictAgeAndGender(t)})))];case 1:return[2,e.sent()]}}))}))}),this.extractedFaces)];case 2:return e=r.sent(),[2,t.map((function(t,n){var r=e[n],o=r.age;return Ev(Dd(t,r.gender,r.genderProbability),o)}))]}}))}))},e.prototype.withFaceExpressions=function(){return new Iv(this,this.input)},e}(Dv),Tv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n,r,o;return _f(this,(function(i){switch(i.label){case 0:return[4,this.parentTask];case 1:return(t=i.sent())?[4,rv(t,this.input,(function(t){return xv.ageGenderNet.predictAgeAndGender(t)}),this.extractedFaces)]:[2];case 2:return e=i.sent(),n=e.age,r=e.gender,o=e.genderProbability,[2,Ev(Dd(t,r,o),n)]}}))}))},e.prototype.withFaceExpressions=function(){return new Rv(this,this.input)},e}(Dv),Nv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.withFaceExpressions=function(){return new Sv(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Ov(this,this.input)},e}(Av),Fv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.withFaceExpressions=function(){return new kv(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Pv(this,this.input)},e}(Tv),Mv=function(t){function e(e,n){var r=t.call(this)||this;return r.parentTask=e,r.input=n,r}return wf(e,t),e}(tv),Ov=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t;return _f(this,(function(e){switch(e.label){case 0:return[4,this.parentTask];case 1:return[4,nv(t=e.sent(),this.input,(function(t){return Promise.all(t.map((function(t){return xv.faceRecognitionNet.computeFaceDescriptor(t)})))}),null,(function(t){return t.landmarks.align(null,{useDlibAlignment:!0})}))];case 2:return[2,e.sent().map((function(e,n){return ev(t[n],e)}))]}}))}))},e.prototype.withFaceExpressions=function(){return new Sv(this,this.input)},e.prototype.withAgeAndGender=function(){return new Nv(this,this.input)},e}(Mv),Pv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e;return _f(this,(function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(t=n.sent())?[4,rv(t,this.input,(function(t){return xv.faceRecognitionNet.computeFaceDescriptor(t)}),null,(function(t){return t.landmarks.align(null,{useDlibAlignment:!0})}))]:[2];case 2:return e=n.sent(),[2,ev(t,e)]}}))}))},e.prototype.withFaceExpressions=function(){return new kv(this,this.input)},e.prototype.withAgeAndGender=function(){return new Fv(this,this.input)},e}(Mv),Bv=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parentTask=e,o.input=n,o.useTinyLandmarkNet=r,o}return wf(e,t),Object.defineProperty(e.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?xv.faceLandmark68TinyNet:xv.faceLandmark68Net},enumerable:!0,configurable:!0}),e}(tv),Lv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n,r,o,i=this;return _f(this,(function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return t=a.sent(),e=t.map((function(t){return t.detection})),this.input instanceof xt?[4,kp(this.input,e)]:[3,3];case 2:return r=a.sent(),[3,5];case 3:return[4,Sp(this.input,e)];case 4:r=a.sent(),a.label=5;case 5:return n=r,[4,Promise.all(n.map((function(t){return i.landmarkNet.detectLandmarks(t)})))];case 6:return o=a.sent(),n.forEach((function(t){return t instanceof xt&&t.dispose()})),[2,t.map((function(t,e){return id(t,o[e])}))]}}))}))},e.prototype.withFaceExpressions=function(){return new Sv(this,this.input)},e.prototype.withAgeAndGender=function(){return new Nv(this,this.input)},e.prototype.withFaceDescriptors=function(){return new Ov(this,this.input)},e}(Bv),Wv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n,r,o;return _f(this,(function(i){switch(i.label){case 0:return[4,this.parentTask];case 1:return(t=i.sent())?(e=t.detection,this.input instanceof xt?[4,kp(this.input,[e])]:[3,3]):[2];case 2:return r=i.sent(),[3,5];case 3:return[4,Sp(this.input,[e])];case 4:r=i.sent(),i.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return o=i.sent(),n.forEach((function(t){return t instanceof xt&&t.dispose()})),[2,id(t,o)]}}))}))},e.prototype.withFaceExpressions=function(){return new kv(this,this.input)},e.prototype.withAgeAndGender=function(){return new Fv(this,this.input)},e.prototype.withFaceDescriptor=function(){return new Pv(this,this.input)},e}(Bv),zv=function(t){function e(e,n){void 0===n&&(n=new Ld);var r=t.call(this)||this;return r.input=e,r.options=n,r}return wf(e,t),e}(tv),Uv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e,n,r;return _f(this,(function(o){switch(o.label){case 0:return e=(t=this).input,(n=t.options)instanceof Ad?[4,xv.mtcnn.forward(e,n)]:[3,2];case 1:return[2,o.sent().map((function(t){return t.detection}))];case 2:if(r=n instanceof Zd?function(t){return xv.tinyFaceDetector.locateFaces(t,n)}:n instanceof Ld?function(t){return xv.ssdMobilenetv1.locateFaces(t,n)}:n instanceof $d?function(t){return xv.tinyYolov2.locateFaces(t,n)}:null,!r)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,r(e)]}}))}))},e.prototype.runAndExtendWithFaceDetections=function(){var t=this;return new Promise((function(e){return Ef(t,void 0,void 0,(function(){var t;return _f(this,(function(n){switch(n.label){case 0:return[4,this.run()];case 1:return t=n.sent(),[2,e(t.map((function(t){return tp({},t)})))]}}))}))}))},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Lv(this.runAndExtendWithFaceDetections(),this.input,t)},e.prototype.withFaceExpressions=function(){return new Iv(this.runAndExtendWithFaceDetections(),this.input)},e.prototype.withAgeAndGender=function(){return new Av(this.runAndExtendWithFaceDetections(),this.input)},e}(zv),Vv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wf(e,t),e.prototype.run=function(){return Ef(this,void 0,void 0,(function(){var t,e;return _f(this,(function(n){switch(n.label){case 0:return[4,new Uv(this.input,this.options)];case 1:return t=n.sent(),e=t[0],t.forEach((function(t){t.score>e.score&&(e=t)})),[2,e]}}))}))},e.prototype.runAndExtendWithFaceDetection=function(){var t=this;return new Promise((function(e){return Ef(t,void 0,void 0,(function(){var t;return _f(this,(function(n){switch(n.label){case 0:return[4,this.run()];case 1:return t=n.sent(),[2,e(t?tp({},t):void 0)]}}))}))}))},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Wv(this.runAndExtendWithFaceDetection(),this.input,t)},e.prototype.withFaceExpressions=function(){return new Rv(this.runAndExtendWithFaceDetection(),this.input)},e.prototype.withAgeAndGender=function(){return new Tv(this.runAndExtendWithFaceDetection(),this.input)},e}(zv);function Gv(t,e){return void 0===e&&(e=new Ld),new Vv(t,e)}var Hv=function(){function t(t,e){void 0===e&&(e=.6),this._distanceThreshold=e;var n=Array.isArray(t)?t:[t];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");var r=1,o=function(){return"person "+r++};this._labeledDescriptors=n.map((function(t){if(t instanceof Qf)return t;if(t instanceof Float32Array)return new Qf(o(),[t]);if(t.descriptor&&t.descriptor instanceof Float32Array)return new Qf(o(),[t.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")}))}return Object.defineProperty(t.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),t.prototype.computeMeanDistance=function(t,e){return e.map((function(e){return function(t,e){if(t.length!==e.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var n=Array.from(t),r=Array.from(e);return Math.sqrt(n.map((function(t,e){return t-r[e]})).reduce((function(t,e){return t+Math.pow(e,2)}),0))}(e,t)})).reduce((function(t,e){return t+e}),0)/(e.length||1)},t.prototype.matchDescriptor=function(t){var e=this;return this.labeledDescriptors.map((function(n){var r=n.descriptors,o=n.label;return new $f(o,e.computeMeanDistance(t,r))})).reduce((function(t,e){return t.distance<e.distance?t:e}))},t.prototype.findBestMatch=function(t){var e=this.matchDescriptor(t);return e.distance<this.distanceThreshold?e:new $f("unknown",e.distance)},t.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map((function(t){return t.toJSON()}))}},t.fromJSON=function(e){var n=e.labeledDescriptors.map((function(t){return Qf.fromJSON(t)}));return new t(n,e.distanceThreshold)},t}();function qv(t,e){var n=new Rf(e.width,e.height),r=n.width,o=n.height;if(r<=0||o<=0)throw new Error("resizeResults - invalid dimensions: "+JSON.stringify({width:r,height:o}));if(Array.isArray(t))return t.map((function(t){return qv(t,{width:r,height:o})}));if(od(t)){var i=t.detection.forSize(r,o),a=t.unshiftedLandmarks.forSize(i.box.width,i.box.height);return id(tp(t,i),a)}return Zf(t)?tp(t,t.detection.forSize(r,o)):t instanceof Kf||t instanceof Uf?t.forSize(r,o):t}},1012:function(t,e,n){n.d(e,{Z:function(){return h}});var r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),o=new Uint8Array(16);function i(){if(!r)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(o)}var a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var s=function(t){return"string"==typeof t&&a.test(t)},u=[],c=0;c<256;++c)u.push((c+256).toString(16).substr(1));var l=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(u[t[e+0]]+u[t[e+1]]+u[t[e+2]]+u[t[e+3]]+"-"+u[t[e+4]]+u[t[e+5]]+"-"+u[t[e+6]]+u[t[e+7]]+"-"+u[t[e+8]]+u[t[e+9]]+"-"+u[t[e+10]]+u[t[e+11]]+u[t[e+12]]+u[t[e+13]]+u[t[e+14]]+u[t[e+15]]).toLowerCase();if(!s(n))throw TypeError("Stringified UUID is invalid");return n};var h=function(t,e,n){var r=(t=t||{}).random||(t.rng||i)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,e){n=n||0;for(var o=0;o<16;++o)e[n+o]=r[o];return e}return l(r)}}}]); |