PageSourceSearch

https://dgac.gob.gt/assets/useFaceApi-DBBB_QOt.js

js dgac.gob.gt collected 2026-10-02 11:18:06 UTC 640,843 bytes, 3,828 lines download raw bytes

vendor: 88,847 bytes, lines 1-25
1import{r as rt}from"./ui-vendor-Cm2ZkKHv.js";/**
2 * @license
3 * Copyright 2020 Google LLC. All Rights Reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * =============================================================================
16 */var Es=function(r,t){return(Es=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var o in n)n.hasOwnProperty(o)&&(e[o]=n[o])})(r,t)};function gt(r,t){function e(){this.constructor=r}Es(r,t),r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function X(r,t,e,n){return new(e||(e=Promise))(function(o,a){function i(c){try{u(n.next(c))}catch(l){a(l)}}function s(c){try{u(n.throw(c))}catch(l){a(l)}}function u(c){c.done?o(c.value):new e(function(l){l(c.value)}).then(i,s)}u((n=n.apply(r,[])).next())})}function $(r,t){var e,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(u){return function(c){return function(l){if(e)throw new TypeError("Generator is already executing.");for(;i;)try{if(e=1,n&&(o=2&l[0]?n.return:l[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,l[1])).done)return o;switch(n=0,o&&(l=[2&l[0],o.value]),l[0]){case 0:case 1:o=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,n=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){i=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){i.label=l[1];break}if(l[0]===6&&i.label<o[1]){i.label=o[1],o=l;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(l);break}o[2]&&i.ops.pop(),i.trys.pop();continue}l=t.call(r,i)}catch(h){l=[6,h],n=0}finally{e=o=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([u,c])}}}var qc=function(){function r(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return r.prototype.setPlatform=function(t,e){this.platform!=null&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},r.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},this.urlFlags[t]!=null){var o=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+o+"."),this.set(t,o)}},r.prototype.get=function(t){return t in this.flags?this.flags[t]:(this.flags[t]=this.evaluateFlag(t),this.flags[t])},r.prototype.getNumber=function(t){return this.get(t)},r.prototype.getBool=function(t){return this.get(t)},r.prototype.getFlags=function(){return this.flags},Object.defineProperty(r.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),r.prototype.set=function(t,e){if(this.flagRegistry[t]==null)throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,this.flagRegistry[t].setHook!=null&&this.flagRegistry[t].setHook(e)},r.prototype.evaluateFlag=function(t){if(this.flagRegistry[t]==null)throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},r.prototype.setFlags=function(t){this.flags=Object.assign({},t)},r.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},r.prototype.populateURLFlags=function(){var t=this;if(this.global!==void 0&&this.global.location!==void 0&&this.global.location.search!==void 0){var e,n,o=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(a){for(var i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];return jc(n,i[0],i[1]),i.join("=")}),n);"tfjsflags"in o&&o.tfjsflags.split(",").forEach(function(a){var i=a.split(":"),s=i[0],u=i[1];t.urlFlags[s]=function(c,l){if((l=l.toLowerCase())==="true"||l==="false")return l==="true";if(""+ +l===l)return+l;throw new Error("Could not parse value flag value "+l+" for flag "+c+".")}(s,u)})}},r}();function jc(r,t,e){r[decodeURIComponent(t)]=decodeURIComponent(e||"")}function M(){return Is}var Is=null,Fr=new Map,Jo=new Map;function Rs(r,t){var e=Ss(r,t);return Fr.get(e)}function Kc(r){return Jo.get(r)}function _i(r){for(var t=Fr.entries(),e=[];;){var n=t.next(),o=n.done,a=n.value;if(o)break;var i=a[0],s=a[1];i.split("_")[0]===r&&e.push(s)}return e}function ks(r){var t=r.kernelName,e=r.backendName,n=Ss(t,e);if(Fr.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is already registered");Fr.set(n,r)}function Xc(r){var t=r.kernelName;Jo.has(t)&&console.warn("Overriding the gradient for '"+t+"'"),Jo.set(t,r)}function Ss(r,t){return t+"_"+r}function Qo(r,t,e){return Math.max(r,Math.min(t,e))}function Ds(r){return r%2==0?r:r+1}function $c(r){for(var t=0,e=0;e<r.length;e++)t+=r[e];return t}function E(r,t){if(!r)throw new Error(typeof t=="string"?t:t())}function ye(r,t,e){e===void 0&&(e=""),E(We(r,t),function(){return e+" Shapes "+r+" and "+t+" must match"})}function jn(r){E(r!=null,function(){return"The input to the tensor constructor must be a non-null value."})}function zn(r,t,e){if(t===void 0&&(t=[]),e===void 0&&(e=!1),t==null&&(t=[]),Array.isArray(r)||St(r)&&!e)for(var n=0;n<r.length;++n)zn(r[n],t,e);else t.push(r);return t}function Y(r){if(r.length===0)return 1;for(var t=r[0],e=1;e<r.length;e++)t*=r[e];return t}function We(r,t){if(r===t)return!0;if(r==null||t==null||r.length!==t.length)return!1;for(var e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}function Ae(r){return r%1==0}function Yc(r){if(Math.tanh!=null)return Math.tanh(r);if(r===1/0)return 1;if(r===-1/0)return-1;var t=Math.exp(2*r);return(t-1)/(t+1)}function Zo(r){var t=Math.ceil(Math.sqrt(r));return[t,Math.ceil(r/t)]}function Pn(r,t){return t<=r.length?r:r+" ".repeat(t-r.length)}function Ei(r,t,e){return t===void 0&&(t=function(n){return 0}),new Promise(function(n,o){var a=0,i=function(){if(r())n();else{a++;var s=t(a);e!=null&&a>=e?o():setTimeout(i,s)}};i()})}function Jc(r,t){for(var e=1,n=-1,o=0;o<r.length;++o)if(r[o]>=0)e*=r[o];else if(r[o]===-1){if(n!==-1)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+o);n=o}else if(r[o]<0)throw Error("Shapes can not be < 0. Found "+r[o]+" at dim "+o);if(n===-1){if(t>0&&t!==e)throw Error("Size("+t+") must match the product of shape "+r);return r}if(e===0)throw Error("Cannot infer the missing size in ["+r+"] when there are 0 elements");if(t%e!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+e);var a=r.slice();return a[n]=t/e,a}function Be(r,t){var e=t.length;return E((r=r==null?t.map(function(n,o){return o}):[].concat(r)).every(function(n){return n>=-e&&n<e}),function(){return"All values in axis param must be in range [-"+e+", "+e+") but got axis "+r}),E(r.every(function(n){return Ae(n)}),function(){return"All values in axis param must be integers but got axis "+r}),r.map(function(n){return n<0?e+n:n})}function hn(r,t){for(var e=[],n=[],o=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||o?null:Be(t,r).sort(),i=0,s=0;s<r.length;++s){if(a!=null){if(a[i]===s&&r[s]!==1)throw new Error("Can't squeeze axis "+s+" since its dim '"+r[s]+"' is not 1");(a[i]==null||a[i]>s)&&r[s]===1&&(e.push(r[s]),n.push(s)),a[i]<=s&&i++}r[s]!==1&&(e.push(r[s]),n.push(s))}return{newShape:e,keptDims:n}}function tr(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else{if(r!=="bool")throw new Error("Unknown data type "+r);e=new Uint8Array(t)}return e}function Pr(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else if(r==="bool")e=new Uint8Array(t);else{if(r!=="string")throw new Error("Unknown data type "+r);e=new Array(t)}return e}function Qc(r,t){for(var e=0;e<r.length;e++){var n=r[e];if(isNaN(n)||!isFinite(n))throw Error("A tensor of type "+t+" being uploaded contains "+n+".")}}function Zc(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function el(r,t){return t!=="complex64"&&(t!=="float32"||r==="complex64")&&(t!=="int32"||r==="float32"||r==="complex64")&&(t!=="bool"||r!=="bool")}function St(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function As(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error("Unknown dtype "+r)}function tl(r){if(r==null)return 0;var t=0;return r.forEach(function(e){return t+=e.length}),t}function ba(r){return typeof r=="string"||r instanceof String}function nl(r){return typeof r=="boolean"}function rl(r){return typeof r=="number"}function ur(r){return Array.isArray(r)?ur(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":rl(r)?"float32":ba(r)?"string":nl(r)?"bool":"float32"}function ea(r){return!!(r&&r.constructor&&r.call&&r.apply)}function ta(r,t){for(var e=t;e<r;++e)if(r%e==0)return e;return r}function Dt(r){var t=r.length;if(t<2)return[];var e=new Array(t-1);e[t-2]=r[t-1];for(var n=t-3;n>=0;--n)e[n]=e[n+1]*r[n+1];return e}function Ts(r,t,e){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=zn(r)),e&&Qc(r,t),function(a,i){return a instanceof Float32Array&&i==="float32"||a instanceof Int32Array&&i==="int32"||a instanceof Uint8Array&&i==="bool"}(r,t))return r;if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool"){for(var n=new Uint8Array(r.length),o=0;o<n.length;++o)Math.round(r[o])!==0&&(n[o]=1);return n}throw new Error("Unknown data type "+t)}function Ii(r,t){if(r.length===0)return t[0];var e=r.reduce(function(n,o){return n*o});if(e===0)return[];if(e!==t.length)throw new Error("["+r+"] does not match the input size.");return function n(o,a,i){var s=new Array;if(a.length===1)for(var u=a[0],c=0;c<u;c++)s[c]=i[o+c];else{u=a[0];var l=a.slice(1),h=l.reduce(function(f,p){return f*p});for(c=0;c<u;c++)s[c]=n(o+c*h,l,i)}return s}(0,r,t)}function Ns(r,t){for(var e=cr(r,t),n=0;n<e.length;n++)e[n]=1;return e}function cr(r,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool")return new Uint8Array(r);throw new Error("Unknown data type "+t)}function Et(){return M().platform.now()}function Fs(r){r.forEach(function(t){E(Number.isInteger(t)&&t>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+r+"]."})})}function ol(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",M().platform.encode(r,t)}function Mr(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",M().platform.decode(r,t)}function Ri(r,t,e){if(t===0)return 0;if(t===1)return r[0];for(var n=r[r.length-1],o=0;o<r.length-1;++o)n+=e[o]*r[o];return n}function al(r,t,e){if(t===0)return[];if(t===1)return[r];for(var n=new Array(t),o=0;o<n.length-1;++o)n[o]=Math.floor(r/e[o]),r-=n[o]*e[o];return n[n.length-1]=r,n}var il=function(){function r(t,e){this.backendTimer=t,this.logger=e,e==null&&(this.logger=new sl)}return r.prototype.profileKernel=function(t,e,n){var o,a=this,i=this.backendTimer.time(function(){o=n()});return o.forEach(function(s){s.data().then(function(u){(function(c,l,h){if(l!=="float32")return!1;for(var f=0;f<c.length;f++){var p=c[f];if(isNaN(p)||!isFinite(p))return console.warn("Found "+p+" in the result of '"+h+"'"),!0}})(u,s.dtype,t),i.then(function(c){var l="";c.getExtraProfileInfo!=null&&(l=c.getExtraProfileInfo()),a.logger.logKernelProfile(t,s,u,c.kernelMs,e,l)})})}),o},r}(),sl=function(){function r(){}return r.prototype.logKernelProfile=function(t,e,n,o,a,i){var s=typeof o=="number"?Pn(o+"ms",9):o.error,u=Pn(t,25),c=e.rank,l=e.size,h=Pn(e.shape.toString(),14),f="";for(var p in a){var d=a[p].shape||e.shape,g=d.length;f+=p+": "+g+"D "+(g>0?d:"")+" "}console.log("%c"+u+"	%c"+s+"	%c"+c+"D "+h+"	%c"+l+"	%c"+f+"	%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},r}(),ki=20,Xn=3,_o=7;function ul(r,t,e,n){var o=Dt(t),a=function(c,l,h,f){var p=Y(l),d=f[f.length-1],g=new Array(d).fill(0),v=l.length,m=h==="complex64"?Yn(c):c;if(v>1)for(var x=0;x<p/d;x++)for(var b=x*d,y=0;y<d;y++)g[y]=Math.max(g[y],$n(m[b+y],0,h).length);return g}(r,t,e,o),i=t.length,s=function c(l,h,f,p,d,g){g===void 0&&(g=!0);var v=f==="complex64"?2:1,m=h[0],x=h.length;if(x===0)return f==="complex64"?[$n(Yn(l)[0],0,f)]:f==="bool"?[Ps(l[0])]:[l[0].toString()];if(x===1){if(m>ki){var b=Xn*v,y=Array.from(l.slice(0,b)),w=Array.from(l.slice((m-Xn)*v,m*v));return f==="complex64"&&(y=Yn(y),w=Yn(w)),["["+y.map(function(B,V){return $n(B,d[V],f)}).join(", ")+", ..., "+w.map(function(B,V){return $n(B,d[m-Xn+V],f)}).join(", ")+"]"]}return["["+(f==="complex64"?Yn(l):Array.from(l)).map(function(B,V){return $n(B,d[V],f)}).join(", ")+"]"]}var C=h.slice(1),S=p.slice(1),k=p[0]*v,I=[];if(m>ki){for(var R=0;R<Xn;R++){var N=(A=R*k)+k;I.push.apply(I,c(l.slice(A,N),C,f,S,d,!1))}for(I.push("..."),R=m-Xn;R<m;R++)N=(A=R*k)+k,I.push.apply(I,c(l.slice(A,N),C,f,S,d,R===m-1))}else for(R=0;R<m;R++){var A;N=(A=R*k)+k,I.push.apply(I,c(l.slice(A,N),C,f,S,d,R===m-1))}var L=x===2?",":"";for(I[0]="["+I[0]+L,R=1;R<I.length-1;R++)I[R]=" "+I[R]+L;var O=`,
17`;for(R=2;R<x;R++)O+=`
18`;return I[I.length-1]=" "+I[I.length-1]+"]"+(g?"":O),I}(r,t,e,o,a),u=["Tensor"];return n&&(u.push("  dtype: "+e),u.push("  rank: "+i),u.push("  shape: ["+t+"]"),u.push("  values:")),u.push(s.map(function(c){return"    "+c}).join(`
19`)),u.join(`
20`)}function $n(r,t,e){return Pn(Array.isArray(r)?parseFloat(r[0].toFixed(_o))+" + "+parseFloat(r[1].toFixed(_o))+"j":ba(r)?"'"+r+"'":e==="bool"?Ps(r):parseFloat(r.toFixed(_o)).toString(),t)}function Ps(r){return r===0?"false":"true"}function Yn(r){for(var t=[],e=0;e<r.length;e+=2)t.push([r[e],r[e+1]]);return t}var nr=function(){function r(t,e,n){var o=this;if(this.dtype=e,this.shape=t.slice(),this.size=Y(t),n!=null){var a=n.length;E(a===this.size,function(){return"Length of values '"+a+"' does not match the size inferred by the shape '"+o.size+"'."})}if(e==="complex64")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||Pr(e,this.size),this.strides=Dt(t)}return r.prototype.set=function(t){for(var e=this,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];n.length===0&&(n=[0]),E(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var a=this.locToIndex(n);this.values[a]=t},r.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];t.length===0&&(t=[0]);for(var n=0,o=0,a=t;o<a.length;o++){var i=a[o];if(i<0||i>=this.shape[n]){var s="Requested out of range element at "+t+".   Buffer shape="+this.shape;throw new Error(s)}n++}for(var u=t[t.length-1],c=0;c<t.length-1;++c)u+=this.strides[c]*t[c];return this.values[u]},r.prototype.locToIndex=function(t){if(this.rank===0)return 0;if(this.rank===1)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},r.prototype.indexToLoc=function(t){if(this.rank===0)return[];if(this.rank===1)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(r.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),r.prototype.toTensor=function(){return It().makeTensor(this.values,this.shape,this.dtype)},r}(),It=null,P=null,Ms=null,Ee=function(){function r(t,e,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=Y(t),this.strides=Dt(t),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}return r.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},r.prototype.asScalar=function(){return this.throwIfDisposed(),E(this.size===1,function(){return"The array must have only 1 element."}),this.reshape([])},r.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},r.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},r.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},r.prototype.as4D=function(t,e,n,o){return this.throwIfDisposed(),this.reshape([t,e,n,o])},r.prototype.as5D=function(t,e,n,o,a){return this.throwIfDisposed(),this.reshape([t,e,n,o,a])},r.prototype.asType=function(t){return this.throwIfDisposed(),P.cast(this,t)},Object.defineProperty(r.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),r.prototype.buffer=function(){return X(this,void 0,void 0,function(){var t;return $(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,P.buffer(this.shape,this.dtype,t)]}})})},r.prototype.bufferSync=function(){return P.buffer(this.shape,this.dtype,this.dataSync())},r.prototype.array=function(){return X(this,void 0,void 0,function(){var t;return $(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,Ii(this.shape,t)]}})})},r.prototype.arraySync=function(){return Ii(this.shape,this.dataSync())},r.prototype.data=function(){return X(this,void 0,void 0,function(){var t,e;return $(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=It().read(this.dataId),this.dtype!=="string"?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map(function(o){return Mr(o)})]}catch{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]}})})},r.prototype.dataSync=function(){this.throwIfDisposed();var t=It().readSync(this.dataId);if(this.dtype==="string")try{return t.map(function(e){return Mr(e)})}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},r.prototype.bytes=function(){return X(this,void 0,void 0,function(){var t;return $(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,It().read(this.dataId)];case 1:return t=e.sent(),this.dtype==="string"?[2,t]:[2,new Uint8Array(t.buffer)]}})})},r.prototype.dispose=function(){this.isDisposed||(It().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),r.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},r.prototype.toFloat=function(){return this.asType("float32")},r.prototype.toInt=function(){return this.asType("int32")},r.prototype.toBool=function(){return this.asType("bool")},r.prototype.print=function(t){return t===void 0&&(t=!1),P.print(this,t)},r.prototype.reshape=function(t){return this.throwIfDisposed(),P.reshape(this,t)},r.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},r.prototype.expandDims=function(t){return t===void 0&&(t=0),P.expandDims(this,t)},r.prototype.cumsum=function(t,e,n){return t===void 0&&(t=0),e===void 0&&(e=!1),n===void 0&&(n=!1),P.cumsum(this,t,e,n)},r.prototype.squeeze=function(t){return this.throwIfDisposed(),P.squeeze(this,t)},r.prototype.clone=function(){return this.throwIfDisposed(),P.clone(this)},r.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),P.oneHot(this,t,e,n)},r.prototype.toString=function(t){return t===void 0&&(t=!1),ul(this.dataSync(),this.shape,this.dtype,t)},r.prototype.tile=function(t){return this.throwIfDisposed(),P.tile(this,t)},r.prototype.gather=function(t,e){return e===void 0&&(e=0),this.throwIfDisposed(),P.gather(this,t,e)},r.prototype.matMul=function(t,e,n){return e===void 0&&(e=!1),n===void 0&&(n=!1),this.throwIfDisposed(),P.matMul(this,t,e,n)},r.prototype.dot=function(t){return this.throwIfDisposed(),P.dot(this,t)},r.prototype.norm=function(t,e,n){return t===void 0&&(t="euclidean"),e===void 0&&(e=null),n===void 0&&(n=!1),this.throwIfDisposed(),P.norm(this,t,e,n)},r.prototype.slice=function(t,e){return this.throwIfDisposed(),P.slice(this,t,e)},r.prototype.reverse=function(t){return this.throwIfDisposed(),P.reverse(this,t)},r.prototype.concat=function(t,e){return e===void 0&&(e=0),this.throwIfDisposed(),t instanceof r&&(t=[t]),P.concat([this].concat(t),e)},r.prototype.split=function(t,e){return e===void 0&&(e=0),this.throwIfDisposed(),P.split(this,t,e)},r.prototype.stack=function(t,e){return e===void 0&&(e=0),P.stack([this,t],e)},r.prototype.unstack=function(t){return t===void 0&&(t=0),P.unstack(this,t)},r.prototype.pad=function(t,e){return e===void 0&&(e=0),P.pad(this,t,e)},r.prototype.batchNormalization=function(t,e,n,o,a){return n===void 0&&(n=.001),Ms("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,a,o,n)},r.prototype.batchNorm=function(t,e,n,o,a){return a===void 0&&(a=.001),this.throwIfDisposed(),P.batchNorm(this,t,e,n,o,a)},r.prototype.all=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.all(this,t,e)},r.prototype.any=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.any(this,t,e)},r.prototype.logSumExp=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.logSumExp(this,t,e)},r.prototype.sum=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.sum(this,t,e)},r.prototype.prod=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.prod(this,t,e)},r.prototype.mean=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.mean(this,t,e)},r.prototype.min=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.min(this,t,e)},r.prototype.max=function(t,e){return t===void 0&&(t=null),e===void 0&&(e=!1),this.throwIfDisposed(),P.max(this,t,e)},r.prototype.argMin=function(t){return t===void 0&&(t=null),this.throwIfDisposed(),P.argMin(this,t)},r.prototype.argMax=function(t){return t===void 0&&(t=null),this.throwIfDisposed(),P.argMax(this,t)},r.prototype.cast=function(t){return this.throwIfDisposed(),P.cast(this,t)},r.prototype.add=function(t){return this.throwIfDisposed(),P.add(this,t)},r.prototype.addStrict=function(t){return this.throwIfDisposed(),P.addStrict(this,t)},r.prototype.atan2=function(t){return this.throwIfDisposed(),P.atan2(this,t)},r.prototype.sub=function(t){return this.throwIfDisposed(),P.sub(this,t)},r.prototype.subStrict=function(t){return this.throwIfDisposed(),P.subStrict(this,t)},r.prototype.pow=function(t){return this.throwIfDisposed(),P.pow(this,t)},r.prototype.powStrict=function(t){return this.throwIfDisposed(),P.powStrict(this,t)},r.prototype.mul=function(t){return this.throwIfDisposed(),P.mul(this,t)},r.prototype.mulStrict=function(t){return this.throwIfDisposed(),P.mulStrict(this,t)},r.prototype.div=function(t){return this.throwIfDisposed(),P.div(this,t)},r.prototype.divNoNan=function(t){return this.throwIfDisposed(),P.divNoNan(this,t)},r.prototype.floorDiv=function(t){return this.throwIfDisposed(),P.floorDiv(this,t)},r.prototype.divStrict=function(t){return this.throwIfDisposed(),P.divStrict(this,t)},r.prototype.minimum=function(t){return this.throwIfDisposed(),P.minimum(this,t)},r.prototype.minimumStrict=function(t){return this.throwIfDisposed(),P.minimumStrict(this,t)},r.prototype.maximum=function(t){return this.throwIfDisposed(),P.maximum(this,t)},r.prototype.maximumStrict=function(t){return this.throwIfDisposed(),P.maximumStrict(this,t)},r.prototype.mod=function(t){return this.throwIfDisposed(),P.mod(this,t)},r.prototype.modStrict=function(t){return this.throwIfDisposed(),P.modStrict(this,t)},r.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),P.squaredDifferenceStrict(this,t)},r.prototype.transpose=function(t){return this.throwIfDisposed(),P.transpose(this,t)},r.prototype.notEqual=function(t){return this.throwIfDisposed(),P.notEqual(this,t)},r.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),P.notEqualStrict(this,t)},r.prototype.less=function(t){return this.throwIfDisposed(),P.less(this,t)},r.prototype.lessStrict=function(t){return this.throwIfDisposed(),P.lessStrict(this,t)},r.prototype.equal=function(t){return this.throwIfDisposed(),P.equal(this,t)},r.prototype.equalStrict=function(t){return this.throwIfDisposed(),P.equalStrict(this,t)},r.prototype.lessEqual=function(t){return this.throwIfDisposed(),P.lessEqual(this,t)},r.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),P.lessEqualStrict(this,t)},r.prototype.greater=function(t){return this.throwIfDisposed(),P.greater(this,t)},r.prototype.greaterStrict=function(t){return this.throwIfDisposed(),P.greaterStrict(this,t)},r.prototype.greaterEqual=function(t){return this.throwIfDisposed(),P.greaterEqual(this,t)},r.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),P.greaterEqualStrict(this,t)},r.prototype.logicalAnd=function(t){return this.throwIfDisposed(),P.logicalAnd(this,t)},r.prototype.logicalOr=function(t){return this.throwIfDisposed(),P.logicalOr(this,t)},r.prototype.logicalNot=function(){return this.throwIfDisposed(),P.logicalNot(this)},r.prototype.logicalXor=function(t){return this.throwIfDisposed(),P.logicalXor(this,t)},r.prototype.where=function(t,e){return this.throwIfDisposed(),P.where(t,this,e)},r.prototype.neg=function(){return this.throwIfDisposed(),P.neg(this)},r.prototype.ceil=function(){return this.throwIfDisposed(),P.ceil(this)},r.prototype.floor=function(){return this.throwIfDisposed(),P.floor(this)},r.prototype.sign=function(){return this.throwIfDisposed(),P.sign(this)},r.prototype.isNaN=function(){return this.throwIfDisposed(),P.isNaN(this)},r.prototype.isInf=function(){return this.throwIfDisposed(),P.isInf(this)},r.prototype.isFinite=function(){return this.throwIfDisposed(),P.isFinite(this)},r.prototype.exp=function(){return this.throwIfDisposed(),P.exp(this)},r.prototype.expm1=function(){return this.throwIfDisposed(),P.expm1(this)},r.prototype.log=function(){return this.throwIfDisposed(),P.log(this)},r.prototype.log1p=function(){return this.throwIfDisposed(),P.log1p(this)},r.prototype.sqrt=function(){return this.throwIfDisposed(),P.sqrt(this)},r.prototype.rsqrt=function(){return this.throwIfDisposed(),P.rsqrt(this)},r.prototype.square=function(){return this.throwIfDisposed(),P.square(this)},r.prototype.reciprocal=function(){return this.throwIfDisposed(),P.reciprocal(this)},r.prototype.abs=function(){return this.throwIfDisposed(),P.abs(this)},r.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),P.clipByValue(this,t,e)},r.prototype.relu=function(){return this.throwIfDisposed(),P.relu(this)},r.prototype.relu6=function(){return this.throwIfDisposed(),P.relu6(this)},r.prototype.elu=function(){return this.throwIfDisposed(),P.elu(this)},r.prototype.selu=function(){return this.throwIfDisposed(),P.selu(this)},r.prototype.leakyRelu=function(t){return t===void 0&&(t=.2),this.throwIfDisposed(),P.leakyRelu(this,t)},r.prototype.prelu=function(t){return this.throwIfDisposed(),P.prelu(this,t)},r.prototype.sigmoid=function(){return this.throwIfDisposed(),P.sigmoid(this)},r.prototype.logSigmoid=function(){return this.throwIfDisposed(),P.logSigmoid(this)},r.prototype.softplus=function(){return this.throwIfDisposed(),P.softplus(this)},r.prototype.zerosLike=function(){return this.throwIfDisposed(),P.zerosLike(this)},r.prototype.onesLike=function(){return this.throwIfDisposed(),P.onesLike(this)},r.prototype.sin=function(){return this.throwIfDisposed(),P.sin(this)},r.prototype.cos=function(){return this.throwIfDisposed(),P.cos(this)},r.prototype.tan=function(){return this.throwIfDisposed(),P.tan(this)},r.prototype.asin=function(){return this.throwIfDisposed(),P.asin(this)},r.prototype.acos=function(){return this.throwIfDisposed(),P.acos(this)},r.prototype.atan=function(){return this.throwIfDisposed(),P.atan(this)},r.prototype.sinh=function(){return this.throwIfDisposed(),P.sinh(this)},r.prototype.cosh=function(){return this.throwIfDisposed(),P.cosh(this)},r.prototype.tanh=function(){return this.throwIfDisposed(),P.tanh(this)},r.prototype.asinh=function(){return this.throwIfDisposed(),P.asinh(this)},r.prototype.acosh=function(){return this.throwIfDisposed(),P.acosh(this)},r.prototype.atanh=function(){return this.throwIfDisposed(),P.atanh(this)},r.prototype.erf=function(){return this.throwIfDisposed(),P.erf(this)},r.prototype.round=function(){return this.throwIfDisposed(),P.round(this)},r.prototype.step=function(t){return t===void 0&&(t=0),this.throwIfDisposed(),P.step(this,t)},r.prototype.softmax=function(t){return t===void 0&&(t=-1),this.throwIfDisposed(),P.softmax(this,t)},r.prototype.logSoftmax=function(t){return t===void 0&&(t=-1),this.throwIfDisposed(),P.logSoftmax(this,t)},r.prototype.resizeBilinear=function(t,e){return e===void 0&&(e=!1),this.throwIfDisposed(),P.image.resizeBilinear(this,t,e)},r.prototype.resizeNearestNeighbor=function(t,e){return e===void 0&&(e=!1),this.throwIfDisposed(),P.image.resizeNearestNeighbor(this,t,e)},r.prototype.conv1d=function(t,e,n,o,a,i){return o===void 0&&(o="NWC"),a===void 0&&(a=1),this.throwIfDisposed(),P.conv1d(this,t,e,n,o,a,i)},r.prototype.conv2d=function(t,e,n,o,a,i){return o===void 0&&(o="NHWC"),a===void 0&&(a=[1,1]),this.throwIfDisposed(),P.conv2d(this,t,e,n,o,a,i)},r.prototype.conv2dTranspose=function(t,e,n,o,a){return this.throwIfDisposed(),P.conv2dTranspose(this,t,e,n,o,a)},r.prototype.depthwiseConv2D=function(t,e,n,o,a,i){return o===void 0&&(o="NHWC"),a===void 0&&(a=[1,1]),this.throwIfDisposed(),P.depthwiseConv2d(this,t,e,n,o,a,i)},r.prototype.separableConv2d=function(t,e,n,o,a,i){return a===void 0&&(a=[1,1]),i===void 0&&(i="NHWC"),this.throwIfDisposed(),P.separableConv2d(this,t,e,n,o,a,i)},r.prototype.avgPool=function(t,e,n,o){return this.throwIfDisposed(),P.avgPool(this,t,e,n,o)},r.prototype.maxPool=function(t,e,n,o){return this.throwIfDisposed(),P.maxPool(this,t,e,n,o)},r.prototype.localResponseNormalization=function(t,e,n,o){return t===void 0&&(t=5),e===void 0&&(e=1),n===void 0&&(n=1),o===void 0&&(o=.5),P.localResponseNormalization(this,t,e,n,o)},r.prototype.pool=function(t,e,n,o,a){return this.throwIfDisposed(),P.pool(this,t,e,n,o,a)},r.prototype.variable=function(t,e,n){return t===void 0&&(t=!0),this.throwIfDisposed(),It().makeVariable(this,t,e,n)},r.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),P.unsortedSegmentSum(this,t,e)},r.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),P.batchToSpaceND(this,t,e)},r.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),P.spaceToBatchND(this,t,e)},r.prototype.topk=function(t,e){return t===void 0&&(t=1),e===void 0&&(e=!0),this.throwIfDisposed(),P.topk(this,t,e)},r.prototype.stridedSlice=function(t,e,n,o,a,i,s,u){return o===void 0&&(o=0),a===void 0&&(a=0),i===void 0&&(i=0),s===void 0&&(s=0),u===void 0&&(u=0),this.throwIfDisposed(),P.stridedSlice(this,t,e,n,o,a,i,s,u)},r.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),P.depthToSpace(this,t,e)},r.prototype.fft=function(){return this.throwIfDisposed(),P.spectral.fft(this)},r.prototype.ifft=function(){return this.throwIfDisposed(),P.spectral.ifft(this)},r.prototype.rfft=function(){return this.throwIfDisposed(),P.spectral.rfft(this)},r.prototype.irfft=function(){return this.throwIfDisposed(),P.spectral.irfft(this)},r}();Object.defineProperty(Ee,Symbol.hasInstance,{value:function(r){return!!r&&r.dataId!=null&&r.shape!=null&&r.dtype!=null}});var Si,na,ra,oa,aa,Gn=function(r){function t(e,n,o,a){var i=r.call(this,e.shape,e.dtype,e.dataId,a)||this;return i.trainable=n,i.name=o,i}return gt(t,r),t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!We(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");It().disposeTensor(this),this.dataId=e.dataId,It().incRef(this,null)},t.prototype.dispose=function(){It().disposeVariable(this),this.isDisposedInternal=!0},t}(Ee);Object.defineProperty(Gn,Symbol.hasInstance,{value:function(r){return r instanceof Ee&&r.assign!=null&&r.assign instanceof Function}}),function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"}(Si||(Si={})),function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"}(na||(na={})),function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"}(ra||(ra={})),function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"}(oa||(oa={})),function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"}(aa||(aa={}));var cl={float32:oa,int32:na,bool:ra,complex64:aa};function ze(r,t){if(r==="string"||t==="string"){if(r==="string"&&t==="string")return"string";throw new Error("Can not upcast "+r+" with "+t)}return cl[r][t]}function Eo(r){return ze(r,"int32")}function Re(r,t){if(r.dtype===t.dtype)return[r,t];var e=ze(r.dtype,t.dtype);return[r.cast(e),t.cast(e)]}function ll(r,t){E(r.dtype===t.dtype,function(){return"The dtypes of the first("+r.dtype+") and second("+t.dtype+") input must match"})}function Os(r){var t=[];return function e(n,o,a){if(n!=null){if(n instanceof Ee)return void o.push(n);if(i=n,!(!Array.isArray(i)&&typeof i!="object")){var i,s=n;for(var u in s){var c=s[u];a.has(c)||(a.add(c),e(c,o,a))}}}}(r,t,new Set),t}var Io,Di=function(){function r(){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 r.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},r}(),hl=function(){function r(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Di}return r.prototype.ready=function(){return X(this,void 0,void 0,function(){var t,e,n;return $(this,function(o){switch(o.label){case 0:if(this.pendingBackendInit!=null)return[2,this.pendingBackendInit.then(function(){})];if(this.backendInstance!=null)return[2];t=this.getSortedBackends(),e=0,o.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return o.sent()?[4,this.setBackend(n)]:[3,4];case 3:return o.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}})})},Object.defineProperty(r.prototype,"backend",{get:function(){if(this.pendingBackendInit!=null)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(this.backendInstance==null){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}),r.prototype.backendNames=function(){return Object.keys(this.registryFactory)},r.prototype.findBackend=function(t){return!(t in this.registry)&&(!(t in this.registryFactory)||this.initializeBackend(t).asyncInit)?null:this.registry[t]},r.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},r.prototype.registerBackend=function(t,e,n){return n===void 0&&(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)},r.prototype.setBackend=function(t){return X(this,void 0,void 0,function(){var e,n,o;return $(this,function(a){switch(a.label){case 0:if(this.registryFactory[t]==null)throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,this.registry[t]!=null?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return o=a.sent(),[3,3];case 2:o=n,a.label=3;case 3:if(!o)return[2,!1];a.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new il(this.backendInstance),[2,!0]}})})},r.prototype.setupRegisteredKernels=function(){var t=this;_i(this.backendName).forEach(function(e){e.setupFunc!=null&&e.setupFunc(t.backendInstance)})},r.prototype.disposeRegisteredKernels=function(t){var e=this;_i(t).forEach(function(n){n.disposeFunc!=null&&n.disposeFunc(e.registry[t])})},r.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(n==null)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var o=n.factory();if(Promise.resolve(o)===o){var a=++this.pendingBackendInitId,i=o.then(function(s){return!(a<e.pendingBackendInitId)&&(e.registry[t]=s,e.pendingBackendInit=null,!0)}).catch(function(s){return!(a<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(s.stack||s.message),!1)});return this.pendingBackendInit=i,{success:i,asyncInit:!0}}return this.registry[t]=o,{success:!0,asyncInit:!1}}catch(s){return console.warn("Initialization of backend "+t+" failed"),console.warn(s.stack||s.message),{success:!1,asyncInit:!1}}},r.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&this.pendingBackendInit!=null&&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)},r.prototype.getSortedBackends=function(){var t=this;if(Object.keys(this.registryFactory).length===0)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})},r.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],o=this.initializeBackend(n),a=o.success,i=o.asyncInit;if(i||a)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")},r.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),o=n.backend,a=this.readSync(e);o.disposeData(e),n.backend=t,t.move(e,a,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},r.prototype.tidy=function(t,e){var n,o=this,a=null;if(e==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");e=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof e!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");a=t}return this.scopedRun(function(){return o.startScope(a)},function(){return o.endScope(n)},function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n})},r.prototype.scopedRun=function(t,e,n){t();try{var o=n();return e(),o}catch(a){throw e(),a}},r.prototype.nextTensorId=function(){return r.nextTensorId++},r.prototype.nextVariableId=function(){return r.nextVariableId++},r.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(o){return{x:function(){return o.toFloat()}}},[]),e},r.prototype.runKernel=function(t,e,n,o,a){return this.runKernelFunc(null,e,null,t,n,o,a)},r.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},r.prototype.checkKernelForMemLeak=function(t,e,n){var o=this.backend.numDataIds(),a=0;n.forEach(function(u){a+=u.dtype==="complex64"?3:1});var i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],s=o-e-a-i;if(s>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+t+"'")},r.prototype.runKernelFunc=function(t,e,n,o,a,i,s){var u,c=this;i===void 0&&(i=[]),s===void 0&&(s=[]);var l=[],h=this.isTapeOn();o==null&&(o=this.state.activeScope!=null?this.state.activeScope.name:"");var f,p=function(x){h&&(l=x.map(function(b){return c.keep(c.clone(b))}))},d=this.state.numBytes,g=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var v,m=Rs(o,this.backendName);return f=m!=null?function(){var x=c.backend.numDataIds();v=m.kernelFunc({inputs:e,attrs:a,backend:c.backend});var b=Array.isArray(v)?v:[v];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,x,b);var y=b.map(function(C){var S=C.dataId,k=C.shape,I=C.dtype;return c.makeTensorFromDataId(S,k,I)}),w=y.filter(function(C,S){return s[S]});return p((i||[]).slice().concat(w)),y}:function(){var x=c.backend.numDataIds();v=c.tidy(function(){return t(c.backend,p)});var b=Array.isArray(v)?v:[v];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,x,b),b},this.scopedRun(function(){return c.state.kernelDepth++},function(){return c.state.kernelDepth--},function(){u=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(o,e,function(){return f()}):f()}),h&&this.addTapeNode(o,e,u,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:o,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-g,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(x){return e[x].shape}),outputShapes:u.map(function(x){return x.shape})}),Array.isArray(v)?u:u[0]},r.prototype.makeTensor=function(t,e,n,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;var a=t;n==="string"&&ba(t[0])&&(a=t.map(function(l){return ol(l)}));var i=o.write(a,e,n),s=new Ee(e,n,i,this.nextTensorId());if(this.incRef(s,o),n==="string"){var u=this.state.tensorInfo.get(i),c=tl(a);this.state.numBytes+=c-u.bytes,u.bytes=c}return s},r.prototype.makeTensorFromDataId=function(t,e,n,o){var a=new Ee(e,n=n||"float32",t,this.nextTensorId());return this.incRef(a,o),a},r.prototype.makeVariable=function(t,e,n,o){e===void 0&&(e=!0),n=n||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.asType(o));var a=new Gn(t,e,n,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},r.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++,t.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;var o=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(o=t.size*As(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:o,refCount:0}),this.state.numBytes+=o}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Gn||this.track(t)},r.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,t.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?(t.dtype!=="complex64"&&(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--}},r.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},r.prototype.disposeVariable=function(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]},r.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,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},r.prototype.profile=function(t){return X(this,void 0,void 0,function(){var e,n;return $(this,function(o){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(a){return a.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},r.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},r.prototype.addTapeNode=function(t,e,n,o,a){var i=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:a},u=Kc(t);u!=null&&(o=u.gradFunc),o!=null&&(s.gradient=function(c){return c=c.map(function(l,h){if(l==null){var f=n[h],p=cr(f.size,f.dtype);return i.makeTensor(p,f.shape,f.dtype)}return l}),o(c.length>1?c:c[0],a)}),this.state.activeTape.push(s)},r.prototype.keep=function(t){return t.kept=!0,t},r.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},r.prototype.endTape=function(){this.state.gradientDepth--},r.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},r.prototype.endScope=function(t){for(var e=this,n=Os(t),o=new Set(n.map(function(u){return u.id})),a=0;a<this.state.activeScope.track.length;a++){var i=this.state.activeScope.track[a];i.kept||o.has(i.id)||i.dispose()}var s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(u){u.kept||u.scopeId!==s.id||e.track(u)})},r.prototype.gradients=function(t,e,n,o){var a=this;if(o===void 0&&(o=!1),E(e.length>0,function(){return"gradients() received an empty list of xs."}),n!=null&&n.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var i=this.scopedRun(function(){return a.startTape()},function(){return a.endTape()},function(){return a.tidy("forward",t)});E(i instanceof Ee,function(){return"The result y returned by f() must be a tensor."});var s=function(u,c,l){for(var h={},f={},p=0;p<c.length;p++)h[c[p].id]=!0;for(p=0;p<u.length;p++){var d=(C=u[p]).inputs;for(var g in d){for(var v=d[g],m=!1,x=0;x<c.length;x++)if(h[v.id]){C.outputs.forEach(function(R){return h[R.id]=!0}),m=!0,f[C.id]=!0;break}if(m)break}}var b={};b[l.id]=!0;var y={};for(p=u.length-1;p>=0;p--)for(d=(C=u[p]).inputs,x=0;x<C.outputs.length;x++)if(b[C.outputs[x].id]){for(var g in d)b[d[g].id]=!0,y[C.id]=!0;break}var w=[];for(p=0;p<u.length;p++){var C;if(f[(C=u[p]).id]&&y[C.id]){var S={};for(var g in C.inputs){var k=C.inputs[g];h[k.id]&&(S[g]=k)}var I=Object.assign({},C);I.inputs=S,I.outputs=C.outputs,w.push(I)}}return w}(this.state.activeTape,e,i);if(!o&&s.length===0&&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 u,c,l={};l[i.id]=n??(u=i.shape,c=Ns(Y(u),"float32"),T.makeTensor(c,u,"float32")),function(f,p,d){for(var g=function(m){var x=p[m],b=[];if(x.outputs.forEach(function(S){var k=f[S.id];k!=null?b.push(k):b.push(null)}),x.gradient==null)throw new Error("Cannot compute gradient: gradient function not found for "+x.kernelName+".");var y=x.gradient(b),w=function(S){if(!(S in y))throw new Error("Cannot backprop through input "+S+". Available gradients found: "+Object.keys(y)+".");var k=d(function(){return y[S]()});if(k.dtype!=="float32")throw new Error("Error in gradient for op "+x.kernelName+". The gradient of input "+S+" must have 'float32' dtype, but has '"+k.dtype+"'");var I=x.inputs[S];if(!We(k.shape,I.shape))throw new Error("Error in gradient for op "+x.kernelName+". The gradient of input '"+S+"' has shape '"+k.shape+"', which does not match the shape of the input '"+I.shape+"'");if(f[I.id]==null)f[I.id]=k;else{var R=f[I.id];f[I.id]=R.add(k),R.dispose()}};for(var C in x.inputs)w(C)},v=p.length-1;v>=0;v--)g(v)}(l,s,function(f){return a.tidy(f)});var h=e.map(function(f){return l[f.id]});return a.state.gradientDepth===0&&(a.state.activeTape.forEach(function(f){for(var p=0,d=f.saved;p<d.length;p++)d[p].dispose()}),a.state.activeTape=null),{value:i,grads:h}})},r.prototype.customGrad=function(t){var e=this;return E(ea(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];E(o.every(function(s){return s instanceof Ee}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"});var i={};return o.forEach(function(s,u){i[u]=s}),e.runKernelFunc(function(s,u){return E((n=t.apply(void 0,o.concat([u]))).value instanceof Ee,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),E(ea(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(s,u){var c=n.gradFunc(s,u),l=Array.isArray(c)?c:[c];E(l.length===o.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(...)."}),E(l.every(function(f){return f instanceof Ee}),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 h={};return l.forEach(function(f,p){h[p]=function(){return f}}),h})}},r.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},r.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},r.prototype.time=function(t){return X(this,void 0,void 0,function(){var e,n;return $(this,function(o){switch(o.label){case 0:return e=Et(),[4,this.backend.time(t)];case 1:return(n=o.sent()).wallMs=Et()-e,[2,n]}})})},r.prototype.track=function(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(r.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),r.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Di,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},r.nextTensorId=0,r.nextVariableId=0,r}(),T=function(){var r=function(){if(Io==null){var e=void 0;if(typeof window<"u")e=window;else if(typeof global<"u")e=global;else if(typeof process<"u")e=process;else{if(typeof self>"u")throw new Error("Could not find a global object");e=self}Io=e}return Io}();if(r._tfengine==null){var t=new qc(r);r._tfengine=new hl(t)}return function(e){Is=e}(r._tfengine.ENV),It=function(){return r._tfengine},r._tfengine}();function Bs(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}var Wt=M();Wt.registerFlag("DEBUG",function(){return!1},function(r){r&&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.")}),Wt.registerFlag("IS_BROWSER",function(){return Bs()}),Wt.registerFlag("IS_NODE",function(){return typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0}),Wt.registerFlag("IS_CHROME",function(){return typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),Wt.registerFlag("PROD",function(){return!1}),Wt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return Wt.getBool("DEBUG")}),Wt.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),Wt.registerFlag("IS_TEST",function(){return!1});var rr,it,at,cn={},Ro={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function fl(r,t){cn[r]=t}function Nt(r){r in cn||(cn[r]=function(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var n=function(o){if(typeof OffscreenCanvas<"u"&&o===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e);return n.addEventListener("webglcontextlost",function(o){o.preventDefault(),delete cn[e]},!1),e===1?n.getContext("webgl",Ro)||n.getContext("experimental-webgl",Ro):n.getContext("webgl2",Ro)}(r));var t=cn[r];return t.isContextLost()?(delete cn[r],Nt(r)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),cn[r])}function no(r,t){return[t,r]}function Qn(r){var t=Y(r);return Zo(Math.ceil(t/4))}function lr(r,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(r/2))]}function wa(r,t){var e,n,o,a,i,s,u,c,l,h=r;return M().getNumber("WEBGL_VERSION")===2?(e=h.R32F,n=h.R16F,o=h.RGBA16F,a=h.RGBA32F,i=h.RED,s=4,u=1,c=h.HALF_FLOAT,l=h.FLOAT):(e=r.RGBA,n=r.RGBA,o=r.RGBA,a=h.RGBA,i=r.RGBA,s=4,u=4,c=t!=null?t.HALF_FLOAT_OES:null,l=r.FLOAT),{internalFormatFloat:e,internalFormatHalfFloat:n,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:r.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c,textureTypeFloat:l}}function J(r,t,e){var n=e();return t&&function(o){var a=o.getError();if(a!==o.NO_ERROR)throw new Error("WebGL Error: "+ml(o,a))}(r),n}(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(rr||(rr={})),function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"}(it||(it={})),function(r){r[r.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",r[r.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",r[r.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",r[r.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",r[r.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(at||(at={}));var pl=596e-10,dl=65504;function vl(r){return!!(M().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||pl<Math.abs(r)&&Math.abs(r)<dl)}function ml(r,t){switch(t){case r.NO_ERROR:return"NO_ERROR";case r.INVALID_ENUM:return"INVALID_ENUM";case r.INVALID_VALUE:return"INVALID_VALUE";case r.INVALID_OPERATION:return"INVALID_OPERATION";case r.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case r.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case r.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+t}}function yr(r,t,e){return zt(r,t,function(){return r.getExtension(e)},'Extension "'+e+'" not supported on this browser.')}function gl(r,t,e){var n=zt(r,t,function(){return r.createShader(r.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(J(r,t,function(){return r.shaderSource(n,e)}),J(r,t,function(){return r.compileShader(n)}),r.getShaderParameter(n,r.COMPILE_STATUS)===!1)throw console.log(r.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function yl(r,t,e){var n=zt(r,t,function(){return r.createShader(r.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(J(r,t,function(){return r.shaderSource(n,e)}),J(r,t,function(){return r.compileShader(n)}),r.getShaderParameter(n,r.COMPILE_STATUS)===!1)throw function(o,a){var i=xl.exec(a);if(i==null)return console.log("Couldn't parse line number in error: "+a),void console.log(o);for(var s=+i[1],u=o.split(`
21`),c=u.length.toString().length+2,l=u.map(function(v,m){return Pn((m+1).toString(),c)+v}),h=0,f=0;f<l.length;f++)h=Math.max(l[f].length,h);var p=l.slice(0,s-1),d=l.slice(s-1,s),g=l.slice(s);console.log(p.join(`
22`)),console.log(a.split(`
23`)[0]),console.log("%c "+Pn(d[0],h),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(g.join(`
24`))}(e,r.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var ko,So,xl=/ERROR: [0-9]+:([0-9]+):/g;function bl(r,t){return zt(r,t,function(){return r.createProgram()},"Unable to create WebGLProgram.")}function wl(r,t,e){if(J(r,t,function(){return r.linkProgram(e)}),r.getProgramParameter(e,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Do(r,t,e){if(J(r,t,function(){return r.validateProgram(e)}),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function Cl(r,t,e){var n=zt(r,t,function(){return r.createBuffer()},"Unable to create WebGLBuffer");return J(r,t,function(){return r.bindBuffer(r.ARRAY_BUFFER,n)}),J(r,t,function(){return r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)}),n}function _l(r,t,e){var n=zt(r,t,function(){return r.createBuffer()},"Unable to create WebGLBuffer");return J(r,t,function(){return r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,n)}),J(r,t,function(){return r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)}),n}function El(r,t){return zt(r,t,function(){return r.createTexture()},"Unable to create WebGLTexture.")}function Il(r,t){var e=M().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||t<=0){var n="["+r+"x"+t+"]";throw new Error("Requested texture size "+n+" is invalid.")}if(r>e||t>e)throw n="["+r+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]")+".")}function Rl(r,t){return zt(r,t,function(){return r.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Ai(r,t,e,n,o,a,i,s){var u=r.getAttribLocation(e,n);return u!==-1&&(J(r,t,function(){return r.bindBuffer(r.ARRAY_BUFFER,o)}),J(r,t,function(){return r.vertexAttribPointer(u,a,r.FLOAT,!1,i,s)}),J(r,t,function(){return r.enableVertexAttribArray(u)}),!0)}function kl(r,t,e,n){Nl(r,n),J(r,t,function(){return r.activeTexture(r.TEXTURE0+n)}),J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)})}function Sl(r,t,e,n){return zt(r,t,function(){return r.getUniformLocation(e,n)},'uniform "'+n+'" not present in program.')}function Dl(r,t,e){return r.getUniformLocation(t,e)}function Al(r,t,e,n,o,a){J(r,t,function(){return kl(r,t,n,a)}),J(r,t,function(){return r.uniform1i(o,a)})}function Ao(r,t,e,n){J(r,t,function(){return r.bindFramebuffer(r.FRAMEBUFFER,n)}),J(r,t,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0)})}function Ti(r,t,e){J(r,t,function(){return r.bindFramebuffer(r.FRAMEBUFFER,e)}),J(r,t,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0)})}function xr(r){var t=r.checkFramebufferStatus(r.FRAMEBUFFER);if(t!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Tl(r,t))}function Tl(r,t){switch(t){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function zt(r,t,e,n){var o=J(r,t,function(){return e()});if(o==null)throw new Error(n);return o}function Nl(r,t){var e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+r.TEXTURE0;if(n<r.TEXTURE0||n>e)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+e+"]")+".")}function Or(r,t){return t===void 0&&(t=2),Y(r.slice(0,r.length-t))}function Br(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function To(r){var t=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(t=[Or(r)].concat(Br(r))),t}function Fl(r,t){var e;t===void 0&&(t=!1);var n=M().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,(r=r.map(function(c,l){return l>=r.length-2?Ds(r[l]):r[l]})).length===1&&(r=[2,r[0]])),r.length!==2){var o=hn(r);r=o.newShape}var a=Y(r);if(r.length<=1&&a<=n)return[1,a];if(r.length===2&&r[0]<=n&&r[1]<=n)return r;if(r.length===3&&r[0]*r[1]<=n&&r[2]<=n)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=n&&r[1]*r[2]<=n)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=n&&r[3]<=n)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=n&&r[1]*r[2]*r[3]<=n)return[r[0],r[1]*r[2]*r[3]];if(t){var i=Or(r),s=2,u=2;return r.length&&(s=(e=Br(r))[0],u=e[1]),Zo(a=i*(s/2)*(u/2)).map(function(c){return 2*c})}return Zo(a)}function br(r){return r%2==0}function wr(r,t){if(We(r=r.slice(-2),t=t.slice(-2))||!r.length||!t.length||r[0]===0||r[1]===0||t[0]===0||t[1]===0)return!0;if(r.length!==t.length){var e=r.slice(-1)[0],n=t.slice(-1)[0];if(e===n||br(e)&&br(n)&&(r[0]===1||t[0]===1))return!0}return r[1]===t[1]&&br(r[0])&&br(t[0])}function Pl(r){if(ko==null){var t=Nt(r);ko=t.getParameter(t.MAX_TEXTURE_SIZE)}return ko}function Ml(r){if(So==null){var t=Nt(r);So=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,So)}function Ol(r){if(r===0)return 0;var t=Nt(r);return ft(t,"EXT_disjoint_timer_query_webgl2")&&r===2?2:ft(t,"EXT_disjoint_timer_query")?1:0}function ft(r,t){return r.getExtension(t)!=null}function Ni(r){try{if(Nt(r)!=null)return!0}catch{return!1}return!1}function Bl(r){if(r===0)return!1;var t=Nt(r);if(r===1){if(!ft(t,"OES_texture_float"))return!1}else if(!ft(t,"EXT_color_buffer_float"))return!1;return ia(t)}function Ll(r){if(r===0)return!1;var t=Nt(r);if(r!==1){if(ft(t,"EXT_color_buffer_float"))return ia(t);if(ft(t,"EXT_color_buffer_half_float")){var e=t.getExtension("EXT_color_buffer_half_float");return function(n,o){var a=wa(n,o),i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,a.internalFormatHalfFloat,1,1,0,a.textureFormatFloat,a.textureTypeHalfFloat,null);var s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0);var u=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.deleteFramebuffer(s),u}(t,e)}return!1}return!!ft(t,"OES_texture_float")&&!!ft(t,"WEBGL_color_buffer_float")&&ia(t)}function ia(r){var t=wa(r),e=r.createTexture();r.bindTexture(r.TEXTURE_2D,e),r.texImage2D(r.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var n=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,n),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0);var o=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(e),r.deleteFramebuffer(n),o}function Wl(r){return r===2&&Nt(r).fenceSync!=null}var ne=M();function Ls(r){M().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function K(r,t){return T.tidy(r,t)}function Ze(r){Os(r).forEach(function(t){return t.dispose()})}function Ul(r){return T.keep(r)}function Lr(){for(var r=[],t=0;t<arguments.length;t++)r[t]=arguments[t];M().getBool("IS_TEST")||console.warn.apply(console,r)}function on(r,t){var e=r;if(St(r))return t==="string"?[]:[r.length];if(!Array.isArray(r))return[];for(var n=[];Array.isArray(e)||St(e)&&t!=="string";)n.push(e.length),e=e[0];return Array.isArray(r)&&M().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function o(a,i,s){if(s=s||[],!Array.isArray(a)&&!St(a))return void E(i.length===0,function(){return"Element arr["+s.join("][")+"] is a primitive, but should be an array/TypedArray of "+i[0]+" elements"});E(i.length>0,function(){return"Element arr["+s.join("][")+"] should be a primitive, but is an array of "+a.length+" elements"}),E(a.length===i[0],function(){return"Element arr["+s.join("][")+"] should have "+i[0]+" elements, but has "+a.length+" elements"});for(var u=i.slice(1),c=0;c<a.length;++c)o(a[c],u,s.concat(c))}(r,n,[]),n}function Fi(r,t,e,n){if(r!=null&&(r!=="numeric"&&r!==t||r==="numeric"&&t==="string"))throw new Error("Argument '"+e+"' passed to '"+n+"' must be "+r+" tensor, but got "+t+" tensor")}function _(r,t,e,n){if(n===void 0&&(n="numeric"),r instanceof Ee)return Fi(n,r.dtype,t,e),r;var o=ur(r);if(o!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(o=n),Fi(n,o,t,e),r==null||!St(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){var a=r==null?"null":r.constructor.name;throw new Error("Argument '"+t+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=on(r,o);St(r)||Array.isArray(r)||(r=[r]);var s=o!=="string"?Ts(r,o,M().getBool("DEBUG")):zn(r,[],!0);return T.makeTensor(s,i,o)}function Wr(r,t,e,n){if(n===void 0&&(n="numeric"),!Array.isArray(r))throw new Error("Argument "+t+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return r.map(function(o,a){return _(o,t+"["+a+"]",e)},n)}function Ws(r,t){for(var e=0;e<r.length;++e)if(r[r.length-e-1]!==t-1-e)return!1;return!0}function Vl(r,t,e){for(var n=r.length+t.length,o=[],a=0,i=0,s=0;s<n;s++)e.indexOf(s)===-1?o.push(r[a++]):o.push(t[i++]);return o}function He(r,t){for(var e=[],n=r.length,o=0;o<n;o++)t.indexOf(o)===-1&&e.push(r[o]);return[e,t.map(function(a){return r[a]})]}function et(r,t){return Vl(r,t.map(function(e){return 1}),t)}function ot(r,t,e){E(Ws(t,e),function(){return r+" supports only inner-most axes for now. Got axes "+t+" and rank-"+e+" input."})}function Ft(r,t){if(Ws(r,t))return null;for(var e=[],n=0;n<t;++n)r.indexOf(n)===-1&&e.push(n);return r.forEach(function(o){return e.push(o)}),e}function Ca(r){return r.map(function(t,e){return[e,t]}).sort(function(t,e){return t[1]-e[1]}).map(function(t){return t[0]})}function Pt(r,t){for(var e=[],n=t-r;n<t;++n)e.push(n);return e}function zl(r,t){var e=r[0].length;r.forEach(function(o,a){E(o.length===e,function(){return"Error in concat"+e+"D: rank of tensors["+a+"] must be the same as the rank of the rest ("+e+")"})}),E(t>=0&&t<e,function(){return"Error in concat"+e+"D: axis must be between 0 and "+(e-1)+"."});var n=r[0];r.forEach(function(o,a){for(var i=0;i<e;i++)E(i===t||o[i]===n[i],function(){return"Error in concat"+e+"D: Shape of tensors["+a+"] ("+o+") does not match the shape of the rest ("+n+") along the non-concatenated axis "+a+"."})})}function Hn(r,t){for(var e=r[0].slice(),n=1;n<r.length;n++)e[t]+=r[n][t];return e}function D(r){var t=Object.keys(r);if(t.length!==1)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");var e=t[0],n=r[e];e.endsWith("_")&&(e=e.substring(0,e.length-1));var o=function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];T.startScope(e);try{var s=n.apply(void 0,a);return s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),T.endScope(s),s}catch(u){throw T.endScope(null),u}};return Object.defineProperty(o,"name",{value:e,configurable:!0}),o}ne.registerFlag("HAS_WEBGL",function(){return ne.getNumber("WEBGL_VERSION")>0}),ne.registerFlag("WEBGL_VERSION",function(){return Ni(2)?2:Ni(1)?1:0}),ne.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return ne.get("WEBGL_VERSION")===2}),ne.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),ne.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),ne.registerFlag("WEBGL_PACK",function(){return ne.getBool("HAS_WEBGL")}),ne.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_CLIP",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),ne.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_PACK_REDUCE",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_LAZILY_UNPACK",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_CONV_IM2COL",function(){return ne.getBool("WEBGL_PACK")}),ne.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Pl(ne.getNumber("WEBGL_VERSION"))}),ne.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ml(ne.getNumber("WEBGL_VERSION"))}),ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var r=ne.getNumber("WEBGL_VERSION");return r===0?0:Ol(r)}),ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return ne.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(r=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(r)||/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(r.substr(0,4))));var r}),ne.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Bl(ne.getNumber("WEBGL_VERSION"))}),ne.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!ne.getBool("WEBGL_FORCE_F16_TEXTURES")&&ne.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),ne.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ll(ne.getNumber("WEBGL_VERSION"))}),ne.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Wl(ne.getNumber("WEBGL_VERSION"))}),ne.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return ne.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),Ms=Ls;var Ve=D({complex_:function(r,t){var e=_(r,"real","complex"),n=_(t,"imag","complex");return ye(e.shape,n.shape,"real and imag shapes, "+e.shape+" and "+n.shape+", must match in call to tf.complex()."),T.runKernelFunc(function(o){return o.complex(e,n)},{$real:e,$imag:n})}}),ht=D({real_:function(r){var t=_(r,"input","real");return T.runKernelFunc(function(e){return e.real(t)},{$input:t})}}),Rt=D({imag_:function(r){var t=_(r,"input","imag");return T.runKernelFunc(function(e){return e.imag(t)},{$input:t})}});function Ge(r,t,e){return an(r,t,on(r,e),e)}function an(r,t,e,n){if(n==null&&(n=ur(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!St(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")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(t!=null){Fs(t);var o=Y(t),a=Y(e);E(o===a,function(){return"Based on the provided shape, ["+t+"], the tensor should have "+o+" values but has "+a});for(var i=0;i<e.length;++i){var s=e[i],u=i!==e.length-1||s!==Y(t.slice(i));E(e[i]===t[i]||!u,function(){return"Error creating a new Tensor. Inferred shape ("+e+") does not match the provided shape ("+t+"). "})}}return St(r)||Array.isArray(r)||(r=[r]),t=t||e,r=n!=="string"?Ts(r,n,M().getBool("DEBUG")):zn(r,[],!0),T.makeTensor(r,t,n)}function q(r,t){if((St(r)&&t!=="string"||Array.isArray(r))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&St(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return an(r,[],[],t)}function Te(r,t){jn(r);var e=on(r,t);if(e.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return an(r,null,e,t)}function Zt(r,t,e){if(jn(r),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");var n=on(r,e);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return an(r,t,n,e)}function _a(r,t,e){if(jn(r),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");var n=on(r,e);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return an(r,t,n,e)}function Je(r,t,e){if(jn(r),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");var n=on(r,e);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return an(r,t,n,e)}function Gl(r,t,e){if(jn(r),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");var n=on(r,e);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return an(r,t,n,e)}function Hl(r,t,e){if(jn(r),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");var n=on(r,e);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return an(r,t=t||n,n,e)}function ql(r,t,e,n){return t===void 0&&(t=!0),T.makeVariable(r,t,e,n)}function Kn(r,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=Kn(r,"float32"),n=we(r,"float32");return Ve(e,n)}var o=Ns(Y(r),t);return T.makeTensor(o,r,t)}function we(r,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=we(r,"float32"),n=we(r,"float32");return Ve(e,n)}var o=cr(Y(r),t);return T.makeTensor(o,r,t)}function At(r,t,e){return T.runKernelFunc(function(n){return n.fill(r,t,e)},{})}function jl(r,t,e){if(e<=0)throw new Error("The number of values should be positive.");return T.runKernelFunc(function(n){return n.linspace(r,t,e)},{})}function Ur(r,t,e,n){if(e===void 0&&(e=1),n===void 0&&(n="float32"),e===0)throw new Error("Cannot have a step of zero");if(r===t||r<t&&e<0||t<r&&e>1)return we([0],n);var o=cr(Math.abs(Math.ceil((t-r)/e)),n);t<r&&e===1&&(e=-1),o[0]=r;for(var a=1;a<o.length;a++)o[a]=o[a-1]+e;return Te(o,n)}var Us=D({onesLike_:function(r){var t=_(r,"x","onesLike");if(t.dtype==="complex64"){var e=Us(ht(t)),n=ve(Rt(t));return Ve(e,n)}return T.runKernelFunc(function(o){return o.onesLike(t)},{$x:t},function(o,a){return{$x:function(){return ve(o)}}})}}),ve=D({zerosLike_:function(r){var t=_(r,"x","zerosLike");return T.runKernelFunc(function(e){return e.zerosLike(t)},{$x:t},function(e,n){return{$x:function(){return ve(e)}}})}}),Fe=D({concat_:function(r,t){t===void 0&&(t=0),E(r.length>=1,function(){return"Pass at least one tensor to concat"});var e=Wr(r,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
25          with dtype `+s.dtype+". ")}),t=Be(t,e[0].shape)[0];var n=Hn(e.map(function(s){return s.shape}),t);if(Y(n)===0)return Ge([],n);if((e=e.filter(function(s){return s.size>0})).length===1)return e[0];var o=e.map(function(s){return s.shape});zl(o,t);var a=e,i={axis:t};return T.runKernelFunc(function(s){return s.concat(e,t)},a,function(s){var u=o.map(function(c){return c[t]});return Ea(s,u,t).map(function(c){return function(){return c}})},"Concat",i)}}),Kl=D({concat1d_:function(r){return Fe(r,0)}}),Xl=D({concat2d_:function(r,t){return Fe(r,t)}}),$l=D({concat3d_:function(r,t){return Fe(r,t)}}),Yl=D({concat4d_:function(r,t){return Fe(r,t)}}),Ea=D({split_:function(r,t,e){e===void 0&&(e=0);var n,o=_(r,"x","split");return e=Be(e,o.shape)[0],typeof t=="number"?(E(o.shape[e]%t==0,function(){return"Number of splits must evenly divide the axis."}),n=new Array(t).fill(o.shape[e]/t)):(E(o.shape[e]===t.reduce(function(a,i){return a+i}),function(){return"The sum of sizes must match the size of the axis dimension."}),n=t),T.runKernelFunc(function(a){return a.split(o,n,e)},{$x:o},function(a){return{$x:function(){return Fe(a,e)}}})}});function yn(r,t){return r(t={exports:{}},t.exports),t.exports}var Jl=yn(function(r){(function(t,e,n){function o(s){var u,c=this,l=(u=4022871197,function(h){h=h.toString();for(var f=0;f<h.length;f++){var p=.02519603282416938*(u+=h.charCodeAt(f));p-=u=p>>>0,u=(p*=u)>>>0,u+=4294967296*(p-=u)}return 23283064365386963e-26*(u>>>0)});c.next=function(){var h=2091639*c.s0+23283064365386963e-26*c.c;return c.s0=c.s1,c.s1=c.s2,c.s2=h-(c.c=0|h)},c.c=1,c.s0=l(" "),c.s1=l(" "),c.s2=l(" "),c.s0-=l(s),c.s0<0&&(c.s0+=1),c.s1-=l(s),c.s1<0&&(c.s1+=1),c.s2-=l(s),c.s2<0&&(c.s2+=1),l=null}function a(s,u){return u.c=s.c,u.s0=s.s0,u.s1=s.s1,u.s2=s.s2,u}function i(s,u){var c=new o(s),l=u&&u.state,h=c.next;return h.int32=function(){return 4294967296*c.next()|0},h.double=function(){return h()+11102230246251565e-32*(2097152*h()|0)},h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.alea=i})(0,r)}),Ql=yn(function(r){(function(t,e,n){function o(s){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var h=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^h^h>>>8},s===(0|s)?u.x=s:c+=s;for(var l=0;l<c.length+64;l++)u.x^=0|c.charCodeAt(l),u.next()}function a(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u}function i(s,u){var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xor128=i})(0,r)}),Zl=yn(function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var h=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^h^h<<1)|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,s===(0|s)?u.x=s:c+=s;for(var l=0;l<c.length+64;l++)u.x^=0|c.charCodeAt(l),l==c.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function a(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u.v=s.v,u.d=s.d,u}function i(s,u){var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xorwow=i})(0,r)}),eh=yn(function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,h=u.x,f=u.i;return c=h[f],l=(c^=c>>>7)^c<<24,l^=(c=h[f+1&7])^c>>>10,l^=(c=h[f+3&7])^c>>>3,l^=(c=h[f+4&7])^c<<7,c=h[f+7&7],l^=(c^=c<<13)^c<<9,h[f]=l,u.i=f+1&7,l},function(c,l){var h,f=[];if(l===(0|l))f[0]=l;else for(l=""+l,h=0;h<l.length;++h)f[7&h]=f[7&h]<<15^l.charCodeAt(h)+f[h+1&7]<<13;for(;f.length<8;)f.push(0);for(h=0;h<8&&f[h]===0;++h);for(h==8?f[7]=-1:f[h],c.x=f,c.i=0,h=256;h>0;--h)c.next()}(u,s)}function a(s,u){return u.x=s.x.slice(),u.i=s.i,u}function i(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(l.x&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xorshift7=i})(0,r)}),th=yn(function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,h=u.w,f=u.X,p=u.i;return u.w=h=h+1640531527|0,l=f[p+34&127],c=f[p=p+1&127],l^=l<<13,c^=c<<17,l^=l>>>15,c^=c>>>12,l=f[p]=l^c,u.i=p,l+(h^h>>>16)|0},function(c,l){var h,f,p,d,g,v=[],m=128;for(l===(0|l)?(f=l,l=null):(l+="\0",f=0,m=Math.max(m,l.length)),p=0,d=-32;d<m;++d)l&&(f^=l.charCodeAt((d+32)%l.length)),d===0&&(g=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,d>=0&&(g=g+1640531527|0,p=(h=v[127&d]^=f+g)==0?p+1:0);for(p>=128&&(v[127&(l&&l.length||0)]=-1),p=127,d=512;d>0;--d)f=v[p+34&127],h=v[p=p+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,v[p]=f^h;c.w=g,c.X=v,c.i=p}(u,s)}function a(s,u){return u.i=s.i,u.w=s.w,u.X=s.X.slice(),u}function i(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(l.X&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xor4096=i})(0,r)}),nh=yn(function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var h=u.b,f=u.c,p=u.d,d=u.a;return h=h<<25^h>>>7^f,f=f-p|0,p=p<<24^p>>>8^d,d=d-h|0,u.b=h=h<<20^h>>>12^f,u.c=f=f-p|0,u.d=p<<16^f>>>16^d,u.a=d-h|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,s===Math.floor(s)?(u.a=s/4294967296|0,u.b=0|s):c+=s;for(var l=0;l<c.length+20;l++)u.b^=0|c.charCodeAt(l),u.next()}function a(s,u){return u.a=s.a,u.b=s.b,u.c=s.c,u.d=s.d,u}function i(s,u){var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.tychei=i})(0,r)}),ln=yn(function(r){(function(t,e){var n,o=this,a=256,i=6,s="random",u=e.pow(a,i),c=e.pow(2,52),l=2*c,h=a-1;function f(m,x,b){var y=[],w=g(function k(I,R){var N,A=[],L=typeof I;if(R&&L=="object")for(N in I)try{A.push(k(I[N],R-1))}catch{}return A.length?A:L=="string"?I:I+"\0"}((x=x==1?{entropy:!0}:x||{}).entropy?[m,v(t)]:m??function(){try{var k;return n&&(k=n.randomBytes)?k=k(a):(k=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(k)),v(k)}catch{var I=o.navigator,R=I&&I.plugins;return[+new Date,o,R,o.screen,v(t)]}}(),3),y),C=new p(y),S=function(){for(var k=C.g(i),I=u,R=0;k<c;)k=(k+R)*a,I*=a,R=C.g(1);for(;k>=l;)k/=2,I/=2,R>>>=1;return(k+R)/I};return S.int32=function(){return 0|C.g(4)},S.quick=function(){return C.g(4)/4294967296},S.double=S,g(v(C.S),t),(x.pass||b||function(k,I,R,N){return N&&(N.S&&d(N,C),k.state=function(){return d(C,{})}),R?(e[s]=k,I):k})(S,w,"global"in x?x.global:this==e,x.state)}function p(m){var x,b=m.length,y=this,w=0,C=y.i=y.j=0,S=y.S=[];for(b||(m=[b++]);w<a;)S[w]=w++;for(w=0;w<a;w++)S[w]=S[C=h&C+m[w%b]+(x=S[w])],S[C]=x;(y.g=function(k){for(var I,R=0,N=y.i,A=y.j,L=y.S;k--;)I=L[N=h&N+1],R=R*a+L[h&(L[N]=L[A=h&A+I])+(L[A]=I)];return y.i=N,y.j=A,R})(a)}function d(m,x){return x.i=m.i,x.j=m.j,x.S=m.S.slice(),x}function g(m,x){for(var b,y=m+"",w=0;w<y.length;)x[h&w]=h&(b^=19*x[h&w])+y.charCodeAt(w++);return v(x)}function v(m){return String.fromCharCode.apply(0,m)}if(e["seed"+s]=f,g(e.random(),t),r.exports){r.exports=f;try{n=require("crypto")}catch{}}})([],Math)});ln.alea=Jl,ln.xor128=Ql,ln.xorwow=Zl,ln.xorshift7=eh,ln.xor4096=th,ln.tychei=nh;var ro=ln.alea,Ia=function(){function r(t,e,n,o,a){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var i=a||Math.random();this.random=ro(i.toString())}return r.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,o=!1;!o;){var a=void 0,i=void 0,s=void 0;do s=(a=2*this.random()-1)*a+(i=2*this.random()-1)*i;while(s>=1||s===0);var u=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*u,n=this.mean+this.stdDev*i*u,this.truncated&&!this.isValidTruncated(e)||(o=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},r.prototype.convertValue=function(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)},r.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},r}(),rh=function(){function r(t,e,n,o){this.alpha=t,this.beta=1/e,this.dtype=n;var a=o||Math.random();this.randu=ro(a.toString()),this.randn=new Ia(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 r.prototype.nextValue=function(){for(var t,e,n,o,a,i;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=1-.331*(t=o*o)*t,n=.5*t+this.d*(1-i+Math.log(i)),(a=this.randu())<e||Math.log(a)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)},r.prototype.convertValue=function(t){return this.dtype==="float32"?t:Math.round(t)},r}(),oh=function(){function r(t,e,n,o){var a=this;if(t===void 0&&(t=0),e===void 0&&(e=1),this.canReturnFloat=function(){return a.dtype==null||a.dtype==="float32"},this.min=t,this.range=e-t,this.dtype=n,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=ro(o)}return r.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},r.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},r}();function oe(r,t,e){return t===void 0&&(t="float32"),t=t||"float32",Fs(r),new nr(r,t,e)}function ah(r,t){t===void 0&&(t=!1),console.log(r.toString(t))}var Vs=D({batchToSpaceND_:function(r,t,e){var n=_(r,"x","batchToSpaceND"),o=t.reduce(function(a,i){return a*i});return E(n.rank>=1+t.length,function(){return"input rank is "+n.rank+" but should be > than blockShape.length "+t.length}),E(e.length===t.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length  "+t.length}),E(n.shape[0]%o==0,function(){return"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockS
25hape "+t.join(" * ")+" === "+o}),T.runKernelFunc(function(a){return a.batchToSpaceND(n,t,e)},{$x:n},function(a){return{$x:function(){return a.spaceToBatchND(t,e)}}})}}),ih=D({broadcastTo_:function(r,t){var e=_(r,"broadcastTo","x"),n=e.shape;if(t.some(function(u){return!(u>0)||u%1!=0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.length<e.rank)throw new Error("broadcastTo(): shape.length="+t.length+" < input.rank="+e.rank+".");if(t.length>e.rank){for(var o=e.shape.slice();o.length<t.length;)o.unshift(1);e=e.reshape(o)}for(var a=Array.from(t),i=t.length-1;i>=0;i--)if(e.shape[i]===t[i])a[i]=1;else if(e.shape[i]!==1)throw new Error("broadcastTo(): ["+n+"] cannot be broadcast to ["+t+"].");var s=a.map(function(u,c){return u>1?c:-1}).filter(function(u){return u>=0});return s.length===0?e.clone():T.runKernelFunc(function(u){return u.tile(e,a)},{input:e},function(u){return{input:function(){return u.sum(s,!0)}}})}}),sh=D({cast_:function(r,t){var e=_(r,"x","cast");if(!Zc(t))throw new Error("Failed to cast to unknown dtype "+t);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");var n={dtype:t};return T.runKernelFunc(function(o){return o.cast(e,t)},{x:e},function(o){return{x:function(){return o.clone()}}},"Cast",n)}}),uh=D({clone_:function(r){var t=_(r,"x","clone",null);return T.runKernelFunc(function(){return T.makeTensorFromDataId(t.dataId,t.shape,t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),ch=D({cumsum_:function(r,t,e,n){t===void 0&&(t=0),e===void 0&&(e=!1),n===void 0&&(n=!1);var o=_(r,"x","cumsum"),a=Ft([t|=0],o.rank),i=o;a!=null&&(i=o.transpose(a));var s=Pt(1,o.rank)[0],u=T.runKernelFunc(function(c){return c.cumsum(i,s,e,n)},{permutedX:i},function(c){return{permutedX:function(){return c.cumsum(t,e,!n)}}});return a!=null&&(u=u.transpose(a)),u}}),lh=D({depthToSpace_:function(r,t,e){e===void 0&&(e="NHWC");var n=_(r,"x","depthToSpace"),o=e==="NHWC"?n.shape[1]:n.shape[2],a=e==="NHWC"?n.shape[2]:n.shape[3],i=e==="NHWC"?n.shape[3]:n.shape[1];return E(o*t>=0,function(){return`Negative dimension size caused by overflow when multiplying
26      `+o+" and "+t+`  for depthToSpace with input shape
27      `+n.shape}),E(a*t>=0,function(){return`Negative dimension size caused by overflow when multiplying
28      `+a+" and "+t+` for depthToSpace with input shape
29          `+n.shape}),E(i%(t*t)==0,function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+i+" for depthToSpace with input shape "+n.shape}),T.runKernelFunc(function(s){return s.depthToSpace(n,t,e)},{$x:n})}}),lt=D({expandDims_:function(r,t){t===void 0&&(t=0);var e=_(r,"x","expandDims",null);E(t<=e.rank,function(){return"Axis must be <= rank of the tensor"});var n=e.shape.slice();return t<0&&(E(-(e.rank+1)<=t,function(){return"Axis must be in the interval ["+-(e.rank+1)+", "+e.rank+"]"}),t=e.rank+t+1),n.splice(t,0,1),vt(e,n)}}),zs=D({eye_:function(r,t,e,n){n===void 0&&(n="float32"),t==null&&(t=r);for(var o=oe([r,t],n),a=r<=t?r:t,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(r,t);if(e==null)return s;if(e.length===1)return Mn(lt(s,0),[e[0],1,1]);if(e.length===2)return Mn(lt(lt(s,0),0),[e[0],e[1],1,1]);if(e.length===3)return Mn(lt(lt(lt(s,0),0),0),[e[0],e[1],e[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+e.length+"D.")}}),hh=D({multinomial_:function(r,t,e,n){n===void 0&&(n=!1);var o=_(r,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);e=e||Math.random();var s=i===1?o.as2D(1,-1):o,u=T.runKernelFunc(function(c){return c.multinomial(s,n,t,e)},{logits2D:s});return i===1?u.as1D():u}}),sa=D({oneHot_:function(r,t,e,n){if(e===void 0&&(e=1),n===void 0&&(n=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var o=_(r,"indices","oneHot","int32"),a=o.shape.concat([t]);return o=o.flatten(),T.runKernelFunc(function(i){return i.oneHot(o,t,e,n)},{$indices:o},function(i){return{$indices:function(){return we(o.shape,"float32")}}}).reshape(a)}}),xn=D({pad_:function(r,t,e){e===void 0&&(e=0);var n=_(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:t,constantValue:e};return T.runKernelFunc(function(a){return a.pad(n,t,e)},{x:n},function(a){var i=t.map(function(s){return s[0]});return{x:function(){return a.slice(i,n.shape)}}},"PadV2",o)}}),fh=D({pad1d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),xn(r,[t],e)}}),ph=D({pad2d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===2&&t[0].length===2&&t[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),xn(r,t,e)}}),dh=D({pad3d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),xn(r,t,e)}}),vh=D({pad4d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),xn(r,t,e)}}),mh=D({rand_:function(r,t,e){var n=Y(r),o=null;if(e==null||e==="float32")o=new Float32Array(n);else if(e==="int32")o=new Int32Array(n);else{if(e!=="bool")throw new Error("Unknown data type "+e);o=new Uint8Array(n)}for(var a=0;a<n;a++)o[a]=t();return T.makeTensor(o,r,e)}}),gh=D({randomNormal_:function(r,t,e,n,o){if(t===void 0&&(t=0),e===void 0&&(e=1),n!=null&&n==="bool")throw new Error("Unsupported data type "+n);for(var a=new Ia(t,e,n,!1,o),i=oe(r,n),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),yh=D({randomGamma_:function(r,t,e,n,o){if(e===void 0&&(e=1),n===void 0&&(n="float32"),e==null&&(e=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error("Unsupported data type "+n);for(var a=new rh(t,e,n,o),i=oe(r,n),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Gs=D({randomUniform_:function(r,t,e,n,o){t===void 0&&(t=0),e===void 0&&(e=1),n===void 0&&(n="float32");for(var a=oe(r,n),i=new oh(t,e,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),vt=D({reshape_:function(r,t){var e=_(r,"x","reshape",null);t=Jc(t,e.size),E(e.size===Y(t),function(){return"new shape and old shape must have the same number of elements."});var n={shape:t};return T.runKernelFunc(function(o){return o.reshape(e,t)},{x:e},function(o){return{x:function(){return o.reshape(e.shape)}}},"Reshape",n)}}),Hs=D({spaceToBatchND_:function(r,t,e){var n=_(r,"x","spaceToBatchND");return E(n.rank>=1+t.length,function(){return"input rank "+n.rank+" should be > than [blockShape] "+t.length}),E(e.length===t.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+t.length}),E(n.shape.reduce(function(o,a,i){return i>0&&i<=t.length?o&&(a+e[i-1][0]+e[i-1][1])%t[i-1]==0:o},!0),function(){return"input spatial dimensions "+n.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+t.toString()}),T.runKernelFunc(function(o){return o.spaceToBatchND(n,t,e)},{$x:n},function(o){return{$x:function(){return o.batchToSpaceND(t,e)}}})}}),qs=D({squeeze_:function(r,t){var e=_(r,"x","squeeze");return vt(e,hn(e.shape,t).newShape)}}),ct=D({stack_:function(r,t){t===void 0&&(t=0);var e=Wr(r,"tensors","stack");if(E(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return e[0].expandDims(t);var n=e[0].rank,o=e[0].shape,a=e[0].dtype;E(t<=n,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(s){ye(o,s.shape,"All tensors passed to stack must have matching shapes")}),e.forEach(function(s){E(a===s.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=e.map(function(s){return s.expandDims(t)});return Fe(i,t)}}),Mn=D({tile_:function(r,t){var e=_(r,"x","tile",null);E(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+t+"."});var n=[e],o={reps:t};return T.runKernelFunc(function(a,i){var s=a.tile(e,t);return i([e]),s},{x:e},function(a,i){var s=i[0];return{x:function(){var u=ve(s);if(s.rank===1)for(var c=0;c<t[0];++c)u=u.add(a.slice([c*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(c=0;c<t[0];++c)for(var l=0;l<t[1];++l)u=u.add(a.slice([c*s.shape[0],l*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(c=0;c<t[0];++c)for(l=0;l<t[1];++l)for(var h=0;h<t[2];++h)u=u.add(a.slice([c*s.shape[0],l*s.shape[1],h*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else{if(s.rank!==4)throw new Error("Gradient for tile operation is not implemented for rank-"+s.rank+" tensors yet.");for(c=0;c<t[0];++c)for(l=0;l<t[1];++l)for(h=0;h<t[2];++h)for(var f=0;f<t[3];++f)u=u.add(a.slice([c*s.shape[0],l*s.shape[1],h*s.shape[2],f*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]))}return u}}},"Tile",o,n)}}),xh=D({truncatedNormal_:function(r,t,e,n,o){if(t===void 0&&(t=0),e===void 0&&(e=1),n!=null&&n==="bool")throw new Error("Unsupported data type "+n);for(var a=new Ia(t,e,n,!0,o),i=oe(r,n),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Pe=D({unstack_:function(r,t){t===void 0&&(t=0),t=t||0;var e=_(r,"x","unstack");E(t>=-e.shape.length&&t<e.shape.length,function(){return"Axis = "+t+" is not in [-"+e.shape.length+", "+e.shape.length+")"}),t<0&&(t+=e.shape.length);var n={axis:t};return T.runKernelFunc(function(o){return o.unstack(e,t)},{x:e},function(o){return{x:function(){return ct(o,t)}}},"Unpack",n)}}),bh=function(r,t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s,u,c,l,h;return $(this,function(f){switch(f.label){case 0:return e=_(r,"x","setdiff1d"),n=_(t,"y","setdiff1d"),E(e.dtype===n.dtype,function(){return"x and y should have the same dtype, but got x ("+e.dtype+") and y ("+n.dtype+")."}),E(e.rank===1,function(){return"x should be 1D tensor, but got x ("+e.shape+")."}),E(n.rank===1,function(){return"y should be 1D tensor, but got y ("+n.shape+")."}),[4,e.data()];case 1:return o=f.sent(),[4,n.data()];
vendor: 34,067 bytes, lines 29-216
29case 2:for(a=f.sent(),i=new Set(a),s=0,l=0;l<o.length;l++)i.has(o[l])||s++;for(u=new nr([s],e.dtype),c=new nr([s],"int32"),l=0,h=0;l<o.length;l++)i.has(o[l])||(u.values[h]=o[l],c.values[h]=l,h++);return[2,[u.toTensor(),c.toTensor()]]}})})};function Vr(r,t,e,n){n===void 0&&(n=!0);var o=[];if(n)(o=o.concat(t.slice(0))).push(r[0]/e),o=o.concat(r.slice(1));else{o=o.concat(r[0]);for(var a=t.length,i=0;i<a;++i)o=o.concat([r[i+1]/t[i],t[i]]);o=o.concat(r.slice(a+1))}return o}function zr(r,t,e){e===void 0&&(e=!0);var n=[];if(e){n.push(t);for(var o=t+1;o<r;++o)o<=2*t?(n.push(o),n.push(o-(t+1))):n.push(o)}else{var a=[],i=[];for(o=1;o<r;++o)o>=2*t+1||o%2==1?i.push(o):a.push(o);n.push.apply(n,a),n.push(0),n.push.apply(n,i)}return n}function Gr(r,t,e,n){n===void 0&&(n=!0);var o=[];n?o.push(r[0]/e):o.push(r[0]*e);for(var a=1;a<r.length;++a)a<=t.length?n?o.push(t[a-1]*r[a]):o.push(r[a]/t[a-1]):o.push(r[a]);return o}function js(r,t){for(var e=[0],n=0;n<t;++n)e.push(r[n][0]);return e}function Ks(r,t,e){for(var n=r.slice(0,1),o=0;o<e;++o)n.push(r[o+1]-t[o][0]-t[o][1]);return n}function Xs(r,t){if(r.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+r.rank+".");if(t.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if(t.dtype!=="int32")throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.shape[t.rank-1]>r.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+r.rank);if(r.size===0)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+r.shape+".");for(var e=t.shape,n=e[e.length-1],o=1,a=0;a<e.length-1;++a)o*=e[a];var i=r.shape,s=e.slice();s.pop();var u=1;for(a=n;a<r.rank;++a)u*=i[a],s.push(i[a]);var c=Dt(r.shape).map(function(l){return l/u}).concat([1]).slice(0,n);return[s,o,u,c]}var $s=30;function No(r){return r<=$s?r:ta(r,Math.floor(Math.sqrt(r)))}function wh(r,t,e){var n=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+t.shape+", shape: "+r+", sliceDim: "+n+", and batchDim: "+o+".";if(e.rank<o)throw new Error(a+" update.rank < "+o+". ");if(r.length<n+(e.rank-o))throw new Error(a+" Output shape length < "+(n+(e.rank-o)));if(e.rank!==o+r.length-n)throw new Error(a+" update.rank != "+(o+r.length-n));for(var i=0;i<o;++i)if(e.shape[i]!==t.shape[i])throw new Error(a+" updates.shape["+i+"] ("+e.shape[i]+") != indices.shape["+i+"] ("+t.shape[i]+").");for(i=0;i<e.rank-o;++i)if(e.shape[i+o]!==r[i+n])throw new Error(a+" updates.shape["+(i+o)+"] ("+e.shape[i+o]+") != shape["+(i+o)+"] ("+r[i+o]+")")}function Ch(r,t,e){if(t.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if(r.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+r.rank+".");if(t.dtype!=="int32")throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.dtype);if(e.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+e);if(e.length===0){if(t.size===0)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(r.size===0)throw new Error("Updates specified for empty output. updates shape: "+r.shape)}wh(e,t,r)}function Hr(r,t,e){for(var n=t.shape.length,o=n>1?t.shape[n-1]:1,a=e.length,i=1,s=o;s<a;++s)i*=e[s];var u=o<1?1:o;return{sliceRank:o,numUpdates:Y(t.shape)/u,sliceSize:i,strides:Dt(e.slice(0,o)).concat([1]),outputSize:Y(e)}}function _h(r,t,e){E(r.rank===t.length,function(){return"Error in slice"+r.rank+"D: Length of begin "+t+" must match the rank of the array ("+r.rank+")."}),E(r.rank===e.length,function(){return"Error in slice"+r.rank+"D: Length of size "+e+" must match the rank of the array ("+r.rank+")."});for(var n=function(a){E(t[a]+e[a]<=r.shape[a],function(){return"Error in slice"+r.rank+"D: begin["+a+"] + size["+a+"] ("+(t[a]+e[a])+") would overflow input.shape["+a+"] ("+r.shape[a]+")"})},o=0;o<r.rank;++o)n(o)}function Pi(r){for(var t=[],e=0;r>0;)1&r&&t.push(e),r/=2,e++;return t}function Ra(r,t,e){for(var n=[],o=0;o<r.length;o++)n[o]=Math.ceil((t[o]-r[o])/e[o]);return n}function Eh(r,t,e,n,o){var a=t[o],i=e[o]||1;(r&1<<o||a==null)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),a=Qo(0,a,s-1)}function Ih(r,t,e,n,o){var a=t[o],i=e[o]||1;(r&1<<o||a==null)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),a=i>0?Qo(0,a,s):Qo(-1,a,s-1)}function Ys(r,t,e){for(var n=e.length,o=0;o<e.length;o++)if(e[o]>1){n=o;break}for(o=n+1;o<e.length;o++)if(t[o]>0||e[o]!==r[o])return!1;return!0}function Js(r,t){for(var e=r.length>0?r[r.length-1]:1,n=0;n<r.length-1;n++)e+=r[n]*t[n];return e}function Rh(r,t){E(ea(r),function(){return"The f passed in variableGrads(f) must be a function"}),E(t==null||Array.isArray(t)&&t.every(function(l){return l instanceof Gn}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var e=t!=null;if(!e)for(var n in t=[],T.registeredVariables)t.push(T.registeredVariables[n]);var o=e?t.filter(function(l){return!l.trainable}):null,a=t.length;E((t=t.filter(function(l){return l.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var i=T.gradients(r,t,null,!0),s=i.value,u=i.grads;E(u.some(function(l){return l!=null}),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()."}),E(s.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return t.forEach(function(l,h){u[h]!=null&&(c[l.name]=u[h])}),o!=null&&o.forEach(function(l){return c[l.name]=null}),{value:s,grads:c}}function oo(r){return T.customGrad(r)}var Gt=D({softmax_:function(r,t){t===void 0&&(t=-1);var e=_(r,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+t);return T.runKernelFunc(function(n,o){var a=n.softmax(e,t);return o([a]),a},{logits:e},function(n,o){var a=o[0],i=n.mul(a);return{logits:function(){return i.sub(i.sum([t],!0).mul(a))}}},"Softmax",{dim:t},[],[!0])}}),kh=D({logSoftmax_:function(r,t){t===void 0&&(t=-1);var e=_(r,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and axis was "+t);return oo(function(n,o){var a=n.max(t,!0),i=n.sub(a),s=i.toFloat().sub(i.exp().sum(t,!0).log());return o([s]),{value:s,gradFunc:function(u,c){var l=c[0].exp();return u.sub(u.sum(t,!0).mul(l))}}})(e)}}),Qs=function(){function r(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return r.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},r.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},r.prototype.has=function(t){return this.data.has(t)},r.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},r.prototype.numDataIds=function(){return this.dataIdsCount},r}(),Zs=function(){function r(){}return r.prototype.time=function(t){return F("time")},r.prototype.read=function(t){return F("read")},r.prototype.readSync=function(t){return F("readSync")},r.prototype.numDataIds=function(){return F("numDataIds")},r.prototype.disposeData=function(t){return F("disposeData")},r.prototype.write=function(t,e,n){return F("write")},r.prototype.move=function(t,e,n,o){return F("move")},r.prototype.memory=function(){return F("memory")},r.prototype.floatPrecision=function(){return F("floatPrecision")},r.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},r.prototype.batchMatMul=function(t,e,n,o){return F("batchMatMul")},r.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,F("fusedBatchMatMul")},r.prototype.slice=function(t,e,n){return F("slice")},r.prototype.stridedSlice=function(t,e,n,o){return F("stridedSlice")},r.prototype.unstack=function(t,e){return F("unstack")},r.prototype.reverse=function(t,e){return F("reverse")},r.prototype.concat=function(t,e){return F("concat")},r.prototype.neg=function(t){return F("neg")},r.prototype.add=function(t,e){return F("add")},r.prototype.addN=function(t){return F("addN")},r.prototype.subtract=function(t,e){return F("subtract")},r.prototype.multiply=function(t,e){return F("multiply")},r.prototype.realDivide=function(t,e){return F("realDivide")},r.prototype.floorDiv=function(t,e){return F("floorDiv")},r.prototype.sum=function(t,e){return F("sum")},r.prototype.prod=function(t,e){return F("prod")},r.prototype.unsortedSegmentSum=function(t,e,n){return F("unsortedSegmentSum")},r.prototype.argMin=function(t,e){return F("argMin")},r.prototype.argMax=function(t,e){return F("argMax")},r.prototype.equal=function(t,e){return F("equal")},r.prototype.notEqual=function(t,e){return F("notEqual")},r.prototype.less=function(t,e){return F("less")},r.prototype.lessEqual=function(t,e){return F("lessEqual")},r.prototype.greater=function(t,e){return F("greater")},r.prototype.greaterEqual=function(t,e){return F("greaterEqual")},r.prototype.logicalNot=function(t){return F("logicalNot")},r.prototype.logicalAnd=function(t,e){return F("logicalAnd")},r.prototype.logicalOr=function(t,e){return F("logicalOr")},r.prototype.where=function(t){return F("where")},r.prototype.select=function(t,e,n){return F("select")},r.prototype.topk=function(t,e,n){return F("topk")},r.prototype.min=function(t,e){return F("min")},r.prototype.minimum=function(t,e){return F("minimum")},r.prototype.mod=function(t,e){return F("mod")},r.prototype.max=function(t,e){return F("max")},r.prototype.maximum=function(t,e){return F("maximum")},r.prototype.all=function(t,e){return F("all")},r.prototype.any=function(t,e){return F("any")},r.prototype.squaredDifference=function(t,e){return F("squaredDifference")},r.prototype.ceil=function(t){return F("ceil")},r.prototype.floor=function(t){return F("floor")},r.prototype.round=function(t){return F("round")},r.prototype.sign=function(t){return F("sign")},r.prototype.isNaN=function(t){return F("isNaN")},r.prototype.isInf=function(t){return F("isInf")},r.prototype.isFinite=function(t){return F("isFinite")},r.prototype.pow=function(t,e){return F("pow")},r.prototype.exp=function(t){return F("exp")},r.prototype.expm1=function(t){return F("expm1")},r.prototype.softmax=function(t,e){return F("softmax")},r.prototype.log=function(t){return F("log")},r.prototype.log1p=function(t){return F("log1p")},r.prototype.sqrt=function(t){return F("sqrt")},r.prototype.rsqrt=function(t){return F("rsqrt")},r.prototype.square=function(t){return F("square")},r.prototype.reciprocal=function(t){return F("reciprocal")},r.prototype.relu=function(t){return F("relu")},r.prototype.relu6=function(t){return F("relu6")},r.prototype.prelu=function(t,e){return F("prelu")},r.prototype.elu=function(t){return F("elu")},r.prototype.eluDer=function(t,e){return F("eluDer")},r.prototype.selu=function(t){return F("selu")},r.prototype.int=function(t){return F("int")},r.prototype.clip=function(t,e,n){return F("clip")},r.prototype.abs=function(t){return F("abs")},r.prototype.complexAbs=function(t){return F("complexAbs")},r.prototype.sigmoid=function(t){return F("sigmoid")},r.prototype.softplus=function(t){return F("softplus")},r.prototype.sin=function(t){return F("sin")},r.prototype.cos=function(t){return F("cos")},r.prototype.tan=function(t){return F("tan")},r.prototype.asin=function(t){return F("asin")},r.prototype.acos=function(t){return F("acos")},r.prototype.atan=function(t){return F("atan")},r.prototype.atan2=function(t,e){return F("atan2")},r.prototype.sinh=function(t){return F("sinh")},r.prototype.cosh=function(t){return F("cosh")},r.prototype.tanh=function(t){return F("tanh")},r.prototype.asinh=function(t){return F("asinh")},r.prototype.acosh=function(t){return F("acosh")},r.prototype.atanh=function(t){return F("atanh")},r.prototype.erf=function(t){return F("erf")},r.prototype.step=function(t,e){return F("step")},r.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,F("fusedConv2d")},r.prototype.conv2d=function(t,e,n){return F("conv2d")},r.prototype.conv2dDerInput=function(t,e,n){return F("conv2dDerInput")},r.prototype.conv2dDerFilter=function(t,e,n){return F("conv2dDerFilter")},r.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,F("fusedDepthwiseConv2D")},r.prototype.depthwiseConv2D=function(t,e,n){return F("depthwiseConv2D")},r.prototype.depthwiseConv2DDerInput=function(t,e,n){return F("depthwiseConv2DDerInput")},r.prototype.depthwiseConv2DDerFilter=function(t,e,n){return F("depthwiseConv2DDerFilter")},r.prototype.conv3d=function(t,e,n){return F("conv3d")},r.prototype.conv3dDerInput=function(t,e,n){return F("conv3dDerInput")},r.prototype.conv3dDerFilter=function(t,e,n){return F("conv3dDerFilter")},r.prototype.maxPool=function(t,e){return F("maxPool")},r.prototype.maxPoolBackprop=function(t,e,n,o){return F("maxPoolBackprop")},r.prototype.avgPool=function(t,e){return F("avgPool")},r.prototype.avgPoolBackprop=function(t,e,n){return F("avgPoolBackprop")},r.prototype.avgPool3d=function(t,e){return F("avgPool3d")},r.prototype.avgPool3dBackprop=function(t,e,n){return F("avgPool3dBackprop")},r.prototype.maxPool3d=function(t,e){return F("maxPool3d")},r.prototype.maxPool3dBackprop=function(t,e,n,o){return F("maxPool3dBackprop")},r.prototype.reshape=function(t,e){return F("reshape")},r.prototype.cast=function(t,e){return F("cast")},r.prototype.tile=function(t,e){return F("tile")},r.prototype.pad=function(t,e,n){return F("pad")},r.prototype.transpose=function(t,e){return F("transpose")},r.prototype.gather=function(t,e,n){return F("gather")},r.prototype.gatherND=function(t,e){return F("gatherND")},r.prototype.scatterND=function(t,e,n){return F("scatterND")},r.prototype.batchToSpaceND=function(t,e,n){return F("batchToSpaceND")},r.prototype.spaceToBatchND=function(t,e,n){return F("spaceToBatchND")},r.prototype.resizeBilinear=function(t,e,n,o){return F("resizeBilinear")},r.prototype.resizeBilinearBackprop=function(t,e,n){return F("resizeBilinearBackprop")},r.prototype.resizeNearestNeighbor=function(t,e,n,o){return F("resizeNearestNeighbor")},r.prototype.resizeNearestNeighborBackprop=function(t,e,n){return F("resizeNearestNeighborBackprop")},r.prototype.batchNormalization=function(t,e,n,o,a,i){return F("batchNormalization")},r.prototype.localResponseNormalization4D=function(t,e,n,o,a){return F("localResponseNormalization4D")},r.prototype.LRNGrad=function(t,e,n,o,a,i,s){return F("LRNGrad")},r.prototype.multinomial=function(t,e,n,o){return F("multinomial")},r.prototype.oneHot=function(t,e,n,o){return F("oneHot")},r.prototype.cumsum=function(t,e,n,o){return F("cumsum")},r.prototype.nonMaxSuppression=function(t,e,n,o,a){return F("nonMaxSuppression")},r.prototype.fft=function(t){return F("fft")},r.prototype.ifft=function(t){return F("ifft")},r.prototype.complex=function(t,e){return F("complex")},r.prototype.real=function(t){return F("real")},r.prototype.imag=function(t){return F("imag")},r.prototype.cropAndResize=function(t,e,n,o,a,i){return F("cropAndResize")},r.prototype.depthToSpace=function(t,e,n){return F("depthToSpace")},r.prototype.split=function(t,e,n){return F("split")},r.prototype.sparseToDense=function(t,e,n,o){return F("sparseToDense")},r.prototype.diag=function(t){return F("diag")},r.prototype.fill=function(t,e,n){return F("fill")},r.prototype.onesLike=function(t){return F("onesLike")},r.prototype.zerosLike=function(t){return F("zerosLike")},r.prototype.linspace=function(t,e,n){return F("linspace")},r.prototype.dispose=function(){return F("dispose")},r}();function F(r){throw new Error("'"+r+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function Jt(r,t){for(var e=r.length,n=[],o=0;o<e;o++){var a=e-1-o,i=r[a]||1;(t[t.length-1-o]||1)>1&&i===1&&n.unshift(a)}return n}function Me(r,t){for(var e=[],n=0;n<t.length;n++){var o=r[r.length-n-1],a=t.length-n-1,i=t[a];(o==null||o===1&&i>1)&&e.unshift(a)}return e}function le(r,t){for(var e=[],n=Math.max(r.length,t.length),o=0;o<n;o++){var a=r[r.length-o-1];a==null&&(a=1);var i=t[t.length-o-1];if(i==null&&(i=1),a===1)e.unshift(i);else if(i===1)e.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+r+" and "+t+".");e.unshift(a)}}return e}function or(r,t,e,n,o,a,i){i===void 0&&(i="channelsLast");var s,u=Kr(t),c=u[0],l=u[1];if(i==="channelsLast")s=[c,l,r[3],r[3]];else{if(i!=="channelsFirst")throw new Error("Unknown dataFormat "+i);s=[c,l,r[1],r[1]]}return bn(r,s,e,n,o,a,!1,i)}function qr(r,t,e,n,o,a,i){i===void 0&&(i="NDHWC");var s,u,c=ua(t),l=c[0],h=c[1],f=c[2];if(i==="NDHWC")u="channelsLast",s=[l,h,f,r[4],r[4]];else{if(i!=="NCDHW")throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,h,f,r[1],r[1]]}return jr(r,s,e,n,o,!1,u,a)}function bn(r,t,e,n,o,a,i,s){i===void 0&&(i=!1),s===void 0&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3];if(s==="channelsLast")c=r[0],l=r[1],h=r[2],f=r[3];else{if(s!=="channelsFirst")throw new Error("Unknown dataFormat "+s);c=r[0],f=r[1],l=r[2],h=r[3]}var p,d=t[0],g=t[1],v=t[3],m=Kr(e),x=m[0],b=m[1],y=Kr(n),w=y[0],C=y[1],S=On(d,w),k=On(g,C),I=function(O,B,V,U,W,G,H,j){var ee,te,ie;if(typeof O=="number"){ee={top:O,bottom:O,left:O,right:O,type:O===0?"VALID":"NUMBER"};var se=function(fe,xe,me,ke,Ce){ke==null&&(ke=eu(fe,xe,me));var _e=fe[0],xt=fe[1],bt=Zn((_e-xe+2*ke)/me+1,Ce);E(Ae(bt),function(){return"The output # of rows ("+bt+") must be an integer. Change the stride and/or zero pad parameters"});var nt=Zn((xt-xe+2*ke)/me+1,Ce);return E(Ae(nt),function(){return"The output # of columns ("+nt+") must be an integer. Change the stride and/or zero pad parameters"}),[bt,nt]}([B,V],G,U,O,j);te=se[0],ie=se[1]}else if(O==="same"){te=Math.ceil(B/U),ie=Math.ceil(V/W);var ce=Math.max(0,(te-1)*U+G-B),pe=Math.max(0,(ie-1)*W+H-V),he=Math.floor(ce/2),de=ce-he,De=Math.floor(pe/2);ee={top:he,bottom:de,left:De,right:pe-De,type:"SAME"}}else{if(O!=="valid")throw Error("Unknown padding parameter: "+O);ee={top:0,bottom:0,left:0,right:0,type:"VALID"},te=Math.ceil((B-G+1)/U),ie=Math.ceil((V-H+1)/W)}return{padInfo:ee,outHeight:te,outWidth:ie}}(o,l,h,x,b,S,k,a),R=I.padInfo,N=I.outHeight,A=I.outWidth,L=i?v*f:v;return s==="channelsFirst"?p=[c,L,N,A]:s==="channelsLast"&&(p=[c,N,A,L]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:h,inChannels:f,outHeight:N,outWidth:A,outChannels:L,padInfo:R,strideHeight:x,strideWidth:b,filterHeight:d,filterWidth:g,effectiveFilterHeight:S,effectiveFilterWidth:k,dilationHeight:w,dilationWidth:C,inShape:r,outShape:p,filterShape:t}}function jr(r,t,e,n,o,a,i,s){a===void 0&&(a=!1),i===void 0&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3],p=u[4];if(i==="channelsLast")c=r[0],l=r[1],h=r[2],f=r[3],p=r[4];else{if(i!=="channelsFirst")throw new Error("Unknown dataFormat "+i);c=r[0],p=r[1],l=r[2],h=r[3],f=r[4]}var d,g=t[0],v=t[1],m=t[2],x=t[4],b=ua(e),y=b[0],w=b[1],C=b[2],S=ua(n),k=S[0],I=S[1],R=S[2],N=On(g,k),A=On(v,I),L=On(m,R),O=function(H,j,ee,te,ie,se,ce,pe,he,de,De){var fe,xe,me,ke;if(typeof H=="number"){fe={top:H,bottom:H,left:H,right:H,front:H,back:H,type:H===0?"VALID":"NUMBER"};var Ce=function(En,Lt,yo,In,wt,xo){wt==null&&(wt=eu(En,Lt,In));var zc=En[0],Gc=En[1],Hc=En[2],bo=Zn((zc-Lt+2*wt)/In+1,xo);E(Ae(bo),function(){return"The output # of depths ("+bo+") must be an integer. Change the stride and/or zero pad parameters"});var wo=Zn((Gc-Lt+2*wt)/In+1,xo);E(Ae(wo),function(){return"The output # of rows ("+wo+") must be an integer. Change the stride and/or zero pad parameters"});var Co=Zn((Hc-Lt+2*wt)/In+1,xo);return E(Ae(Co),function(){return"The output # of columns ("+Co+") must be an integer. Change the stride and/or zero pad parameters"}),[bo,wo,Co,yo]}([j,ee,te,1],pe,1,ie,H,De);xe=Ce[0],me=Ce[1],ke=Ce[2]}else if(H==="same"){xe=Math.ceil(j/ie),me=Math.ceil(ee/se),ke=Math.ceil(te/ce);var _e=(xe-1)*ie+pe-j,xt=(me-1)*se+he-ee,bt=(ke-1)*ce+de-te,nt=Math.floor(_e/2),_n=_e-nt,Ot=Math.floor(xt/2),Xt=xt-Ot,Bt=Math.floor(bt/2);fe={top:Ot,bottom:Xt,left:Bt,right:bt-Bt,front:nt,back:_n,type:"SAME"}}else{if(H!=="valid")throw Error("Unknown padding parameter: "+H);fe={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},xe=Math.ceil((j-pe+1)/ie),me=Math.ceil((ee-he+1)/se),ke=Math.ceil((te-de+1)/ce)}return{padInfo:fe,outDepth:xe,outHeight:me,outWidth:ke}}(o,l,h,f,y,w,C,N,A,L,s),B=O.padInfo,V=O.outDepth,U=O.outHeight,W=O.outWidth,G=a?x*p:x;return i==="channelsFirst"?d=[c,G,V,U,W]:i==="channelsLast"&&(d=[c,V,U,W,G]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:h,inWidth:f,inChannels:p,outDepth:V,outHeight:U,outWidth:W,outChannels:G,padInfo:B,strideDepth:y,strideHeight:w,strideWidth:C,filterDepth:g,filterHeight:v,filterWidth:m,effectiveFilterDepth:N,effectiveFilterHeight:A,effectiveFilterWidth:L,dilationDepth:k,dilationHeight:I,dilationWidth:R,inShape:r,outShape:d,filterShape:t}}function eu(r,t,e,n){n===void 0&&(n=1);var o=On(t,n);return Math.floor((r[0]*(e-1)-e+o)/2)}function Kr(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function ua(r){return typeof r=="number"?[r,r,r]:r}function On(r,t){return t<=1?r:r+(r-1)*(t-1)}function Zn(r,t){if(!t)return r;switch(t){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error("Unknown roundingMode "+t)}}function qn(r){var t=Kr(r),e=t[0],n=t[1],o=t[2];return e===1&&n===1&&o===1}function tt(r,t){return qn(r)||qn(t)}function ka(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error("Unknown dataFormat "+r)}function tu(r,t,e){if(t==="complex64"){if(r.dtype==="complex64")return r.clone();var n=we(r.shape),o=r.toFloat(),a=e.complex(o,n);return n.dispose(),o.dispose(),a}if(!el(r.dtype,t))return T.makeTensorFromDataId(r.dataId,r.shape,t);if(r.dtype==="complex64"){var i=e.real(r);return a=i.cast(t),i.dispose(),a}if(t==="int32")return e.int(r);if(t==="bool"){var s=q(0,r.dtype);return a=e.notEqual(r,s),s.dispose(),a}throw new Error("Error in Cast: failed to cast "+r.dtype+" to "+t)}function ca(r,t){return T.makeTensorFromDataId(r.dataId,t,r.dtype)}function nu(r,t,e){var n=(t-r)/(e-1),o=cr(e,"float32");o[0]=r;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return Te(o,"float32")}function la(r,t){if(r.length!==t.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+r.length+", imag: "+t.length+".");for(var e=new Float32Array(2*r.length),n=0;n<e.length;n+=2)e[n]=r[n/2],e[n+1]=t[n/2];return e}function Mi(r,t){return{real:r[2*t],imag:r[2*t+1]}}function Sh(r,t,e,n){r[2*n]=t,r[2*n+1]=e}function Dh(r,t,e){var n=(e?2:-2)*Math.PI*(r/t);return{real:Math.cos(n),imag:Math.sin(n)}}function Ah(r,t,e){var n=function(a,i,s){return function(u,c,l){for(var h=0,f=u.length,p=0,d=!1;h<f;){var g=l(c,u[p=h+(f-h>>>1)]);g>0?h=p+1:(f=p,d=!g)}return d?h:-h-1}(a,i,s||Th)}(r,t,e),o=n<0?-(n+1):n;r.splice(o,0,t)}function Th(r,t){return r>t?1:r<t?-1:0}function Sa(r,t,e,n,o){return ru(r,t,e,n,o,0).selectedIndices}function Da(r,t,e,n,o,a){var i=ru(r,t,e,n,o,a);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function ru(r,t,e,n,o,a,i,s){s===void 0&&(s=!1);for(var u=Array.from(t).map(function(y,w){return{score:y,boxIndex:w,suppressBeginIndex:0}}).filter(function(y){return y.score>o}).sort(Oi),c=a>0?-.5/a:0,l=[],h=[];l.length<e&&u.length>0;){var f=u.pop(),p=f.score,d=f.boxIndex,g=f.suppressBeginIndex;if(p<o)break;for(var v=!1,m=l.length-1;m>=g;--m){var x=Nh(r,d,l[m]);if(x>=n){v=!0;break}if(f.score=f.score*Fh(n,c,x),f.score<=o)break}f.suppressBeginIndex=l.length,v||(f.score===p?(l.push(d),h.push(f.score)):f.score>o&&Ah(u,f,Oi))}var b=l.length;return s&&(l.fill(0,b),h.fill(0,b)),{selectedIndices:Te(l,"int32"),selectedScores:Te(h,"float32"),numValidOutputs:q(b,"int32")}}function Nh(r,t,e){var n=r.subarray(4*t,4*t+4),o=r.subarray(4*e,4*e+4),a=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),s=Math.max(n[0],n[2]),u=Math.max(n[1],n[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-a)*(u-i),d=(h-c)*(f-l);if(p<=0||d<=0)return 0;var g=Math.max(a,c),v=Math.max(i,l),m=Math.min(s,h),x=Math.min(u,f),b=Math.max(m-g,0)*Math.max(x-v,0);return b/(p+d-b)}function Fh(r,t,e){var n=Math.exp(t*e*e);return e<=r?n:0}function Oi(r,t){return r.score-t.score||r.score===t.score&&t.boxIndex-r.boxIndex}function ou(r,t,e){var n=new Array(r.rank).fill(0),o=r.shape.slice();return t.map(function(a){o[e]=a;var i=r.slice(n,o);return n[e]+=a,i})}function au(r,t){for(var e=new Array(r.rank),n=0;n<e.length;n++)e[n]=r.shape[n]*t[n];var o=oe(e,r.dtype);for(n=0;n<o.values.length;++n){for(var a=o.indexToLoc(n),i=new Array(r.rank),s=0;s<i.length;s++)i[s]=a[s]%r.shape[s];var u=r.locToIndex(i);o.values[n]=r.values[u]}return o.toTensor()}function iu(r,t,e,n,o){for(var a=t[t.length-1],i=[r.length/a,a],s=i[0],u=i[1],c=tr(e,s*n),l=tr("int32",s*n),h=0;h<s;h++){for(var f=h*u,p=r.subarray(f,f+u),d=[],g=0;g<p.length;g++)d.push({value:p[g],index:g});d.sort(function(y,w){return w.value-y.value});var v=h*n,m=c.subarray(v,v+n),x=l.subarray(v,v+n);for(g=0;g<n;g++)m[g]=d[g].value,x[g]=d[g].index}var b=t.slice();return b[b.length-1]=n,[Ge(c,b,e),Ge(l,b,"int32")]}function Aa(r,t){for(var e=[],n=0;n<t.length;n++)t[n]&&e.push(n);var o=oe(r,"int32"),a=oe([e.length,r.length],"int32");for(n=0;n<e.length;n++){var i=o.indexToLoc(e[n]),s=n*r.length;a.values.set(i,s)}return a.toTensor()}var Ph=function(r,t){this.outputShape=[],this.outputShape=r,this.variableNames=t.map(function(o,a){return"T"+a});var e=[];this.variableNames.forEach(function(o){e.push("float v"+o+" = get"+o+"AtOutCoords();")});var n=this.variableNames.map(function(o){return"v"+o}).join(" + ");this.userCode=`
30      void main() {
31        `+e.join(`
32        `)+`
33
34        float result = `+n+`;
35        setOutput(result);
36      }
37    `},Mh=function(r,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.variableNames=t.map(function(o,a){return"T"+a});var e=[];this.variableNames.forEach(function(o){e.push("vec4 v"+o+" = get"+o+"AtOutCoords();")});var n=this.variableNames.map(function(o){return"v"+o}).join(" + ");this.userCode=`
38      void main() {
39        `+e.join(`
40        `)+`
41
42        vec4 result = `+n+`;
43        setOutput(result);
44      }
45    `},Oh=function(r,t,e){this.variableNames=["A"];var n=r.windowSize,o=r.batchSize,a=r.inSize,i=Math.ceil(a/n);e||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];var s=t==="max"?">":"<",u=e?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
46      void main() {
47        ivec2 coords = getOutputCoords();
48        int batch = coords[0];
49        int outIdx = coords[1];
50        int inOffset = outIdx * `+n+`;
51
52        int bestIndex = inOffset;
53        float bestValue = getA(batch, bestIndex);
54
55        for (int i = 0; i < `+n+`; i++) {
56          int inIdx = `+u+`;
57          float candidate = getA(batch, inIdx);
58          if (candidate `+s+` bestValue) {
59            bestValue = candidate;
60            bestIndex = inIdx;
61          }
62        }
63        setOutput(float(bestIndex));
64      }
65    `};function su(r,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return r+"."+e})}function Qe(r,t){return t===1?[r]:su(r,t)}function je(){var r,t,e,n,o,a,i,s,u,c;return M().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",t="in",e="out",n="in",o="texture",a="outputColor",i="out vec4 outputColor;",s=`
66      bool isnan_custom(float val) {
67        return (val > 0.0 || val < 0.0) ? false : val != 0.0;
68      }
69
70      bvec4 isnan_custom(vec4 val) {
71        return bvec4(isnan_custom(val.x),
72          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
73      }
74
75      #define isnan(value) isnan_custom(value)
76    `,u="",c=`
77      #define round(value) newRound(value)
78      int newRound(float value) {
79        return int(floor(value + 0.5));
80      }
81
82      ivec4 newRound(vec4 value) {
83        return ivec4(floor(value + vec4(0.5)));
84      }
85    `):(r="",t="attribute",e="varying",n="varying",o="texture2D",a="gl_FragColor",i="",s=`
86      #define isnan(value) isnan_custom(value)
87      bool isnan_custom(float val) {
88        return (val > 0. || val < 1. || val == 0.) ? false : true;
89      }
90      bvec4 isnan_custom(vec4 val) {
91        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
92      }
93    `,u=`
94      uniform float INFINITY;
95
96      bool isinf(float val) {
97        return abs(val) == INFINITY;
98      }
99      bvec4 isinf(vec4 val) {
100        return equal(abs(val), vec4(INFINITY));
101      }
102    `,c=`
103      int round(float value) {
104        return int(floor(value + 0.5));
105      }
106
107      ivec4 round(vec4 value) {
108        return ivec4(floor(value + vec4(0.5)));
109      }
110    `),{version:r,attribute:t,varyingVs:e,varyingFs:n,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function fn(r,t,e){e===void 0&&(e="index");var n=Dt(t);return n.map(function(o,a){return"int "+r[a]+" = "+e+" / "+o+"; "+(a===n.length-1?"int "+r[a+1]+" = "+e+" - "+r[a]+" * "+o:"index -= "+r[a]+" * "+o)+";"}).join("")}function Ta(r){var t=Dt(r).map(function(e){return e.toString()});return`
111  int getFlatIndex(ivec3 coords) {
112    return coords.x * `+t[0]+" + coords.y * "+t[1]+` + coords.z;
113  }
114`}var uu=`
115  const float FLOAT_MAX = 1.70141184e38;
116  const float FLOAT_MIN = 1.17549435e-38;
117
118  lowp vec4 encode_float(highp float v) {
119    if (isnan(v)) {
120      return vec4(255, 255, 255, 255);
121    }
122
123    highp float av = abs(v);
124
125    if(av < FLOAT_MIN) {
126      return vec4(0.0, 0.0, 0.0, 0.0);
127    } else if(v > FLOAT_MAX) {
128      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
129    } else if(v < -FLOAT_MAX) {
130      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;
131    }
132
133    highp vec4 c = vec4(0,0,0,0);
134
135    highp float e = floor(log2(av));
136    highp float m = exp2(fract(log2(av))) - 1.0;
137
138    c[2] = floor(128.0 * m);
139    m -= c[2] / 128.0;
140    c[1] = floor(32768.0 * m);
141    m -= c[1] / 32768.0;
142    c[0] = floor(8388608.0 * m);
143
144    highp float ebias = e + 127.0;
145    c[3] = floor(ebias / 2.0);
146    ebias -= c[3] * 2.0;
147    c[2] += floor(ebias) * 128.0;
148
149    c[3] += 128.0 * step(0.0, -v);
150
151    return c / 255.0;
152  }
153`;function Bh(r,t,e,n){var o=[];r.forEach(function(p){var d=Y(p.shapeInfo.logicalShape);p.shapeInfo.isUniform?o.push("uniform float "+p.name+(d>1?"["+d+"]":"")+";"):(o.push("uniform sampler2D "+p.name+";"),o.push("uniform int offset"+p.name+";"))});var a,i,s=o.join(`
154`),u=r.map(function(p){return function(d,g,v){v===void 0&&(v=!1);var m="";m+=v?cu(d):An(d);var x=d.shapeInfo.logicalShape,b=g.logicalShape;return x.length<=b.length&&(m+=v?function(y,w){var C,S=y.name,k=S.charAt(0).toUpperCase()+S.slice(1),I="get"+k+"AtOutCoords",R=y.shapeInfo.logicalShape.length,N=w.logicalShape.length,A=Jt(y.shapeInfo.logicalShape,w.logicalShape),L=be(N),O=N-R,B=["x","y","z","w","u","v"];C=R===0?"":N<2&&A.length>=1?"coords = 0;":A.map(function(ee){return"coords."+B[ee+O]+" = 0;"}).join(`
155`);var V="";V=N<2&&R>0?"coords":y.shapeInfo.logicalShape.map(function(ee,te){return"coords."+B[te+O]}).join(", ");var U="return outputValue;",W=Y(y.shapeInfo.logicalShape)===1,G=Y(w.logicalShape)===1;if(R!==1||W||G){if(W&&!G)U=N===1?`
156        return vec4(outputValue.x, outputValue.x, 0., 0.);
157      `:`
158        return vec4(outputValue.x);
159      `;else if(A.length){var H=R-2,j=R-1;A.indexOf(H)>-1&&A.indexOf(j)>-1?U="return vec4(outputValue.x);":A.indexOf(H)>-1?U="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":A.indexOf(j)>-1&&(U="return vec4(outputValue.xx, outputValue.zz);")}}else U=`
160      return vec4(outputValue.xy, outputValue.xy);
161    `;return`
162    vec4 `+I+`() {
163      `+L+` coords = getOutputCoords();
164      `+C+`
165      vec4 outputValue = get`+k+"("+V+`);
166      `+U+`
167    }
168  `}(d,g):function(y,w){var C=y.name,S=C.charAt(0).toUpperCase()+C.slice(1),k="get"+S+"AtOutCoords",I=w.texShape,R=y.shapeInfo.texShape,N=y.shapeInfo.logicalShape.length,A=w.logicalShape.length;if(!y.shapeInfo.isUniform&&N===A&&y.shapeInfo.flatOffset==null&&We(R,I))return`
169      float `+k+`() {
170        return sampleTexture(`+C+`, resultUV);
171      }
172    `;var L,O=be(A),B=Jt(y.shapeInfo.logicalShape,w.logicalShape),V=A-N,U=["x","y","z","w","u","v"];L=N===0?"":A<2&&B.length>=1?"coords = 0;":B.map(function(G){return"coords."+U[G+V]+" = 0;"}).join(`
173`);var W="";return W=A<2&&N>0?"coords":y.shapeInfo.logicalShape.map(function(G,H){return"coords."+U[H+V]}).join(", "),`
174    float `+k+`() {
175      `+O+` coords = getOutputCoords();
176      `+L+`
177      return get`+S+"("+W+`);
178    }
179  `}(d,g)),m}(p,t,n)}).join(`
180`),c=t.texShape,l=je(),h=function(p){return`
181    float sampleTexture(sampler2D textureSampler, vec2 uv) {
182      return `+p.texture2D+`(textureSampler, uv).r;
183    }
184  `}(l),f=function(p){return p.version+`
185    precision highp float;
186    precision highp int;
187    precision highp sampler2D;
188    `+p.varyingFs+` vec2 resultUV;
189    `+p.defineOutput+`
190    const vec2 halfCR = vec2(0.5, 0.5);
191
192    struct ivec5
193    {
194      int x;
195      int y;
196      int z;
197      int w;
198      int u;
199    };
200
201    struct ivec6
202    {
203      int x;
204      int y;
205      int z;
206      int w;
207      int u;
208      int v;
209    };
210
211    uniform float NAN;
212    `+p.defineSpecialNaN+`
213    `+p.defineSpecialInf+`
214    `+p.defineRound+`
215
216    int imod(int x, int y) {
217      return x - y * (x / y);
218    }
219
220    int idiv(int a, int b, float sign) {
221      int res = a / b;
222      int mod = imod(a, b);
223      if (sign < 0. && mod != 0) {
224        res -= 1;
225      }
226      return res;
227    }
228
229    //Based on the work of Dave Hoskins
230    //https://www.shadertoy.com/view/4djSRW
231    #define HASHSCALE1 443.8975
232    float random(float seed){
233      vec2 p = resultUV * seed;
234      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);
235      p3 += dot(p3, p3.yzx + 19.19);
236      return fract((p3.x + p3.y) * p3.z);
237    }
238
239    `+Lh+`
240    `+Wh+`
241    `+Uh+`
242  `}(l);return t.isPacked?(a=function(p,d){switch(p.length){case 0:return`
243    int getOutputCoords() {
244      return 0;
245    }
246  `;case 1:return function(y,w){var C=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];return C[0]===1?`
247      int getOutputCoords() {
248        return 2 * int(resultUV.x * `+C[1]+`.0);
249      }
250    `:C[1]===1?`
251      int getOutputCoords() {
252        return 2 * int(resultUV.y * `+C[0]+`.0);
253      }
254    `:`
255    int getOutputCoords() {
256      ivec2 resTexRC = ivec2(resultUV.yx *
257                             vec2(`+C[0]+", "+C[1]+`));
258      return 2 * (resTexRC.x * `+C[1]+` + resTexRC.y);
259    }
260  `}(0,d);case 2:return function(y,w){var C=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];if(We(y,w))return`
261      ivec2 getOutputCoords() {
262        return 2 * ivec2(resultUV.yx * vec2(`+C[0]+", "+C[1]+`));
263      }
264    `;var S=Math.ceil(y[1]/2);return`
265    ivec2 getOutputCoords() {
266      ivec2 resTexRC = ivec2(resultUV.yx *
267                             vec2(`+C[0]+", "+C[1]+`));
268
269      int index = resTexRC.x * `+C[1]+` + resTexRC.y;
270      int r = 2 * (index / `+S+`);
271      int c = imod(index, `+S+`) * 2;
272
273      return ivec2(r, c);
274    }
275  `}(p,d);case 3:return g=p,v=d,m=[Math.ceil(v[0]/2),Math.ceil(v[1]/2)],x=Math.ceil(g[2]/2),b=x*Math.ceil(g[1]/2),`
276    ivec3 getOutputCoords() {
277      ivec2 resTexRC = ivec2(resultUV.yx *
278                             vec2(`+m[0]+", "+m[1]+`));
279      int index = resTexRC.x * `+m[1]+` + resTexRC.y;
280
281      int b = index / `+b+`;
282      index -= b * `+b+`;
283
284      int r = 2 * (index / `+x+`);
285      int c = imod(index, `+x+`) * 2;
286
287      return ivec3(b, r, c);
288    }
289  `;default:return function(y,w){for(var C=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)],S=Math.ceil(y[y.length-1]/2),k=S*Math.ceil(y[y.length-2]/2),I=k,R="",N="b, r, c",A=2;A<y.length-1;A++)I*=y[y.length-A-1],R=`
290      int b`+A+" = index / "+I+`;
291      index -= b`+A+" * "+I+`;
292    `+R,N="b"+A+", "+N;return`
293    ivec`+y.length+` getOutputCoords() {
294      ivec2 resTexRC = ivec2(resultUV.yx *
295                             vec2(`+C[0]+", "+C[1]+`));
296      int index = resTexRC.x * `+C[1]+` + resTexRC.y;
297
298      `+R+`
299
300      int b = index / `+k+`;
301      index -= b * `+k+`;
302
303      int r = 2 * (index / `+S+`);
304      int c = imod(index, `+S+`) * 2;
305
306      return ivec`+y.length+"("+N+`);
307    }
308  `}(p,d)}var g,v,m,x,b}(t.logicalShape,c),i=function(p){return`
309    void setOutput(vec4 val) {
310      `+p.output+` = val;
311    }
312  `}(l)):(a=function(p,d){switch(p.length){case 0:return`
313    int getOutputCoords() {
314      return 0;
315    }
316  `;case 1:return function(m,x){return x[0]===1?`
317      int getOutputCoords() {
318        return int(resultUV.x * `+x[1]+`.0);
319      }
320    `:x[1]===1?`
321      int getOutputCoords() {
322        return int(resultUV.y * `+x[0]+`.0);
323      }
324    `:`
325    int getOutputCoords() {
326      ivec2 resTexRC = ivec2(resultUV.yx *
327                             vec2(`+x[0]+", "+x[1]+`));
328      return resTexRC.x * `+x[1]+` + resTexRC.y;
329    }
330  `}(0,d);case 2:return function(m,x){return We(m,x)?`
331      ivec2 getOutputCoords() {
332        return ivec2(resultUV.yx * vec2(`+x[0]+", "+x[1]+`));
333      }
334    `:m[1]===1?`
335      ivec2 getOutputCoords() {
336        ivec2 resTexRC = ivec2(resultUV.yx *
337                               vec2(`+x[0]+", "+x[1]+`));
338        int index = resTexRC.x * `+x[1]+` + resTexRC.y;
339        return ivec2(index, 0);
340      }
341    `:m[0]===1?`
342      ivec2 getOutputCoords() {
343        ivec2 resTexRC = ivec2(resultUV.yx *
344                               vec2(`+x[0]+", "+x[1]+`));
345        int index = resTexRC.x * `+x[1]+` + resTexRC.y;
346        return ivec2(0, index);
347      }
348    `:`
349    ivec2 getOutputCoords() {
350      ivec2 resTexRC = ivec2(resultUV.yx *
351                             vec2(`+x[0]+", "+x[1]+`));
352      int index = resTexRC.x * `+x[1]+` + resTexRC.y;
353      int r = index / `+m[1]+`;
354      int c = index - r * `+m[1]+`;
355      return ivec2(r, c);
356    }
357  `}(p,d);case 3:return g=d,v=fn(["r","c","d"],p),`
358    ivec3 getOutputCoords() {
359      ivec2 resTexRC = ivec2(resultUV.yx *
360                             vec2(`+g[0]+", "+g[1]+`));
361      int index = resTexRC.x * `+g[1]+` + resTexRC.y;
362      `+v+`
363      return ivec3(r, c, d);
364    }
365  `;case 4:return function(m,x){var b=fn(["r","c","d","d2"],m);return`
366    ivec4 getOutputCoords() {
367      ivec2 resTexRC = ivec2(resultUV.yx *
368        vec2(`+x[0]+", "+x[1]+`));
369      int index = resTexRC.x * `+x[1]+` + resTexRC.y;
370      `+b+`
371      return ivec4(r, c, d, d2);
372    }
373  `}(p,d);case 5:return function(m,x){var b=fn(["r","c","d","d2","d3"],m);return`
374    ivec5 getOutputCoords() {
375      ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+x[0]+`,
376                             `+x[1]+`));
377
378      int index = resTexRC.x * `+x[1]+` + resTexRC.y;
379
380      `+b+`
381
382      ivec5 outShape = ivec5(r, c, d, d2, d3);
383      return outShape;
384    }
385  `}(p,d);case 6:return function(m,x){var b=fn(["r","c","d","d2","d3","d4"],m);return`
386    ivec6 getOutputCoords() {
387      ivec2 resTexRC = ivec2(resultUV.yx *
388        vec2(`+x[0]+", "+x[1]+`));
389      int index = resTexRC.x * `+x[1]+` + resTexRC.y;
390
391      `+b+`
392
393      ivec6 result = ivec6(r, c, d, d2, d3, d4);
394      return result;
395    }
396  `}(p,d);default:throw new Error(p.length+"-D output sampling is not yet supported")}var g,v}(t.logicalShape,c),i=function(p){return`
397    void setOutput(float val) {
398      `+p.output+` = vec4(val, 0, 0, 0);
399    }
400  `}(l)),n&&(f+=Vh),[f,h,i,s,a,u,e].join(`
401`)}function An(r){var t=r.shapeInfo.logicalShape;switch(t.length){case 0:return function(e){var n=e.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return"float "+o+"() {return "+n+";}";var a=e.shapeInfo.texShape,i=a[0],s=a[1];if(i===1&&s===1)return`
402      float `+o+`() {
403        return sampleTexture(`+n+`, halfCR);
404      }
405    `;var u=e.shapeInfo.texShape,c=u[0],l=u[1],h=un(n);return`
406    float `+o+`() {
407      vec2 uv = uvFromFlat(`+c+", "+l+", "+h+`);
408      return sampleTexture(`+n+`, uv);
409    }
410  `}(r);case 1:return function(e){var n=e.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
411      float `+o+`(int index) {
412        `+Rn(e)+`
413      }
414    `;var a=e.shapeInfo.texShape,i=a[0],s=a[1];if(s===1&&i===1)return`
415      float `+o+`(int index) {
416        return sampleTexture(`+n+`, halfCR);
417      }
418    `;var u=un(n);return s===1?`
419      float `+o+`(int index) {
420        vec2 uv = vec2(0.5, (float(index + `+u+") + 0.5) / "+i+`.0);
421        return sampleTexture(`+n+`, uv);
422      }
423    `:i===1?`
424      float `+o+`(int index) {
425        vec2 uv = vec2((float(index + `+u+") + 0.5) / "+s+`.0, 0.5);
426        return sampleTexture(`+n+`, uv);
427      }
428    `:`
429    float `+o+`(int index) {
430      vec2 uv = uvFromFlat(`+i+", "+s+", index + "+u+`);
431      return sampleTexture(`+n+`, uv);
432    }
433  `}(r);case 2:return function(e){var n=e.shapeInfo.logicalShape,o=e.name,a="get"+o.charAt(0).toUpperCase()+o.slice(1),i=e.shapeInfo.texShape;if(i!=null&&We(n,i)){var s=i[0],u=i[1];return`
434    float `+a+`(int row, int col) {
435      vec2 uv = (vec2(col, row) + halfCR) / vec2(`+u+".0, "+s+`.0);
436      return sampleTexture(`+o+`, uv);
437    }
438  `}var c=hn(n),l=c.newShape,h=c.keptDims,f=l;if(f.length<n.length){var p=Tn(e,f);return`
439      `+An(p)+`
440      float `+a+`(int row, int col) {
441        return `+a+"("+Nn(["row","col"],h)+`);
442      }
443    `}if(e.shapeInfo.isUniform)return`
444      float `+a+`(int row, int col) {
445        int index = round(dot(vec2(row, col), vec2(`+n[1]+`, 1)));
446        `+Rn(e)+`
447      }
448    `;var d=i[0],g=i[1],v=un(o);return g===1?`
449    float `+a+`(int row, int col) {
450      float index = dot(vec3(row, col, `+v+"), vec3("+n[1]+`, 1, 1));
451      vec2 uv = vec2(0.5, (index + 0.5) / `+d+`.0);
452      return sampleTexture(`+o+`, uv);
453    }
454  `:d===1?`
455    float `+a+`(int row, int col) {
456      float index = dot(vec3(row, col, `+v+"), vec3("+n[1]+`, 1, 1));
457      vec2 uv = vec2((index + 0.5) / `+g+`.0, 0.5);
458      return sampleTexture(`+o+`, uv);
459    }
460  `:`
461  float `+a+`(int row, int col) {
462    // Explicitly use integer operations as dot() only works on floats.
463    int index = row * `+n[1]+" + col + "+v+`;
464    vec2 uv = uvFromFlat(`+d+", "+g+`, index);
465    return sampleTexture(`+o+`, uv);
466  }
467`}(r);case 3:return function(e){var n=e.shapeInfo.logicalShape,o=e.name,a="get"+o.charAt(0).toUpperCase()+o.slice(1),i=n[1]*n[2],s=n[2],u=hn(n),c=u.newShape,l=u.keptDims,h=c;if(h.length<n.length){var f=Tn(e,h);return`
468        `+An(f)+`
469        float `+a+`(int row, int col, int depth) {
470          return `+a+"("+Nn(["row","col","depth"],l)+`);
471        }
472      `}if(e.shapeInfo.isUniform)return`
473      float `+a+`(int row, int col, int depth) {
474        int index = round(dot(vec3(row, col, depth),
475                          vec3(`+i+", "+s+`, 1)));
476        `+Rn(e)+`
477      }
478    `;var p=e.shapeInfo.texShape,d=p[0],g=p[1],v=e.shapeInfo.flatOffset;if(g===i&&v==null)return`
479        float `+a+`(int row, int col, int depth) {
480          float texR = float(row);
481          float texC = dot(vec2(col, depth), vec2(`+s+`, 1));
482          vec2 uv = (vec2(texC, texR) + halfCR) /
483                     vec2(`+g+".0, "+d+`.0);
484          return sampleTexture(`+o+`, uv);
485        }
486      `;if(g===s&&v==null)return`
487    float `+a+`(int row, int col, int depth) {
488      float texR = dot(vec2(row, col), vec2(`+n[1]+`, 1));
489      float texC = float(depth);
490      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+g+".0, "+d+`.0);
491      return sampleTexture(`+o+`, uv);
492    }
493  `;var m=un(o);return`
494      float `+a+`(int row, int col, int depth) {
495        // Explicitly use integer operations as dot() only works on floats.
496        int index = row * `+i+" + col * "+s+" + depth + "+m+`;
497        vec2 uv = uvFromFlat(`+d+", "+g+`, index);
498        return sampleTexture(`+o+`, uv);
499      }
500  `}(r);case 4:return function(e){var n=e.shapeInfo.logicalShape,o=e.name,a="get"+o.charAt(0).toUpperCase()+o.slice(1),i=n[3],s=n[2]*i,u=n[1]*s,c=hn(n),l=c.newShape,h=c.keptDims;if(l.length<n.length){var f=Tn(e,l);return`
501      `+An(f)+`
502      float `+a+`(int row, int col, int depth, int depth2) {
503        return `+a+"("+Nn(["row","col","depth","depth2"],h)+`);
504      }
505    `}if(e.shapeInfo.isUniform)return`
506      float `+a+`(int row, int col, int depth, int depth2) {
507        int index = round(dot(vec4(row, col, depth, depth2),
508                          vec4(`+u+", "+s+", "+i+`, 1)));
509        `+Rn(e)+`
510      }
511    `;var p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,g=d[0],v=d[1];if(v===u&&p==null)return`
512      float `+a+`(int row, int col, int depth, int depth2) {
513        float texR = float(row);
514        float texC =
515            dot(vec3(col, depth, depth2),
516                vec3(`+s+", "+i+`, 1));
517        vec2 uv = (vec2(texC, texR) + halfCR) /
518                   vec2(`+v+".0, "+g+`.0);
519        return sampleTexture(`+o+`, uv);
520      }
521    `;if(v===i&&p==null)return`
522      float `+a+`(int row, int col, int depth, int depth2) {
523        float texR = dot(vec3(row, col, depth),
524                         vec3(`+n[1]*n[2]+", "+n[2]+`, 1));
525        float texC = float(depth2);
526        vec2 uv = (vec2(texC, texR) + halfCR) /
527                  vec2(`+v+".0, "+g+`.0);
528        return sampleTexture(`+o+`, uv);
529      }
530    `;var m=un(o);return`
531    float `+a+`(int row, int col, int depth, int depth2) {
532      // Explicitly use integer operations as dot() only works on floats.
533      int index = row * `+u+" + col * "+s+` +
534          depth * `+i+` + depth2;
535      vec2 uv = uvFromFlat(`+g+", "+v+", index + "+m+`);
536      return sampleTexture(`+o+`, uv);
537    }
538  `}(r);case 5:return function(e){var n=e.shapeInfo.logicalShape,o=e.name,a="get"+o.charAt(0).toUpperCase()+o.slice(1),i=n[4],s=n[3]*i,u=n[2]*s,c=n[1]*u,l=hn(n),h=l.newShape,f=l.keptDims;if(h.length<n.length){var p=Tn(e,h);return`
539      `+An(p)+`
540      float `+a+`(int row, int col, int depth, int depth2, int depth3) {
541        return `+a+"("+Nn(["row","col","depth","depth2","depth3"],f)+`);
542      }
543    `}if(e.shapeInfo.isUniform)return`
544      float `+a+`(int row, int col, int depth, int depth2, int depth3) {
545        float index = dot(
546          vec4(row, col, depth, depth2),
547          vec4(`+c+", "+u+", "+s+", "+i+`)) +
548          depth3;
549        `+Rn(e)+`
550      }
551    `;var d=e.shapeInfo.flatOffset,g=e.shapeInfo.texShape,v=g[0],m=g[1];if(m===c&&d==null)return`
552      float `+a+`(int row, int col, int depth, int depth2, int depth3) {
553        int texR = row;
554        float texC = dot(vec4(col, depth, depth2, depth3),
555                         vec4(`+u+", "+s+", "+i+`, 1));
556        vec2 uv = (vec2(texC, texR) + halfCR) /
557                   vec2(`+m+".0, "+v+`.0);
558        return sampleTexture(`+o+`, uv);
559      }
560    `;if(m===i&&d==null)return`
561      float `+a+`(int row, int col, int depth, int depth2, int depth3) {
562        float texR = dot(
563          vec4(row, col, depth, depth2),
564          vec4(`+n[1]*n[2]*n[3]+`,
565               `+n[2]*n[3]+", "+n[3]+`, 1));
566        int texC = depth3;
567        vec2 uv = (vec2(texC, texR) + halfCR) /
568                  vec2(`+m+".0, "+v+`.0);
569        return sampleTexture(`+o+`, uv);
570      }
571    `;var x=un(o);return`
572    float `+a+`(int row, int col, int depth, int depth2, int depth3) {
573      // Explicitly use integer operations as dot() only works on floats.
574      int index = row * `+c+" + col * "+u+" + depth * "+s+` +
575          depth2 * `+i+" + depth3 + "+x+`;
576      vec2 uv = uvFromFlat(`+v+", "+m+`, index);
577      return sampleTexture(`+o+`, uv);
578    }
579  `}(r);case 6:return function(e){var n=e.shapeInfo.logicalShape,o=e.name,a="get"+o.charAt(0).toUpperCase()+o.slice(1),i=hn(n),s=i.newShape,u=i.keptDims;if(s.length<n.length){var c=Tn(e,s);return`
580      `+An(c)+`
581      float `+a+`(int row, int col, int depth,
582                    int depth2, int depth3, int depth4) {
583        return `+a+"("+Nn(["row","col","depth","depth2","depth3","depth4"],u)+`);
584      }
585    `}var l=n[5],h=n[4]*l,f=n[3]*h,p=n[2]*f,d=n[1]*p;if(e.shapeInfo.isUniform)return`
586      float `+a+`(int row, int col, int depth,
587                  int depth2, int depth3, int depth4) {
588        int index = round(dot(
589          vec4(row, col, depth, depth2),
590          vec4(`+d+", "+p+", "+f+", "+h+`)) +
591          dot(
592            vec2(depth3, depth4),
593            vec2(`+l+`, 1)));
594        `+Rn(e)+`
595      }
596    `;var g=e.shapeInfo.flatOffset,v=e.shapeInfo.texShape,m=v[0],x=v[1];if(x===d&&g==null)return`
597      float `+a+`(int row, int col, int depth,
598                    int depth2, int depth3, int depth4) {
599        int texR = row;
600        float texC = dot(vec4(col, depth, depth2, depth3),
601          vec4(`+p+", "+f+", "+h+", "+l+`)) +
602               float(depth4);
603        vec2 uv = (vec2(texC, texR) + halfCR) /
604                   vec2(`+x+".0, "+m+`.0);
605        return sampleTexture(`+o+`, uv);
606      }
607    `;if(x===l&&g==null)return`
608      float `+a+`(int row, int col, int depth,
609                    int depth2, int depth3, int depth4) {
610        float texR = dot(vec4(row, col, depth, depth2),
611          vec4(`+n[1]*n[2]*n[3]*n[4]+`,
612               `+n[2]*n[3]*n[4]+`,
613               `+n[3]*n[4]+`,
614               `+n[4]+`)) + float(depth3);
615        int texC = depth4;
616        vec2 uv = (vec2(texC, texR) + halfCR) /
617                  vec2(`+x+".0, "+m+`.0);
618        return sampleTexture(`+o+`, uv);
619      }
620    `;var b=un(o);return`
621    float `+a+`(int row, int col, int depth,
622                  int depth2, int depth3, int depth4) {
623      // Explicitly use integer operations as dot() only works on floats.
624      int index = row * `+d+" + col * "+p+" + depth * "+f+` +
625          depth2 * `+h+" + depth3 * "+l+" + depth4 + "+b+`;
626      vec2 uv = uvFromFlat(`+m+", "+x+`, index);
627      return sampleTexture(`+o+`, uv);
628    }
629  `}(r);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function cu(r){var t,e,n;switch(r.shapeInfo.logicalShape.length){case 0:return t=r.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),n=je(),`
630    vec4 `+e+`() {
631      return `+n.texture2D+"("+t+`, halfCR);
632    }
633  `;case 1:return function(o){var a=o.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),s=o.shapeInfo.texShape,u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],c=je();return`
634    vec4 `+i+`(int index) {
635      vec2 uv = packedUVfrom1D(
636        `+u[0]+", "+u[1]+`, index);
637      return `+c.texture2D+"("+a+`, uv);
638    }
639  `}(r);case 2:return function(o){var a=o.shapeInfo.logicalShape,i=o.name,s="get"+i.charAt(0).toUpperCase()+i.slice(1),u=o.shapeInfo.texShape,c=u[0],l=u[1],h=je();if(u!=null&&We(a,u))return`
640      vec4 `+s+`(int row, int col) {
641        vec2 uv = (vec2(col, row) + halfCR) / vec2(`+l+".0, "+c+`.0);
642
643        return `+h.texture2D+"("+i+`, uv);
644      }
645    `;var f=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)],p=Math.ceil(a[1]/2);return`
646    vec4 `+s+`(int row, int col) {
647      vec2 uv = packedUVfrom2D(`+p+", "+f[0]+", "+f[1]+`, row, col);
648      return `+h.texture2D+"("+i+`, uv);
649    }
650  `}(r);case 3:return function(o){var a=o.shapeInfo.logicalShape,i=o.name,s="get"+i.charAt(0).toUpperCase()+i.slice(1),u=o.shapeInfo.texShape,c=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)];if(a[0]===1){var l=a.slice(1),h=Tn(o,l);return`
651        `+cu(h)+`
652        vec4 `+s+`(int b, int row, int col) {
653          return `+s+"("+Nn(["b","row","col"],[1,2])+`);
654        }
655      `}var f=c[0],p=c[1],d=Math.ceil(a[2]/2),g=d*Math.ceil(a[1]/2),v=je();return`
656    vec4 `+s+`(int b, int row, int col) {
657      vec2 uv = packedUVfrom3D(
658        `+f+", "+p+", "+g+", "+d+`, b, row, col);
659      return `+v.texture2D+"("+i+`, uv);
660    }
661  `}(r);default:return function(o){for(var a=o.shapeInfo.logicalShape,i=a.length,s=o.name,u="get"+s.charAt(0).toUpperCase()+s.slice(1),c=o.shapeInfo.texShape,l=[Math.ceil(c[0]/2),Math.ceil(c[1]/2)],h=l[0],f=l[1],p=Math.ceil(a[i-1]/2),d=p*Math.ceil(a[i-2]/2),g="int b, int row, int col",v="b * "+d+" + (row / 2) * "+p+" + (col / 2)",m=2;m<i-1;m++)g="int b"+m+", "+g,d*=a[i-m-1],v="b"+m+" * "+d+" + "+v;var x=je();return`
662    vec4 `+u+"("+g+`) {
663      int index = `+v+`;
664      int texR = index / `+f+`;
665      int texC = index - texR * `+f+`;
666      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+f+", "+h+`);
667      return `+x.texture2D+"("+s+`, uv);
668    }
669  `}(r)}}var Lh=`
670vec2 uvFromFlat(int texNumR, int texNumC, int index) {
671  int texR = index / texNumC;
672  int texC = index - texR * texNumC;
673  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
674}
675vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
676  int texelIndex = index / 2;
677  int texR = texelIndex / texNumC;
678  int texC = texelIndex - texR * texNumC;
679  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
680}
681`,Wh=`
682vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
683  int texNumC, int row, int col) {
684  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
685  int texR = texelIndex / texNumC;
686  int texC = texelIndex - texR * texNumC;
687  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
688}
689`,Uh=`
690vec2 packedUVfrom3D(int texNumR, int texNumC,
691    int texelsInBatch, int texelsInLogicalRow, int b,
692    int row, int col) {
693  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
694  int texR = index / texNumC;
695  int texC = index - texR * texNumC;
696  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
697}
698`,Vh=`
699  float getChannel(vec4 frag, vec2 innerDims) {
700    vec2 modCoord = mod(innerDims, 2.);
701    return modCoord.x == 0. ?
702      (modCoord.y == 0. ? frag.r : frag.g) :
703      (modCoord.y == 0. ? frag.b : frag.a);
704  }
705  float getChannel(vec4 frag, int dim) {
706    float modCoord = mod(float(dim), 2.);
707    return modCoord == 0. ? frag.r : frag.g;
708  }
709`;function un(r){return"offset"+r}function Rn(r){var t=r.name,e=Y(r.shapeInfo.logicalShape);return e<2?"return "+t+";":`
710    for (int i = 0; i < `+e+`; i++) {
711      if (i == index) {
712        return `+t+`[i];
713      }
714    }
715  `}function be(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error("GPU for rank "+r+" is not yet supported")}function Tn(r,t){var e=JSON.parse(JSON.stringify(r));return e.shapeInfo.logicalShape=t,e}function Nn(r,t){return t.map(function(e){return r[e]}).join(", ")}var zh=function(r,t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,E(r.length>2,function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only input
715s with rank above 2."});var o=r[r.length-1],a=Math.ceil(o/t);this.outputShape=r.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=be(c),h=Qe("coords",c);if(a===1){var f=be(s=c+1);i=`
716        `+f+" sourceLocR = "+f+"("+h.join()+`, 0);
717        ++`+h[c-1]+`;
718        `+f+" sourceLocG = "+f+"("+h.join()+`, 0);
719        ++`+h[c-2]+`;
720        `+f+" sourceLocA = "+f+"("+h.join()+`, 0);
721        --`+h[c-1]+`;
722        `+f+" sourceLocB = "+f+"("+h.join()+`, 0);
723        --`+h[c-2]+";"}else s=c,i=`
724        `+l+` sourceLocR = coords;
725        ++`+h[c-1]+`;
726        `+l+` sourceLocG = coords;
727        ++`+h[c-2]+`;
728        `+l+` sourceLocA = coords;
729        --`+h[c-1]+`;
730        `+l+` sourceLocB = coords;
731        --`+h[c-2]+";";var p=["x","y","z","w","u","v"].slice(0,s),d="."+p[s-1],g=p.map(function(k){return"int "+k}),v=Qe("sourceLocR",s-1).concat("inIdx.r"),m=Qe("sourceLocG",s-1).concat("inIdx.g"),x=Qe("sourceLocB",s-1).concat("inIdx.b"),b=Qe("sourceLocA",s-1).concat("inIdx.a"),y=e==="max"?"greaterThan":"lessThan",w=n?"":`
732          inIdx = round(vec4(getBestIndicesAChannel(`+v.join()+`),
733                             getBestIndicesAChannel(`+m.join()+`),
734                             getBestIndicesAChannel(`+x.join()+`),
735                             getBestIndicesAChannel(`+b.join()+")));",C=`vec4(
736            getAChannel(`+v.join()+`),
737            hasNextCol ? getAChannel(`+m.join()+`) : 0.,
738            hasNextRow ? getAChannel(`+x.join()+`) : 0.,
739            hasNextRow && hasNextCol ? getAChannel(`+b.join()+") : 0.)",S=n?"":`
740      float getBestIndicesAChannel(`+g.join()+`) {
741        return getChannel(getBestIndicesA(`+p.join()+`),
742                                          vec2(`+p.slice(-2).join()+`));
743      }`;this.userCode=`
744      float getAChannel(`+g.join()+`) {
745        return getChannel(getA(`+p.join()+`),
746                               vec2(`+p.slice(-2).join()+`));
747      }
748      `+S+`
749      void main() {
750        `+l+` coords = getOutputCoords();
751        bool hasNextCol = `+h[c-1]+" < "+(u[c-1]-1)+`;
752        bool hasNextRow = `+h[c-2]+" < "+(u[c-2]-1)+`;
753        `+i+`
754        ivec4 srcIdx = ivec4(sourceLocR`+d+", sourceLocG"+d+`,
755          sourceLocB`+d+", sourceLocA"+d+") * "+t+`;
756        ivec4 inIdx = srcIdx;
757        vec4 bestIndex = vec4(inIdx);
758        vec4 bestValue = `+C+`;
759
760        for (int i = 0; i < `+t+`; i++) {
761          inIdx = srcIdx;
762          `+w+`
763          vec4 candidate = `+C+`;
764          bvec4 nan = isnan(candidate);
765          bvec4 replace = bvec4(
766            vec4(`+y+`(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
767
768          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,
769                           replace.y  ? candidate.y : bestValue.y,
770                           replace.z  ? candidate.z : bestValue.z,
771                           replace.w  ? candidate.w : bestValue.w);
772          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
773          srcIdx++;
774        }
775        setOutput(bestIndex);
776      }
777    `},Gh=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterHeight,u=r.effectiveFilterWidth,c=s-1-r.padInfo.top,l=u-1-r.padInfo.left,h=1/(t*e);this.userCode=`
778      const ivec2 pads = ivec2(`+c+", "+l+`);
779      const float avgMultiplier = float(`+h+`);
780
781      void main() {
782        ivec4 coords = getOutputCoords();
783        int b = coords[0];
784        int d = coords[3];
785
786        ivec2 dyRCCorner = coords.yz - pads;
787        int dyRCorner = dyRCCorner.x;
788        int dyCCorner = dyRCCorner.y;
789
790        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
791        // ? = to be determined. : = across all values in that axis.
792        float dotProd = 0.0;
793        for (int wR = 0; wR < `+s+`;
794            wR += `+a+`) {
795          float dyR = float(dyRCorner + wR) / `+n+`.0;
796
797          if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
798            continue;
799          }
800          int idyR = int(dyR);
801
802          for (int wC = 0; wC < `+u+`;
803            wC+= `+i+`) {
804            float dyC = float(dyCCorner + wC) / `+o+`.0;
805
806            if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
807                fract(dyC) > 0.0) {
808              continue;
809            }
810            int idyC = int(dyC);
811
812            float dyValue = getDy(b, idyR, idyC, d);
813
814            dotProd += dyValue * avgMultiplier;
815          }
816        }
817        setOutput(dotProd);
818      }
819    `},Hh=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,p=l-1-r.padInfo.front,d=h-1-r.padInfo.top,g=f-1-r.padInfo.left,v=1/(t*e*n);this.userCode=`
820      const ivec3 pads = ivec3(`+p+", "+d+", "+g+`);
821      const float avgMultiplier = float(`+v+`);
822
823      void main() {
824        ivec5 coords = getOutputCoords();
825        int batch = coords.x;
826        int ch = coords.u;
827
828        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
829        int dyDCorner = dyCorner.x;
830        int dyRCorner = dyCorner.y;
831        int dyCCorner = dyCorner.z;
832
833        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
834        // dx(xD, xR, xC, ch).
835        // ? = to be determined. : = across all values in that axis.
836        float dotProd = 0.0;
837
838        for (int wD = 0; wD < `+l+`;
839            wD += `+s+`) {
840          float dyD = float(dyDCorner + wD) / `+o+`.0;
841
842          if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) {
843            continue;
844          }
845          int idyD = int(dyD);
846
847          for (int wR = 0; wR < `+h+`;
848              wR += `+u+`) {
849            float dyR = float(dyRCorner + wR) / `+a+`.0;
850
851            if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
852                fract(dyR) > 0.0) {
853              continue;
854            }
855            int idyR = int(dyR);
856
857            for (int wC = 0; wC < `+f+`;
858                wC += `+c+`) {
859              float dyC = float(dyCCorner + wC) / `+i+`.0;
860
861              if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
862                  fract(dyC) > 0.0) {
863                continue;
864              }
865              int idyC = int(dyC);
866
867              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
868
869              dotProd += dyValue * avgMultiplier;
870            }
871          }
872        }
873        setOutput(dotProd);
874      }
875    `},qh=function(r,t,e,n,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],le(r,t),le(r,e);var i="0.0";n!=null&&(le(r,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";o!=null&&(le(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=`
876      void main() {
877        float x = getXAtOutCoords();
878        float mean = getMeanAtOutCoords();
879        float variance = getVarianceAtOutCoords();
880        float offset = `+i+`;
881        float scale = `+s+`;
882        float inv = scale * inversesqrt(variance + float(`+a+`));
883        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
884      }
885    `},jh=function(r,t,e,n,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],le(r,t),le(r,e);var i="vec4(0.0)";n!=null&&(le(r,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";o!=null&&(le(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=`
886      void main() {
887        vec4 offset = `+i+`;
888        vec4 scale = `+s+`;
889
890        vec4 x = getXAtOutCoords();
891        vec4 mean = getMeanAtOutCoords();
892        vec4 variance = getVarianceAtOutCoords();
893
894        vec4 inv = scale * inversesqrt(variance + vec4(`+a+`));
895
896        setOutput((x - mean) * inv + offset);
897      }
898    `},Kh="return areal * breal - aimag * bimag;",Xh="return areal * bimag + aimag * breal;",Bi=function(r,t,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=le(t,e),this.userCode=`
899      float binaryOpComplex(
900          float areal, float aimag, float breal, float bimag) {
901        `+r+`
902      }
903
904      void main() {
905        float areal = getARealAtOutCoords();
906        float aimag = getAImagAtOutCoords();
907        float breal = getBRealAtOutCoords();
908        float bimag = getBImagAtOutCoords();
909        setOutput(binaryOpComplex(areal, aimag, breal, bimag));
910      }
911    `},Fo="return a + b;",Po="return a - b;",Li="return a * b;",lu="return (a < 0.) ? b * a : a;",Se=function(r,t,e){this.variableNames=["A","B"],this.outputShape=le(t,e),this.userCode=`
912      float binaryOperation(float a, float b) {
913        `+r+`
914      }
915
916      void main() {
917        float a = getAAtOutCoords();
918        float b = getBAtOutCoords();
919        setOutput(binaryOperation(a, b));
920      }
921    `},hu=`
922  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
923  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
924`,Ut=function(r,t,e,n){n===void 0&&(n=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=le(t,e);var o=this.outputShape.length,a="";if(n)if(o===0||Y(this.outputShape)===1)a=`
925          result.y = 0.;
926          result.z = 0.;
927          result.w = 0.;
928        `;else if(a=`
929          `+be(o)+` coords = getOutputCoords();
930        `,o===1)a+=`
931            result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
932            result.z = 0.;
933            result.w = 0.;
934          `;else{var i=Qe("coords",o);a+=`
935            bool nextRowOutOfBounds =
936              (`+i[o-2]+" + 1) >= "+this.outputShape[o-2]+`;
937            bool nextColOutOfBounds =
938              (`+i[o-1]+" + 1) >= "+this.outputShape[o-1]+`;
939            result.y = nextColOutOfBounds ? 0. : result.y;
940            result.z = nextRowOutOfBounds ? 0. : result.z;
941            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
942          `}this.userCode=`
943      vec4 binaryOperation(vec4 a, vec4 b) {
944        `+r+`
945      }
946
947      void main() {
948        vec4 a = getAAtOutCoords();
949        vec4 b = getBAtOutCoords();
950
951        vec4 result = binaryOperation(a, b);
952        `+a+`
953
954        setOutput(result);
955      }
956    `},$h=function(){function r(t){this.variableNames=["A"],this.outputShape=t,this.userCode=`
957      uniform float minVal;
958      uniform float maxVal;
959
960      void main() {
961        float value = getAAtOutCoords();
962        if (isnan(value)) {
963          setOutput(value);
964          return;
965        }
966
967        setOutput(clamp(value, minVal, maxVal));
968      }
969    `}return r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,a){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r}(),Yh=function(){function r(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=`
970      uniform float minVal;
971      uniform float maxVal;
972
973      void main() {
974        vec4 value = getAAtOutCoords();
975
976        if (any(isnan(value))) {
977          setOutput(value);
978          return;
979        }
980
981        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
982      }
983    `}return r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,a){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r}(),Jh=function(r){this.variableNames=["real","imag"],this.outputShape=r,this.userCode=`
984      void main() {
985        float re = abs(getRealAtOutCoords());
986        float im = abs(getImagAtOutCoords());
987        float mx = max(re, im);
988
989        // sadly the length function in glsl is not underflow-safe
990        // (at least not on Intel GPUs). So the safe solution is
991        // to ensure underflow-safety in all cases.
992        setOutput(
993          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
994        );
995      }
996    `},Qh=function(r){this.outputShape=[],this.outputShape=Hn(r,1),this.variableNames=r.map(function(s,u){return"T"+u});var t=new Array(r.length-1);t[0]=r[0][1];for(var e=1;e<t.length;e++)t[e]=t[e-1]+r[e][1];var n=["if (yC < "+t[0]+") setOutput(getT0(yR, yC));"];for(e=1;e<t.length;e++){var o=t[e-1];n.push("else if (yC < "+t[e]+") setOutput(getT"+e+"(yR, yC-"+o+"));")}var a=t.length,i=t[t.length-1];n.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode=`
997      void main() {
998        ivec2 coords = getOutputCoords();
999        int yR = coords.x;
1000        int yC = coords.y;
1001
1002        `+n.join(`
1003        `)+`
1004      }
1005    `},Zh=function(r,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Hn(r,t);var e=this.outputShape,n=e.length,o=be(n),a=Qe("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=r.map(function(v,m){return"T"+m});var s=new Array(r.length-1);s[0]=r[0][t];for(var u=1;u<s.length;u++)s[u]=s[u-1]+r[u][t];var c=i[t],l=i.slice(-2),h=i.join(),f="if ("+c+" < "+s[0]+`) {
1006        return getChannel(
1007            getT0(`+h+"), vec2("+l.join()+`));
1008        }`;for(u=1;u<s.length;u++){var p=s[u-1];f+=`
1009        if (`+c+" < "+s[u]+"  && "+c+" >
1009= "+s[u-1]+`) {
1010          return getChannel(
1011            getT`+u+"("+Cr(i,c,p)+`),
1012            vec2(`+Cr(l,c,p)+`));
1013        }`}var d=s.length,g=s[s.length-1];f+=`
1014        return getChannel(
1015          getT`+d+"("+Cr(i,c,g)+`),
1016          vec2(`+Cr(l,c,g)+"));",this.userCode=`
1017      float getValue(`+i.map(function(v){return"int "+v})+`) {
1018        `+f+`
1019      }
1020
1021      void main() {
1022        `+o+` coords = getOutputCoords();
1023        vec4 result = vec4(getValue(`+a+`), 0., 0., 0.);
1024
1025        `+a[n-1]+" = "+a[n-1]+` + 1;
1026        if (`+a[n-1]+" < "+e[n-1]+`) {
1027          result.g = getValue(`+a+`);
1028        }
1029
1030        `+a[n-2]+" = "+a[n-2]+` + 1;
1031        if (`+a[n-2]+" < "+e[n-2]+`) {
1032          result.a = getValue(`+a+`);
1033        }
1034
1035        `+a[n-1]+" = "+a[n-1]+` - 1;
1036        if (`+a[n-2]+" < "+e[n-2]+` &&
1037            `+a[n-1]+" < "+e[n-1]+`) {
1038          result.b = getValue(`+a+`);
1039        }
1040        setOutput(result);
1041      }
1042    `};function Cr(r,t,e){var n=r.indexOf(t);return r.map(function(o,a){return a===n?o+" - "+e:o}).join()}var ef=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,a=r.dataFormat==="channelsLast";this.userCode=`
1043      void main() {
1044        ivec4 coords = getOutputCoords();
1045        int wR = coords.x;
1046        int wC = coords.y;
1047        int d1 = coords.z;
1048        int d2 = coords.w;
1049
1050        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
1051        // ? = to be determined. : = across all values in that axis.
1052        float dotProd = 0.0;
1053
1054        for (int b = 0; b < `+r.batchSize+`; b++) {
1055          for (int yR = 0; yR < `+r.outHeight+`; yR++) {
1056            int xR = wR + yR * `+t+" - "+n+`;
1057
1058            if (xR < 0 || xR >= `+r.inHeight+`) {
1059              continue;
1060            }
1061
1062            for (int yC = 0; yC < `+r.outWidth+`; yC++) {
1063              int xC = wC + yC * `+e+" - "+o+`;
1064
1065              if (xC < 0 || xC >= `+r.inWidth+`) {
1066                continue;
1067              }
1068
1069              if (`+a+`) {
1070                float dyValue = getDy(b, yR, yC, d2);
1071                float xValue = getX(b, xR, xC, d1);
1072                dotProd += (xValue * dyValue);
1073              } else {
1074                float dyValue = getDy(b, d2, yR, yC);
1075                float xValue = getX(b, d1, xR, xC);
1076                dotProd += (xValue * dyValue);
1077              }
1078
1079            }
1080          }
1081        }
1082        setOutput(dotProd);
1083      }
1084    `},tf=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=r.dataFormat==="channelsLast",i=t-1-r.padInfo.top,s=e-1-r.padInfo.left,u=a?1:2,c=a?2:3,l=a?3:1;this.userCode=`
1085      const ivec2 pads = ivec2(`+i+", "+s+`);
1086
1087      void main() {
1088        ivec4 coords = getOutputCoords();
1089        int batch = coords[0];
1090        int d1 = coords[`+l+`];
1091
1092        ivec2 dyCorner = ivec2(coords[`+u+"], coords["+c+`]) - pads;
1093        int dyRCorner = dyCorner.x;
1094        int dyCCorner = dyCorner.y;
1095
1096        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
1097        // ? = to be determined. : = across all values in that axis.
1098        float dotProd = 0.0;
1099        for (int wR = 0; wR < `+t+`; wR++) {
1100          float dyR = float(dyRCorner + wR) / `+n+`.0;
1101
1102          if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
1103            continue;
1104          }
1105          int idyR = int(dyR);
1106
1107          int wRPerm = `+t+` - 1 - wR;
1108
1109          for (int wC = 0; wC < `+e+`; wC++) {
1110            float dyC = float(dyCCorner + wC) / `+o+`.0;
1111
1112            if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
1113                fract(dyC) > 0.0) {
1114              continue;
1115            }
1116            int idyC = int(dyC);
1117
1118            int wCPerm = `+e+` - 1 - wC;
1119
1120            for (int d2 = 0; d2 < `+r.outChannels+`; d2++) {
1121
1122              if (`+a+`) {
1123                float xValue = getDy(batch, idyR, idyC, d2);
1124                float wValue = getW(wRPerm, wCPerm, d1, d2);
1125                dotProd += xValue * wValue;
1126              } else {
1127                float xValue = getDy(batch, d2, idyR, idyC);
1128                float wValue = getW(wRPerm, wCPerm, d1, d2);
1129                dotProd += xValue * wValue;
1130              }
1131
1132            }
1133          }
1134        }
1135        setOutput(dotProd);
1136      }
1137    `},nf=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.padInfo.front,a=r.padInfo.top,i=r.padInfo.left;this.userCode=`
1138      void main() {
1139        ivec5 coords = getOutputCoords();
1140        int wF = coords.x;
1141        int wR = coords.y;
1142        int wC = coords.z;
1143        int d1 = coords.w;
1144        int d2 = coords.u;
1145
1146        float dotProd = 0.0;
1147
1148        for (int b = 0; b < `+r.batchSize+`; b++) {
1149          for (int yF = 0; yF < `+r.outDepth+`; yF++) {
1150            int xF = wF + yF * `+t+" - "+o+`;
1151
1152            if (xF < 0 || xF >= `+r.inDepth+`) {
1153              continue;
1154            }
1155
1156            for (int yR = 0; yR < `+r.outHeight+`; yR++) {
1157              int xR = wR + yR * `+e+" - "+a+`;
1158
1159              if (xR < 0 || xR >= `+r.inHeight+`) {
1160                continue;
1161              }
1162
1163              for (int yC = 0; yC < `+r.outWidth+`; yC++) {
1164                int xC = wC + yC * `+n+" - "+i+`;
1165
1166                if (xC < 0 || xC >= `+r.inWidth+`) {
1167                  continue;
1168                }
1169
1170                float dyValue = getDy(b, yF, yR, yC, d2);
1171                float xValue = getX(b, xF, xR, xC, d1);
1172                dotProd += (xValue * dyValue);
1173              }
1174            }
1175          }
1176        }
1177        setOutput(dotProd);
1178      }
1179    `},rf=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=t-1-r.padInfo.front,u=e-1-r.padInfo.top,c=n-1-r.padInfo.left;this.userCode=`
1180      const ivec3 pads = ivec3(`+s+", "+u+", "+c+`);
1181
1182      void main() {
1183        ivec5 coords = getOutputCoords();
1184        int batch = coords.x;
1185        int d1 = coords.u;
1186
1187
1188        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
1189        int dyFCorner = dyCorner.x;
1190        int dyRCorner = dyCorner.y;
1191        int dyCCorner = dyCorner.z;
1192
1193        float dotProd = 0.0;
1194        for (int wF = 0; wF < `+t+`; wF++) {
1195          float dyF = float(dyFCorner + wF) / `+o+`.0;
1196
1197          if (dyF < 0.0 || dyF >= `+r.outDepth+`.0 || fract(dyF) > 0.0) {
1198            continue;
1199          }
1200          int idyF = int(dyF);
1201
1202          int wFPerm = `+t+` - 1 - wF;
1203
1204          for (int wR = 0; wR < `+e+`; wR++) {
1205            float dyR = float(dyRCorner + wR) / `+a+`.0;
1206
1207            if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
1208              fract(dyR) > 0.0) {
1209              continue;
1210            }
1211            int idyR = int(dyR);
1212
1213            int wRPerm = `+e+` - 1 - wR;
1214
1215            for (int wC = 0; wC < `+n+`; wC++) {
1216              float dyC = float(dyCCorner + wC) / `+i+`.0;
1217
1218              if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
1219                  fract(dyC) > 0.0) {
1220                continue;
1221              }
1222              int idyC = int(dyC);
1223
1224              int wCPerm = `+n+` - 1 - wC;
1225
1226              for (int d2 = 0; d2 < `+r.outChannels+`; d2++) {
1227                float xValue = getDy(batch, idyF, idyR, idyC, d2);
1228                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
1229                dotProd += xValue * wValue;
1230              }
1231            }
1232          }
1233        }
1234        setOutput(dotProd);
1235      }
1236    `},of=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,a=r.outChannels/r.inChannels;this.userCode=`
1237      void main() {
1238        ivec4 coords = getOutputCoords();
1239        int wR = coords.x;
1240        int wC = coords.y;
1241        int d1 = coords.z;
1242        int dm = coords.w;
1243        int d2 = d1 * `+a+` + dm;
1244
1245        float dotProd = 0.0;
1246
1247        // TO DO: Vec4 over the batch size
1248        for (int b = 0; b < `+r.batchSize+`; b++) {
1249          for (int yR = 0; yR < `+r.outHeight+`; yR++) {
1250            int xR = wR + yR * `+t+" - "+n+`;
1251
1252            if (xR < 0 || xR >= `+r.inHeight+`) {
1253              continue;
1254            }
1255
1256            for (int yC = 0; yC < `+r.outWidth+`; yC++) {
1257              int xC = wC + yC * `+e+" - "+o+`;
1258
1259              if (xC < 0 || xC >= `+r.inWidth+`) {
1260                continue;
1261              }
1262
1263              float dyValue = getDy(b, yR, yC, d2);
1264              float xValue = getX(b, xR, xC, d1);
1265              dotProd += (xValue * dyValue);
1266            }
1267          }
1268        }
1269        setOutput(dotProd);
1270      }
1271    `},af=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=t-1-r.padInfo.top,i=e-1-r.padInfo.left,s=r.outChannels/r.inChannels;this.userCode=`
1272      const ivec2 pads = ivec2(`+a+", "+i+`);
1273
1274      void main() {
1275        ivec4 coords = getOutputCoords();
1276        int batch = coords[0];
1277        int d1 = coords[3];
1278        ivec2 dyCorner = coords.yz - pads;
1279        int dyRCorner = dyCorner.x;
1280        int dyCCorner = dyCorner.y;
1281
1282        float dotProd = 0.0;
1283
1284        for (int wR = 0; wR < `+t+`; wR++) {
1285          float dyR = float(dyRCorner + wR) / `+n+`.0;
1286
1287          if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
1288            continue;
1289          }
1290          int idyR = int(dyR);
1291
1292          int wRPerm = `+t+` - 1 - wR;
1293
1294          for (int wC = 0; wC < `+e+`; wC++) {
1295            float dyC = float(dyCCorner + wC) / `+o+`.0;
1296
1297            if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
1298                fract(dyC) > 0.0) {
1299              continue;
1300            }
1301            int idyC = int(dyC);
1302
1303            int wCPerm = `+e+` - 1 - wC;
1304
1305            // TO DO: Vec4 over the channelMul
1306            for (int dm = 0; dm < `+s+`; dm++) {
1307              int d2 = d1 * `+s+` + dm;
1308              float xValue = getDy(batch, idyR, idyC, d2);
1309              float wValue = getW(wRPerm, wCPerm, d1, dm);
1310              dotProd += xValue * wValue;
1311            }
1312          }
1313        }
1314        setOutput(dotProd);
1315      }
1316    `},Wi=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.padInfo.top,a=r.padInfo.left,i=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterHeight,h=r.filterWidth,f=4*Math.floor(r.inChannels/4),p=r.inChannels%4,d=r.dataFormat==="channelsLast",g=d?1:2,v=d?2:3,m=d?3:1,x="",b="";e&&(x=n?`float activation(float a) {
1317          float b = getPreluActivationWeightsAtOutCoords();
1318          `+e+`
1319        }`:`
1320          float activation(float x) {
1321            `+e+`
1322          }
1323        `,b="result = activation(result);");var y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
1324      `+x+`
1325
1326      const ivec2 strides = ivec2(`+i+", "+s+`);
1327      const ivec2 pads = ivec2(`+o+", "+a+`);
1328
1329      void main() {
1330        ivec4 coords = getOutputCoords();
1331        int batch = coords[0];
1332        int d2 = coords[`+m+`];
1333
1334        ivec2 xRCCorner =
1335            ivec2(coords[`+g+"], coords["+v+`]) * strides - pads;
1336        int xRCorner = xRCCorner.x;
1337        int xCCorner = xRCCorner.y;
1338
1339        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
1340        // ? = to be determined. : = across all values in that axis.
1341        float dotProd = 0.0;
1342        for (int wR = 0; wR < `+l+`; wR++) {
1343          int xR = xRCorner + wR * `+u+`;
1344
1345          if (xR < 0 || xR >= `+r.inHeight+`) {
1346            continue;
1347          }
1348
1349          for (int wC = 0; wC < `+h+`; wC++) {
1350            int xC = xCCorner + wC * `+c+`;
1351
1352            if (xC < 0 || xC >= `+r.inWidth+`) {
1353              continue;
1354            }
1355
1356            for (int d1 = 0; d1 < `+f+`; d1 += 4) {
1357              vec4 wValues = vec4(
1358                getW(wR, wC, d1, d2),
1359                getW(wR, wC, d1 + 1, d2),
1360                getW(wR, wC, d1 + 2, d2),
1361                getW(wR, wC, d1 + 3, d2)
1362              );
1363
1364              if (`+d+`) {
1365                vec4 xValues = vec4(
1366                  getX(batch, xR, xC, d1),
1367                  getX(batch, xR, xC, d1 + 1),
1368                  getX(batch, xR, xC, d1 + 2),
1369                  getX(batch, xR, xC, d1 + 3)
1370                );
1371                dotProd += dot(xValues, wValues);
1372              } else {
1373                vec4 xValues = vec4(
1374                  getX(batch, d1, xR, xC),
1375                  getX(batch, d1 + 1, xR, xC),
1376                  getX(batch, d1 + 2, xR, xC),
1377                  getX(batch, d1 + 3, xR, xC)
1378                );
1379                dotProd += dot(xValues, wValues);
1380              }
1381            }
1382
1383            if (`+(p===1)+`) {
1384
1385              if (`+d+`) {
1386                dotProd +=
1387                    getX(batch, xR, xC, `+f+`) *
1388                    getW(wR, wC, `+f+`, d2);
1389              } else {
1390                dotProd +=
1391                    getX(batch, `+f+`, xR, xC) *
1392                    getW(wR, wC, `+f+`, d2);
1393              }
1394
1395            } else if (`+(p===2)+`) {
1396              vec2 wValues = vec2(
1397                getW(wR, wC, `+f+`, d2),
1398                getW(wR, wC, `+f+` + 1, d2)
1399              );
1400
1401              if (`+d+`) {
1402                vec2 xValues = vec2(
1403                  getX(batch, xR, xC, `+f+`),
1404                  getX(batch, xR, xC, `+f+` + 1)
1405                );
1406                dotProd += dot(xValues, wValues);
1407              } else {
1408                vec2 xValues = vec2(
1409                  getX(batch, `+f+`, xR, xC),
1410                  getX(batch, `+f+` + 1, xR, xC)
1411                );
1412                dotProd += dot(xValues, wValues);
1413              }
1414
1415            } else if (`+(p===3)+`) {
1416              vec3 wValues = vec3(
1417                getW(wR, wC, `+f+`, d2),
1418                getW(wR, wC, `+f+` + 1, d2),
1419                getW(wR, wC, `+f+` + 2, d2)
1420              );
1421
1422              if (`+d+`) {
1423                vec3 xValues = vec3(
1424                  getX(batch, xR, xC, `+f+`),
1425                  getX(batch, xR, xC, `+f+` + 1),
1426                  getX(batch, xR, xC, `+f+` + 2)
1427                );
1428                dotProd += dot(xValues, wValues);
1429              } else {
1430                vec3 xValues = vec3(
1431                  getX(batch, `+f+`, xR, xC),
1432                  getX(batch, `+f+` + 1, xR, xC),
1433                  getX(batch, `+f+` + 2, xR, xC)
1434                );
1435                dotProd += dot(xValues, wValues);
1436              }
1437
1438            }
1439          }
1440        }
1441
1442        float result = dotProd;
1443        `+y+`
1444        `+b+`
1445        setOutput(result);
1446      }
1447    `},sf=function(r){this.variableNames=["x","W"],this.outputShape=r.outShape;var t=r.padInfo.front,e=r.padInfo.top,n=r.padInfo.left,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterDepth,h=r.filterHeight,f=r.filterWidth,p=4*Math.floor(r.inChannels/4),d=r.inChannels%4;this.userCode=`
1448      const ivec3 strides = ivec3(`+o+", "+a+", "+i+`);
1449      const ivec3 pads = ivec3(`+t+", "+e+", "+n+`);
1450
1451      void main() {
1452        ivec5 coords = getOutputCoords();
1453        int batch = coords.x;
1454        int d2 = coords.u;
1455
1456        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
1457        int xFCorner = xFRCCorner.x;
1458        int xRCorner = xFRCCorner.y;
1459        int xCCorner = xFRCCorner.z;
1460
1461        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
1462        // y(yF, yR, yC, d2). ? = to be determined. : = across all
1463        // values in that axis.
1464        float dotProd = 0.0;
1465        for (int wF = 0; wF < `+l+`; wF++) {
1466          int xF = xFCorner + wF * `+s+`;
1467
1468          if (xF < 0 || xF >= `+r.inDepth+`) {
1469            continue;
1470          }
1471
1472          for (int wR = 0; wR < `+h+`; wR++) {
1473            int xR = xRCorner + wR * `+u+`;
1474
1475            if (xR < 0 || xR >= `+r.inHeight+`) {
1476              continue;
1477            }
1478
1479            for (int wC = 0; wC < `+f+`; wC++) {
1480              int xC = xCCorner + wC * `+c+`;
1481
1482              if (xC < 0 || xC >= `+r.inWidth+`) {
1483                continue;
1484              }
1485
1486              for (int d1 = 0; d1 < `+p+`; d1 += 4) {
1487                vec4 xValues = vec4(
1488       
1488           getX(batch, xF, xR, xC, d1),
1489                  getX(batch, xF, xR, xC, d1 + 1),
1490                  getX(batch, xF, xR, xC, d1 + 2),
1491                  getX(batch, xF, xR, xC, d1 + 3)
1492                );
1493                vec4 wValues = vec4(
1494                  getW(wF, wR, wC, d1, d2),
1495                  getW(wF, wR, wC, d1 + 1, d2),
1496                  getW(wF, wR, wC, d1 + 2, d2),
1497                  getW(wF, wR, wC, d1 + 3, d2)
1498                );
1499
1500                dotProd += dot(xValues, wValues);
1501              }
1502
1503              if (`+(d===1)+`) {
1504                dotProd +=
1505                  getX(batch, xF, xR, xC, `+p+`) *
1506                  getW(wF, wR, wC, `+p+`, d2);
1507              } else if (`+(d===2)+`) {
1508                vec2 xValues = vec2(
1509                  getX(batch, xF, xR, xC, `+p+`),
1510                  getX(batch, xF, xR, xC, `+p+` + 1)
1511                );
1512                vec2 wValues = vec2(
1513                  getW(wF, wR, wC, `+p+`, d2),
1514                  getW(wF, wR, wC, `+p+` + 1, d2)
1515                );
1516                dotProd += dot(xValues, wValues);
1517              } else if (`+(d===3)+`) {
1518                vec3 xValues = vec3(
1519                  getX(batch, xF, xR, xC, `+p+`),
1520                  getX(batch, xF, xR, xC, `+p+` + 1),
1521                  getX(batch, xF, xR, xC, `+p+` + 2)
1522                );
1523                vec3 wValues = vec3(
1524                  getW(wF, wR, wC, `+p+`, d2),
1525                  getW(wF, wR, wC, `+p+` + 1, d2),
1526                  getW(wF, wR, wC, `+p+` + 2, d2)
1527                );
1528                dotProd += dot(xValues, wValues);
1529              }
1530            }
1531          }
1532        }
1533        setOutput(dotProd);
1534      }
1535    `},Ui=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.inHeight,a=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,h=r.dilationWidth,f=r.filterHeight,p=r.filterWidth,d=r.outChannels/r.inChannels,g="",v="";e&&(g=n?`float activation(float a) {
1536          float b = getPreluActivationWeightsAtOutCoords();
1537          `+e+`
1538        }`:`
1539          float activation(float x) {
1540            `+e+`
1541          }
1542        `,v="result = activation(result);");var m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
1543      `+g+`
1544
1545      const ivec2 strides = ivec2(`+u+", "+c+`);
1546      const ivec2 pads = ivec2(`+i+", "+s+`);
1547
1548      void main() {
1549        ivec4 coords = getOutputCoords();
1550        int batch = coords.x;
1551        ivec2 xRCCorner = coords.yz * strides - pads;
1552        int d2 = coords.w;
1553        int d1 = d2 / `+d+`;
1554        int q = d2 - d1 * `+d+`;
1555
1556        int xRCorner = xRCCorner.x;
1557        int xCCorner = xRCCorner.y;
1558
1559        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
1560        // ? = to be determined. : = across all values in that axis.
1561        float dotProd = 0.0;
1562        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
1563        for (int wR = 0; wR < `+f+`; wR++) {
1564          int xR = xRCorner + wR * `+l+`;
1565
1566          if (xR < 0 || xR >= `+o+`) {
1567            continue;
1568          }
1569
1570          for (int wC = 0; wC < `+p+`; wC++) {
1571            int xC = xCCorner + wC * `+h+`;
1572
1573            if (xC < 0 || xC >= `+a+`) {
1574              continue;
1575            }
1576
1577            float xVal = getX(batch, xR, xC, d1);
1578            float wVal = getW(wR, wC, d1, q);
1579            dotProd += xVal * wVal;
1580          }
1581        }
1582
1583        float result = dotProd;
1584        `+m+`
1585        `+v+`
1586        setOutput(result);
1587      }
1588    `},Vi=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.outShape;for(var o=r.inHeight,a=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,h=r.dilationWidth,f=r.filterHeight,p=r.filterWidth,d=p,g="int xR; int xC; int xCOffset;",v=0;v<f;v++)for(var m=0;m<p;m++)g+=`
1589          vec4 xTexelR`+v+"C"+2*m+` = vec4(0.);
1590          vec4 wR`+v+"C"+m+` = vec4(0.);
1591          vec4 xR`+v+"C"+m+" = vec4(0.);";for(v=0;v<f;v++)for(var x=0;x<d;x++){if(g+=`
1592          xR = xRCorner + `+v*l+`;
1593          xC = xCCorner + `+(m=2*x)*h+`;
1594        `,c===1){if(m<p&&(g+=s%2==1?`
1595                xCOffset = xC + 1;
1596                if(xR >= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) {
1597                  xTexelR`+v+"C"+m+` = getX(batch, xR, xCOffset, d1);
1598
1599                  // Need to manually clear unused channels in case
1600                  // we're reading from recycled texture.
1601                  if(xCOffset + 1 >= `+a+`) {
1602                    xTexelR`+v+"C"+m+`.zw = vec2(0.);
1603                  }
1604                } else {
1605                  xTexelR`+v+"C"+m+` = vec4(0.);
1606                }
1607
1608                xCOffset = xC + 1 - 2;
1609                if(xR >= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) {
1610                  vec4 previous = getX(batch, xR, xCOffset, d1);
1611
1612                  // Need to manually clear unused channels in case
1613                  // we're reading from recycled texture.
1614                  if(xCOffset + 1 >= `+a+`) {
1615                    previous.zw = vec2(0.);
1616                  }
1617
1618                  xR`+v+"C"+m+" = vec4(previous.zw, xTexelR"+v+"C"+m+`.xy);
1619                } else {
1620                  xR`+v+"C"+m+" = vec4(0, 0, xTexelR"+v+"C"+m+`.xy);
1621                }
1622              `:`
1623                if(xR >= 0 && xR < `+o+" && xC >= 0 && xC < "+a+`) {
1624                  xTexelR`+v+"C"+m+` = getX(batch, xR, xC, d1);
1625                } else {
1626                  xTexelR`+v+"C"+m+` = vec4(0.);
1627                }
1628
1629                xR`+v+"C"+m+" = xTexelR"+v+"C"+m+`;
1630              `,m+1<p)){var b=s%2==0?Ds(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(g+=`
1631                  xCOffset = xC + `+s%2+" + "+b+`;
1632
1633                  if(xR >= 0 && xR < `+o+` &&
1634                    xCOffset >= 0 && xCOffset < `+a+`) {
1635                    xTexelR`+v+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1);
1636                  }
1637                `,h>1&&(g+=`
1638                    xCOffset -= 2;
1639                    if(xR >= 0 && xR < `+o+` &&
1640                      xCOffset >= 0 && xCOffset < `+a+`) {
1641                      xTexelR`+v+"C"+m+` = getX(batch, xR, xCOffset, d1);
1642                    } else {
1643                      xTexelR`+v+"C"+m+` = vec4(0.);
1644                    }
1645                  `),g+=`
1646                  xR`+v+"C"+(m+1)+` = vec4(
1647                    xTexelR`+v+"C"+m+".zw, xTexelR"+v+"C"+(m+2)+`.xy);
1648                `):g+=`
1649                  xCOffset = xC + `+b+`;
1650
1651                  if(xR >= 0 && xR < `+o+` &&
1652                    xCOffset >= 0 && xCOffset < `+a+`) {
1653                    xTexelR`+v+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1);
1654                  }
1655
1656                  xR`+v+"C"+(m+1)+" = xTexelR"+v+"C"+(m+2)+`;
1657                `}}else m<p&&(g+=`
1658              if(xR >= 0 && xR < `+o+`) {
1659            `,s%2==1?(g+=`
1660                xCOffset = xC + 1 - `+c+`;
1661                if(xCOffset >= 0 && xCOffset < `+a+`) {
1662                  xTexelR`+v+"C"+m+` = getX(batch, xR, xCOffset, d1);
1663                } else {
1664                  xTexelR`+v+"C"+m+` = vec4(0.);
1665                }
1666
1667                if(xC + 1 >= 0 && xC + 1 < `+a+`) {
1668                  xTexelR`+v+"C"+(m+2)+` = getX(batch, xR, xC + 1, d1);
1669                } else {
1670                  xTexelR`+v+"C"+(m+2)+` = vec4(0.);
1671                }
1672
1673                xR`+v+"C"+m+` = vec4(
1674                  xTexelR`+v+"C"+m+".zw, xTexelR"+v+"C"+(m+2)+`.zw);
1675              `,m+1<p&&(g+=`
1676                  vec4 final = vec4(0.);
1677                  xCOffset = xC + 1 + `+c+`;
1678                  if(xCOffset >= 0 && xCOffset < `+a+`) {
1679                    final = getX(batch, xR, xCOffset, d1);
1680                  }
1681                  xR`+v+"C"+(m+1)+" = vec4(xTexelR"+v+"C"+(m+2)+`.xy, final.xy);
1682                `)):(g+=`
1683                if(xC >= 0 && xC < `+a+`) {
1684                  xTexelR`+v+"C"+m+` = getX(batch, xR, xC, d1);
1685                } else {
1686                  xTexelR`+v+"C"+m+` = vec4(0.);
1687                }
1688
1689                xCOffset = xC + `+c+`;
1690                if(xCOffset >= 0 && xCOffset < `+a+`) {
1691                  xTexelR`+v+"C"+(m+2)+` = getX(batch, xR, xCOffset, d1);
1692                } else {
1693                  xTexelR`+v+"C"+(m+2)+` = vec4(0.);
1694                }
1695
1696                xR`+v+"C"+m+` = vec4(
1697                  xTexelR`+v+"C"+m+".xy, xTexelR"+v+"C"+(m+2)+`.xy);
1698              `,m+1<p&&(g+=`
1699                  xR`+v+"C"+(m+1)+` = vec4(
1700                    xTexelR`+v+"C"+m+".zw, xTexelR"+v+"C"+(m+2)+`.zw);
1701                `)),g+="}");m<p&&(g+=`
1702            vec4 wTexelR`+v+"C"+m+" = getW("+v+", "+m+`, d1, q);
1703            wR`+v+"C"+m+" = vec4(wTexelR"+v+"C"+m+".xz, wTexelR"+v+"C"+m+`.xz);
1704          `,m+1<p&&(g+=`
1705              vec4 wTexelR`+v+"C"+(m+1)+" = getW("+v+", "+(m+1)+`, d1, q);
1706              wR`+v+"C"+(m+1)+` =
1707                vec4(wTexelR`+v+"C"+(m+1)+".xz, wTexelR"+v+"C"+(m+1)+".xz);"))}for(v=0;v<f;v++)for(m=0;m<p;m++)g+="dotProd += xR"+v+"C"+m+" * wR"+v+"C"+m+";";var y="",w="";e&&(y=n?`vec4 activation(vec4 a) {
1708          vec4 b = getPreluActivationWeightsAtOutCoords();
1709          `+e+`
1710        }`:`vec4 activation(vec4 x) {
1711          `+e+`
1712        }`,w="result = activation(result);");var C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
1713      `+y+`
1714
1715      const ivec2 strides = ivec2(`+u+", "+c+`);
1716      const ivec2 pads = ivec2(`+i+", "+s+`);
1717
1718      void main() {
1719
1720        ivec4 coords = getOutputCoords();
1721        int batch = coords.x;
1722        ivec2 xRCCorner = coords.yz * strides - pads;
1723        int d2 = coords.w;
1724        int d1 = d2;
1725        int q = 0;
1726        int xRCorner = xRCCorner.x;
1727        int xCCorner = xRCCorner.y;
1728
1729        vec4 dotProd = vec4(0.);
1730
1731        `+g+`
1732
1733        vec4 result = dotProd;
1734        `+C+`
1735        `+w+`
1736        setOutput(result);
1737      }
1738    `},uf=function(r,t,e,n,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=r[0],i=r[1],s=r[2],u=r[3],c=t[0],l=e[0],h=e[1];this.outputShape=[c,l,h,u];var f=n==="bilinear"?1:0,p=[i-1+".0",s-1+".0"],d=p[0],g=p[1],v=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],m=v[0],x=v[1],b=v[2],y=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],w=y[0],C=y[1],S=y[2];this.userCode=`
1739      const float height_ratio = float(`+m+`);
1740      const float width_ratio = float(`+w+`);
1741      void main() {
1742        ivec4 coords = getOutputCoords();
1743        int b = coords[0];
1744        int y = coords[1];
1745        int x = coords[2];
1746        int d = coords[3];
1747
1748        // get box vals
1749        float y1 = getBoxes(b,0);
1750        float x1 = getBoxes(b,1);
1751        float y2 = getBoxes(b,2);
1752        float x2 = getBoxes(b,3);
1753
1754        // get image in batch index
1755        int bInd = round(getBoxInd(b));
1756        if(bInd < 0 || bInd >= `+a+`) {
1757          return;
1758        }
1759
1760        float height_scale = `+x+`;
1761        float width_scale = `+C+`;
1762
1763        float in_y = `+b+`;
1764        if( in_y < 0.0 || in_y > `+d+` ) {
1765          setOutput(float(`+o+`));
1766          return;
1767        }
1768        float in_x = `+S+`;
1769        if( in_x < 0.0 || in_x > `+g+` ) {
1770          setOutput(float(`+o+`));
1771          return;
1772        }
1773
1774        vec2 sourceFracIndexCR = vec2(in_x,in_y);
1775        if(`+f+` == 1) {
1776          // Compute the four integer indices.
1777          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
1778          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
1779
1780          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
1781          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
1782          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
1783          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
1784
1785          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
1786
1787          float top = topLeft + (topRight - topLeft) * fracCR.x;
1788          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
1789          float newValue = top + (bottom - top) * fracCR.y;
1790          setOutput(newValue);
1791        } else {
1792          // Compute the coordinators of nearest neighbor point.
1793          ivec2 sourceNearestCR = ivec2(floor(
1794            sourceFracIndexCR + vec2(0.5,0.5)));
1795          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
1796          setOutput(newValue);
1797        }
1798      }
1799    `},cf=function(r,t,e){this.variableNames=["x"],this.outputShape=r;var n=r.length,o=r[r.length-1],a=e?"<":">";this.userCode=`
1800      int getIndex(int i) {
1801        `+(e?"return "+o+" -i - 1;":"return i;")+`
1802      }
1803
1804      void main() {
1805        `+be(n)+` coords = getOutputCoords();
1806        int end = `+zi(n,"coords")+`;
1807        float val = 0.0;
1808        for (int i = `+o+` - 1; i >= 0; i -= 1) {
1809          int idx = getIndex(i);
1810          if (idx `+a+` end) {
1811            continue;
1812          }
1813          if (idx == end && `+t+`) {
1814            continue;
1815          }
1816          `+zi(n,"coords")+` = idx;
1817          val += getX(`+function(i,s){if(i===1)return""+s;if(i===2)return s+".x, "+s+".y";if(i===3)return s+".x, "+s+".y, "+s+".z";if(i===4)return s+".x, "+s+".y, "+s+".z, "+s+".w";throw Error("Cumulative sum for rank "+i+" is not yet supported")}(n,"coords")+`);
1818        }
1819        setOutput(val);
1820      }
1821    `};function zi(r,t){if(r===1)return""+t;if(r===2)return t+".y";if(r===3)return t+".z";if(r===4)return t+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}var lf=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=rr.DENSE;var t=Qn(r),e=je();this.outputShape=r,this.userCode=`
1822      ivec3 outCoordsFromFlatIndex(int index) {
1823        `+fn(["r","c","d"],r)+`
1824        return ivec3(r, c, d);
1825      }
1826
1827      void main() {
1828        ivec2 resTexRC = ivec2(resultUV.yx *
1829          vec2(`+t[0]+", "+t[1]+`));
1830        int index = 4 * (resTexRC.x * `+t[1]+` + resTexRC.y);
1831
1832        vec4 result = vec4(0.);
1833
1834        for (int i=0; i<4; i++) {
1835          int flatIndex = index + i;
1836          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
1837          result[i] = getA(rc.x, rc.y, rc.z);
1838        }
1839
1840        `+e.output+` = result;
1841      }
1842    `},hf=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=rr.DENSE;var t=Qn(r),e=je();this.outputShape=r,this.userCode=`
1843      ivec3 outCoordsFromFlatIndex(int index) {
1844        `+fn(["r","c","d"],r)+`
1845        return ivec3(r, c, d);
1846      }
1847
1848      void main() {
1849        ivec2 resTexRC = ivec2(resultUV.yx *
1850          vec2(`+t[0]+", "+t[1]+`));
1851        int index = 4 * (resTexRC.x * `+t[1]+` + resTexRC.y);
1852
1853        vec4 result = vec4(0.);
1854
1855        for (int i=0; i<4; i++) {
1856          int flatIndex = index + i;
1857          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
1858          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
1859        }
1860
1861        `+e.output+` = result;
1862      }
1863    `},ff=function(){function r(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode=`
1864    void main() {
1865      ivec4 coords = getOutputCoords();
1866      int b = coords[0];
1867      int h = `+this.getHeightCoordString()+`;
1868      int w = `+this.getWidthCoordString()+`;
1869      int d = `+this.getDepthCoordString()+`;
1870
1871      int in_h = h / `+e+`;
1872      int offset_h = imod(h, `+e+`);
1873      int in_w = w / `+e+`;
1874      int offset_w = imod(w, `+e+`);
1875      int offset_d = (offset_h * `+e+` + offset_w) *
1876        `+this.getOutputDepthSize()+`;
1877      int in_d = d + offset_d;
1878
1879      float result = `+this.getInputSamplingString()+`;
1880      setOutput(result);
1881    }
1882  `}return r.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},r.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},r.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},r.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},r.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},r}(),pf=function(r){this.variableNames=["X"],this.outputShape=[r,r],this.userCode=`
1883      void main() {
1884          ivec2 coords = getOutputCoords();
1885          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
1886          setOutput(val);
1887      }
1888    `},df=function(r){this.variableNames=["A"],this.outTexUsage=it.DOWNLOAD;var t=je();this.outputShape=r,this.userCode=`
1889      `+uu+`
1890
1891      void main() {
1892        float x = getAAtOutCoords();
1893        `+t.output+` = encode_float(x);
1894      }
1895    `},vf=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=it.DOWNLOAD;var t=je();this.outputShape=r,this.userCode=`
1896      `+uu+`
1897
1898      void main() {
1899        ivec3 coords = getOutputCoords();
1900        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
1901        `+t.output+` = encode_float(x);
1902      }
1903    `},mf=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"];var n=je(),o=t[0],a=t[1];this.outputShape=r;var i="result";e&&(i="floor(result * 255. + 0.5)"),this.userCode=`
1904      `+Ta(r)+`
1905
1906      void main() {
1907        ivec3 coords = getOutputCoords();
1908
1909        int flatIndex = getFlatIndex(coords);
1910        int offset = imod(flatIndex, 4);
1911
1912        flatIndex = idiv(flatIndex, 4, 1.);
1913        
1914        int r = flatIndex / `+a+`;
1915        int c = imod(flatIndex, `+a+`);
1916        vec2 uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0);
1917        vec4 values = `+n.texture2D+`(A, uv);
1918
1919        float result;
1920
1921        if(offset == 0) {
1922          result = values[0];
1923        } else if(offset == 1) {
1924          result = values[1];
1925        } else if(offset == 2) {
1926          result = values[2];
1927        } else {
1928          result = values[3];
1929        }
1930
1931        `+n.output+" = vec4("+i+`, 0., 0., 0.);
1932      }
1933    `},gf=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var n=je(),o=t[0],a=t[1];this.outputShape=r;var i="",s="result";e&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;i+=`
1934          localCoords = coords;
1935          if(localCoords[2] + `+c+" < "+r[2]+`) {
1936            localCoords[2] += `+c+`;
1937            if(localCoords[1] + `+u+" < "+r[1]+`) {
1938              localCoords[1] += `+u+`;
1939
1940              flatIndex = getFlatIndex(localCoords);
1941              offset = imod(flatIndex, 4);
1942
1943              flatIndex = idiv(flatIndex, 4, 1.);
1944
1945              r = flatIndex / `+a+`;
1946              c = imod(flatIndex, `+a+`);
1947              uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0);
1948              values = `+n.texture2D+`(A, uv);
1949
1950              if(offset == 0) {
1951                result[`+l+`] = values[0];
1952              } else if(offset == 1) {
1953                result[`+l+`] = values[1];
1954              } else if(offset == 2) {
1955                result[`+l+`] = values[2];
1956              } else {
1957                result[`+l+`] = values[3];
1958              }
1959            }
1960          }
1961        `}this.userCode=`
1962      `+Ta(r)+`
1963
1964      void main() {
1965        ivec3 coords = getOutputCoords();
1966
1967        vec4 result = vec4(0.);
1968        int flatIndex, r, c, offset;
1969        ivec3 localCoords;
1970        vec2 uv;
1971        vec4 values;
1972
1973        `+i+`
1974
1975        `+n.output+" = "+s+`;
1976      }
1977    `},yf="return real * expR - imag * expI;",xf="return real * expI + imag * expR;",Gi=function(r,t,e){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var o=e?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=e?n+".0":"1.0";this.userCode=`
1978      const float exponentMultiplier = `+o+`;
1979
1980      float unaryOpComplex(float real, float expR, float imag, float expI) {
1981        `+r+`
1982      }
1983
1984      float mulMatDFT(int batch, int index) {
1985        float indexRatio = float(index) / float(`+n+`);
1986        float exponentMultiplierTimesIndexRatio =
1987            exponentMultiplier * indexRatio;
1988
1989        float result = 0.0;
1990
1991        for (int i = 0; i < `+n+`; i++) {
1992          // x = (-2|2 * PI / N) * index * i;
1993          float x = exponentMultiplierTimesIndexRatio * float(i);
1994          float expR = cos(x);
1995          float expI = sin(x);
1996          float real = getReal(batch, i);
1997          float imag = getImag(batch, i);
1998
1999          result +=
2000              unaryOpComplex(real, expR, imag, expI) / `+a+`;
2001        }
2002
2003        return result;
2004      }
2005
2006      void main() {
2007        ivec2 coords = getOutputCoords();
2008        setOutput(mulMatDFT(coords[0], coords[1]));
2009      }
2010    `},bf=function(){function r(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=`
2011      uniform float value;
2012      void main() {
2013        // Input can be obtained from uniform value.
2014        setOutput(value);
2015      }
2016    `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.valueLoc==null&&(e.valueLoc=n.getUniformLocationNoThrow(o,"value")),n.gl.uniform1f(e.valueLoc,t)}},r}(),wf=function(r,t,e){this.variableNames=["A","indices"];var n=r.slice();n[e]=t,this.outputShape=n,this.rank=n.length;var o=be(this.rank),a=function(i,s){var u=i.length;if(u>4)throw Error("Gather for rank "+u+" is not yet supported");if(u===1)return"int(getIndices(resRC))";for(var c=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],h=0;h<i.length;h++)h===s?l.push("int(getIndices("+c[h]+"))"):l.push(""+c[h]);return l.join()}(r,e);this.userCode=`
2017      void main() {
2018        `+o+` resRC = getOutputCoords();
2019        setOutput(getA(`+a+`));
2020      }
2021    `},Cf=function(r,t,e){this.sliceDim=r,this.strides=t,this.variableNames=["x","indices"],this.outputShape=e;var n=be(t.length),o=be(e.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2022        `+n+" strides = "+n+"("+this.strides+`);
2023         void main() {
2024          `+o+` coords = getOutputCoords();
2025          int flattenIndex = 0;
2026          for (int j = 0; j < `+this.sliceDim+`; j++) {
2027            int index = round(getIndices(coords[0], j));
2028            flattenIndex += index * `+a+`;
2029          }
2030          setOutput(getX(flattenIndex, coords[1]));
2031        }
2032      `};function _f(r,t){var e=je();return gl(r,t,e.version+`
2033    precision highp float;
2034    `+e.attribute+` vec3 clipSpacePos;
2035    `+e.attribute+` vec2 uv;
2036    `+e.varyingVs+` vec2 resultUV;
2037
2038    void main() {
2039      gl_Position = vec4(clipSpacePos, 1);
2040      resultUV = uv;
2041    }`)}function Ef(r,t){return Cl(r,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function If(r,t){return _l(r,t,new Uint16Array([0,1,2,2,1,3]))}function hr(r,t,e,n,o,a,i){Il(e,n);var s=El(r,t),u=r.TEXTURE_2D;return J(r,t,function(){return r.bindTexture(u,s)}),J(r,t,function(){return r.texParameteri(u,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)}),J(r,t,function(){return r.texParameteri(u,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}),J(r,t,function(){return r.texParameteri(u,r.TEXTURE_MIN_FILTER,r.NEAREST)}),J(r,t,function(){return r.texParameteri(u,r.TEXTURE_MAG_FILTER,r.NEAREST)}),J(r,t,function(){return r.texImage2D(u,0,o,e,n,0,a,i,null)}),J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)}),s}function Rf(r,t,e,n,o){var a=no(e,n);return hr(r,t,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,r.FLOAT)}function kf(r,t,e,n,o){var a=no(e,n);return hr(r,t,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Sf(r,t,e,n,o){var a=no(e,n);return hr(r,t,a[0],a[1],r.RGBA,r.RGBA,r.UNSIGNED_BYTE)}function Df(r,t,e,n,o){var a=lr(e,n);return hr(r,t,a[0],a[1],o.internalFormatPackedFloat,r.RGBA,r.FLOAT)}function Af(r,t,e,n,o){var a=lr(e,n);return hr(r,t,a[0],a[1],o.internalFormatPackedHalfFloat,r.RGBA,o.textureTypeHalfFloat)}function Tf(r,t,e,n){return J(r,t,function(){return r.bindBuffer(r.ARRAY_BUFFER,n)}),Ai(r,t,e,"clipSpacePos",n,3,20,0)&&Ai(r,t,e,"uv",n,2,20,12)}function Nf(r,t,e,n,o,a,i){var s,u,c;J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)}),a instanceof Uint8Array?(s=new Uint8Array(n*o*4),u=r.UNSIGNED_BYTE,c=r.RGBA):(s=new Float32Array(n*o*4),u=r.FLOAT,c=i.internalFormatPackedFloat),s.set(a),J(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,c,n,o,0,r.RGBA,u,s)}),J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function Ff(r,t,e,n){J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,e)}),n.data instanceof Uint8Array?J(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,n.width,n.height,0,r.RGBA,r.UNSIGNED_BYTE,n.data)}):J(r,t,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,n)}),J(r,t,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function Pf(r,t,e,n,o){var a=r.createBuffer();J(r,t,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,a)});var i=16*e*n;return J(r,t,function(){return r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)}),J(r,t,function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,0)}),J(r,t,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,null)}),a}function Mf(r,t,e){var n=r,o=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}
vendor: 14,572 bytes, lines 2041-2093
2041function Of(r,t,e,n,o){var a=no(e,n),i=a[0],s=a[1],u=new Uint8Array(e*n*4);return J(r,t,function(){return r.readPixels(0,0,i,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Bf(r,t,e,n,o,a,i,s){var u=r,c=new Float32Array(function(l,h){var f=lr(l,h);return f[0]*f[1]*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function Lf(r,t,e,n){var o=new Float32Array(e*n*4);return J(r,t,function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,o)}),o}var Wf=function(){function r(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=M().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,fl(e,t)):this.gl=Nt(e);var n="WEBGL_color_buffer_float";if(M().getNumber("WEBGL_VERSION")===1){if(this.textureFloatExtension=yr(this.gl,this.debug,"OES_texture_float"),ft(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=yr(this.gl,this.debug,"OES_texture_half_float");else if(M().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),ft(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=yr(this.gl,this.debug,"EXT_color_buffer_half_float");else if(M().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",ft(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!ft(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=Ef(this.gl,this.debug),this.indexBuffer=If(this.gl,this.debug),this.framebuffer=Rl(this.gl,this.debug),this.textureConfig=wa(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(r.prototype,"debug",{get:function(){return M().getBool("DEBUG")},enumerable:!0,configurable:!0}),r.prototype.dispose=function(){var t=this;if(!this.disposed){this.program!=null&&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."),this.outputTexture!=null&&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;J(e,this.debug,function(){return e.finish()}),J(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),J(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),J(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),J(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),J(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},r.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Rf(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),kf(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Sf(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Ff(this.gl,this.debug,t,e)},r.prototype.uploadDenseMatrixToTexture=function(t,e,n,o){this.throwIfDisposed(),Nf(this.gl,this.debug,t,e,n,o,this.textureConfig)},r.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Af(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Df(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(Ti(this.gl,this.debug,this.framebuffer),this.outputTexture=null),J(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},r.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,function(){return Of(o.gl,o.debug,e,n,o.textureConfig)})},r.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,o,a,i){return Bf(this.gl,t,0,0,0,a,i,this.textureConfig)},r.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Mf(this.gl,t,e)},r.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var o=Pf(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),o},r.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},r.prototype.createFence=function(t){var e,n,o=this;if(M().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var s=a.clientWaitSync(i,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},e=i}else M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return o.isQueryAvailable(e,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},r.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,function(){return Lf(o.gl,o.debug,e,n)})},r.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=yl(e,this.debug,t),o=_f(e,this.debug),a=bl(e,this.debug);return J(e,this.debug,function(){return e.attachShader(a,o)}),J(e,this.debug,function(){return e.attachShader(a,n)}),wl(e,this.debug,a),this.debug&&Do(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=Tf(e,this.debug,this.program,this.vertexBuffer)),a},r.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&J(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},r.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&Do(this.gl,this.debug,this.program),J(this.gl,this.debug,function(){return e.gl.useProgram(t)})},r.prototype.getUniformLocation=function(t,e,n){return n===void 0&&(n=!0),this.throwIfDisposed(),n?Sl(this.gl,this.debug,t,e):Dl(this.gl,t,e)},r.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),J(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},r.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},r.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),Al(this.gl,this.debug,this.program,t,e,n)},r.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},r.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var o=lr(e,n),a=o[0],i=o[1];this.setOutputMatrixTextureDriver(t,a,i)},r.prototype.setOutputMatrixWriteRegion=function(t,e,n,o){this.setOutputMatrixWriteRegionDriver(n,t,o,e)},r.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},r.prototype.debugValidate=function(){this.program!=null&&Do(this.gl,this.debug,this.program),xr(this.gl)},r.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),J(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},r.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),J(this.gl,this.debug,function(){return t.gl.finish()})},r.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=yr(this.gl,this.debug,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},r.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},r.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},r.prototype.beginQuery=function(){if(M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var o=this.getQueryTimerExtensionWebGL1(),a=o.createQueryEXT();return o.beginQueryEXT(o.TIME_ELAPSED_EXT,a),a},r.prototype.endQuery=function(){if(M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")!==2){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},r.prototype.waitForQueryAndGetTime=function(t){return X(this,void 0,void 0,function(){var e=this;return $(this,function(n){switch(n.label){case 0:return[4,Ei(function(){return e.disposed||e.isQueryAvailable(t,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},r.prototype.getQueryTime=function(t,e){if(e===0)return null;if(e===2){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var o=this.getQueryTimerExtensionWebGL1();return o.getQueryObjectEXT(t,o.QUERY_RESULT_EXT)/1e6},r.prototype.isQueryAvailable=function(t,e){if(e===0)return!0;if(e===2){var n=this.gl,o=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(o=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,o.QUERY_RESULT_AVAILABLE_EXT),this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint},r.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},r.prototype.pollItems=function(){for(var t=function(n){for(var o=0;o<n.length&&n[o]();++o);return o-1}(this.itemsToPoll.map(function(n){return n.isDoneFn})),e=0;e<=t;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(t+1)},r.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||Ei(function(){return n.pollItems(),n.itemsToPoll.length===0})},r.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),Ao(this.gl,this.debug,t,this.framebuffer),this.debug&&xr(this.gl)},r.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(Ao(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&xr(this.gl)):Ti(this.gl,this.debug,this.framebuffer)},r.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},r.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var o=this.gl;Ao(o,this.debug,t,this.framebuffer),this.debug&&xr(o),this.outputTexture=t,J(o,this.debug,function(){return o.viewport(0,0,e,n)}),J(o,this.debug,function(){return o.scissor(0,0,e,n)})},r.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,o){var a=this;this.throwIfDisposed(),J(this.gl,this.debug,function(){return a.gl.scissor(t,e,n,o)})},r.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},r.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},r}();function Hi(r,t){if(r.length!==t.length)throw Error("Binary was compiled with "+r.length+" inputs, but was executed with "+t.length+" inputs");r.forEach(function(e,n){var o=e.logicalShape,a=t[n],i=a.shape;if(!We(o,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+o+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var s=e.texShape,u=a.isUniform?null:a.texData.texShape;if(!We(s,u))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+u+" must match")}})}var Uf=function(r,t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var n=e.filterWidth,o=e.inChannels,a=e.strideWidth,i=e.strideHeight,s=e.padInfo,u=e.outWidth,c=e.dilationWidth,l=e.dilationHeight,h=e.dataFormat,f=s.left,p=s.top,d=o*n,g=je(),v=h==="channelsLast",m=v?0:1,x=v?1:2,b="",y=0;y<=1;y++)for(var w=0;w<=1;w++)b+=`
2042          blockIndex = rc.y + `+w+`;
2043          pos = rc.x + `+y+`;
2044
2045          if(blockIndex < `+r[1]+" && pos < "+r[0]+`) {
2046            offsetY = int(blockIndex / (`+u+")) * "+i+" - "+p+`;
2047            d0 = offsetY + `+l+" * (pos / "+d+`);
2048
2049            if(d0 < `+t[m]+` && d0 >= 0) {
2050
2051              offsetX = int(mod(float(blockIndex), `+u+".) * "+a+". - "+f+`.);
2052              d1 = offsetX + `+c+" * (int(mod(float(pos), "+d+".) / "+o+`.));
2053
2054              if(d1 < `+t[x]+` && d1 >= 0) {
2055
2056                ch = int(mod(float(pos), `+o+`.));
2057
2058                if (`+v+`) {
2059                  innerDims = vec2(d1, ch);
2060                  result[`+(2*y+w)+`] = getChannel(
2061                    getA(d0, int(innerDims.x),
2062                    int(innerDims.y)), innerDims);
2063                } else {
2064                  innerDims = vec2(d0, d1);
2065                  result[`+(2*y+w)+`] = getChannel(
2066                    getA(ch, int(innerDims.x),
2067                    int(innerDims.y)), innerDims);
2068                }
2069              }
2070            }
2071          }
2072        `;this.userCode=`
2073      void main() {
2074        ivec2 rc = getOutputCoords();
2075
2076        vec4 result = vec4(0);
2077
2078        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
2079        vec2 innerDims;
2080
2081        `+b+`
2082
2083        `+g.output+` = result;
2084      }
2085    `},Vf=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[];var a,i=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode=`
2086      void main() {
2087        ivec4 coords = getOutputCoords();
2088        int b = coords[0];
2089        int r = coords[1];
2090        int c = coords[2];
2091        int d = coords[3];
2092        float x = getX(b, r, c, d);
2093        float sum = 0.0;
2094        for (int j = -`+i+"; j <= "+i+`; j++) {
2095          int idx = d + j;
2096          if (idx >= 0 && idx <=  `+s+`) {
2097            float z = getX(b, r, c, idx);
2098            sum += z * z;
2099          }
2100        }
2101        float val = x * `+a+`;
2102        setOutput(val);
2103      }
2104    `},zf=function(r,t,e,n,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=r,this.depth=r[3],this.depthRadius=t,this.bias=e,this.alpha=n,this.beta=o,this.userCode=`
2105      void main() {
2106        ivec4 coords = getOutputCoords();
2107        int b = coords[0];
2108        int r = coords[1];
2109        int c = coords[2];
2110
2111        float result = 0.0;
2112        for (int d = 0; d < `+this.depth+`; ++d) {
2113          int depthBegin = int(max(0.0, float(d - `+t+`)));
2114          int depthEnd = int(min(float(`+this.depth+`),
2115              float(d + `+t+` + 1)));
2116
2117          const int MIN_DEPTH_BEGIN = 0;
2118          const int MAX_DEPTH_END = `+this.depth+`;
2119
2120          float norm = 0.0;
2121          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
2122            if (k < depthBegin){
2123              continue;
2124            }
2125            else if (k >= depthBegin && k < depthEnd) {
2126              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
2127            }
2128            else {
2129              break;
2130            }
2131          }
2132
2133          norm = float(`+n+") * norm + float("+e+`);
2134
2135          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
2136            if (k < depthBegin){
2137              continue;
2138            }
2139            else if (k >= depthBegin && k < depthEnd){
2140              float dyi = -2.0 * float(`+n+`)
2141                * float(`+o+`)
2142                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
2143                / norm;
2144              if (k == d) {
2145                dyi += pow(norm, -1.0 * `+o+`);
2146              }
2147              if (k == coords[3]) {
2148                dyi *= getDy(b, r, c, d);
2149                result += dyi;
2150              }
2151            }
2152            else {
2153              break;
2154            }
2155          }
2156      }
2157      setOutput(result);
2158      }
2159    `},Gf=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode=`
2160      void main() {
2161        ivec4 coords = getOutputCoords();
2162        int b = coords.x;
2163        int r = coords.y;
2164        int c = coords.z;
2165        int d = coords.w;
2166
2167        bool hasNextCol = d < `+this.outputShape[3]+`;
2168        bool hasNextRow = c < `+this.outputShape[2]+`;
2169
2170        vec4 sum = vec4(0.);
2171        vec4 xFragAtOutputCoords = getX(b, r, c, d);
2172
2173        vec4 xAtOutputCoords = vec4(
2174          getChannel(xFragAtOutputCoords, vec2(c, d)),
2175          hasNextCol ?
2176            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
2177          hasNextRow ?
2178            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
2179          (hasNextRow && hasNextCol) ?
2180            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
2181        );
2182
2183        int firstChannel = d - `+i+`;
2184        vec2 cache = vec2(0.);
2185        if(firstChannel >= 0){
2186          vec4 firstChannelFrag = getX(b, r, c, firstChannel);
2187          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
2188            if(hasNextRow){
2189              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
2190            }
2191        }
2192
2193        ivec2 depth = ivec2(d, d + 1);
2194        for (int j = - `+i+"; j <= "+i+`; j++) {
2195          ivec2 idx = depth + j;
2196          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
2197          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+s+`));
2198
2199          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
2200          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
2201
2202          if(depthInRange || depthPlusOneInRange){
2203            vec4 z = vec4(0.);
2204            vec4 xFragAtCurrentDepth;
2205            z.xz = cache.xy;
2206            if(depthPlusOneInRange && hasNextCol){
2207              xFragAtCurrentDepth = idx.y != d ?
2208                getX(b, r, c, idx.y) : xFragAtOutputCoords;
2209              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
2210              if(hasNextRow){
2211                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
2212              }
2213            }
2214            cache.xy = z.yw;
2215            sum += z * z;
2216          }
2217        }
2218        vec4 result = xAtOutputCoords * `+a+`;
2219        setOutput(result);
2220      }
2221    `},Hf=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideHeight,e=r.strideWidth,n=r.dilationHeight,o=r.effectiveFilterHeight,a=r.effectiveFilterWidth,i=o-1-r.padInfo.top,s=a-1-r.padInfo.left,u=o*a-1;this.userCode=`
2222      const ivec2 pads = ivec2(`+i+", "+s+`);
2223
2224      void main() {
2225        ivec4 coords = getOutputCoords();
2226        int b = coords[0];
2227        int d = coords[3];
2228
2229        ivec2 dyRCCorner = coords.yz - pads;
2230        int dyRCorner = dyRCCorner.x;
2231        int dyCCorner = dyRCCorner.y;
2232
2233        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
2234        // ? = to be determined. : = across all values in that axis.
2235        float dotProd = 0.0;
2236        for (int wR = 0; wR < `+o+`;
2237          wR += `+n+`) {
2238          float dyR = float(dyRCorner + wR) / `+t+`.0;
2239
2240          if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
2241            continue;
2242          }
2243          int idyR = int(dyR);
2244
2245          for (int wC = 0; wC < `+a+`; wC++) {
2246            float dyC = float(dyCCorner + wC) / `+e+`.0;
2247
2248            if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
2249                fract(dyC) > 0.0) {
2250              continue;
2251            }
2252            int idyC = int(dyC);
2253
2254            float dyValue = getDy(b, idyR, idyC, d);
2255            int maxPosValue = `+u+` - int(getMaxPos(b, idyR, idyC, d));
2256
2257            // Get the current value, check it against the value from the
2258            // position matrix.
2259            int curPosValue = wR * `+a+` + wC;
2260            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2261
2262            dotProd += dyValue * mask;
2263          }
2264        }
2265        setOutput(dotProd);
2266      }
2267    `},qf=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.dilationDepth,a=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterDepth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,l=s-1-r.padInfo.front,h=u-1-r.padInfo.top,f=c-1-r.padInfo.left,p=s*u*c-1;this.userCode=`
2268      const ivec3 pads = ivec3(`+l+", "+h+", "+f+`);
2269
2270      void main() {
2271        ivec5 coords = getOutputCoords();
2272        int batch = coords.x;
2273        int ch = coords.u;
2274
2275        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
2276        int dyDCorner = dyCorner.x;
2277        int dyRCorner = dyCorner.y;
2278        int dyCCorner = dyCorner.z;
2279
2280        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
2281        // dx(xD, xR, xC, ch).
2282        // ? = to be determined. : = across all values in that axis.
2283        float dotProd = 0.0;
2284
2285        for (int wD = 0; wD < `+s+`;
2286           wD += `+o+`) {
2287          float dyD = float(dyDCorner + wD) / `+t+`.0;
2288
2289          if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) {
2290            continue;
2291          }
2292          int idyD = int(dyD);
2293
2294          for (int wR = 0; wR < `+u+`;
2295              wR += `+a+`) {
2296            float dyR = float(dyRCorner + wR) / `+e+`.0;
2297
2298            if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
2299                fract(dyR) > 0.0) {
2300              continue;
2301            }
2302            int idyR = int(dyR);
2303
2304            for (int wC = 0; wC < `+c+`;
2305                wC += `+i+`) {
2306              float dyC = float(dyCCorner + wC) / `+n+`.0;
2307
2308              if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
2309                  fract(dyC) > 0.0) {
2310                continue;
2311              }
2312              int idyC = int(dyC);
2313
2314              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2315              int maxPosValue = `+p+` -
2316                  int(getMaxPos(batch, idyD, idyR, idyC, ch));
2317
2318              // Get the current value, check it against the value from the
2319              // position matrix.
2320              int curPosValue =
2321                  wD * `+u+" * "+c+` +
2322                  wR * `+c+` + wC;
2323              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2324
2325              dotProd += dyValue * mask;
2326            }
2327          }
2328        }
2329        setOutput(dotProd);
2330      }
2331    `},Mo=function(r,t,e,n,o,a,i){e===void 0&&(e=!1),n===void 0&&(n=!1),o===void 0&&(o=!1),a===void 0&&(a=null),i===void 0&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=e?r[1]:r[2],u=Math.ceil(s/2),c=e?"i * 2, rc.y":"rc.y, i * 2",l=n?"rc.z, i * 2":"i * 2, rc.z",h=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],p="",d="";a&&(p=i?`vec4 activation(vec4 a) {
2332          vec4 b = getPreluActivationWeightsAtOutCoords();
2333          `+a+`
2334        }`:`vec4 activation(vec4 x) {
2335          `+a+`
2336        }`,d="result = activation(result);");var g=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
2337      `+p+`
2338
2339      const float sharedDimension = `+u+`.0;
2340
2341      vec4 dot2x2ARowBCol(ivec3 rc) {
2342        vec4 result = vec4(0);
2343        for (int i = 0; i < `+u+`; i++) {
2344          vec4 a = getMatrixA(rc.x, `+c+`);
2345          vec4 b = getMatrixB(rc.x, `+l+`);
2346
2347          // These swizzled products need to be separately added.
2348          // See: https://github.com/tensorflow/tfjs/issues/1735
2349          result += (`+h[0]+" * "+f[0]+`);
2350          result += (`+h[1]+" * "+f[1]+`);
2351        }
2352        return result;
2353      }
2354
2355      void main() {
2356        ivec3 rc = getOutputCoords();
2357        vec4 result = dot2x2ARowBCol(rc);
2358
2359        `+g+`
2360
2361        `+d+`
2362
2363        setOutput(result);
2364      }
2365    `},jf=function(){function r(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode=`
2366      uniform float seed;
2367
2368      void main() {
2369        ivec2 coords = getOutputCoords();
2370        int batch = coords[0];
2371
2372        float r = random(seed);
2373        float cdf = 0.0;
2374
2375        for (int i = 0; i < `+(e-1)+`; i++) {
2376          cdf += getProbs(batch, i);
2377
2378          if (r < cdf) {
2379            setOutput(float(i));
2380            return;
2381          }
2382        }
2383
2384        // If no other event happened, last event happened.
2385        setOutput(float(`+(e-1)+`));
2386      }
2387    `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.seedLoc==null&&(e.seedLoc=n.getUniformLocation(o,"seed")),n.gl.uniform1f(e.seedLoc,t)}},r}(),Kf=function(r,t,e,n){this.variableNames=["indices"],this.outputShape=[r,t],this.userCode=`
2388      void main() {
2389        ivec2 coords = getOutputCoords();
2390        int index = round(getIndices(coords.x));
2391        setOutput(mix(float(`+n+"), float("+e+`),
2392                      float(index == coords.y)));
2393      }
2394    `},Xf=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=r;var t=r.length;if(t===0)this.userCode=`
2395        void main() {
2396          setOutput(vec4(getA(), 0., 0., 0.));
2397        }
2398      `;else{var e=Qe("rc",t),n=be(t),o=function(s,u,c){if(s===1)return"rc > "+u[0];for(var l="",h=s-2;h<s;h++)l+=c[h]+" >= "+u[h],h<s-1&&(l+="||");return l}(t,r,e),a=function(s,u,c,l){if(s===1)return"";var h=l.slice(-2);return`
2399    int r = `+h[0]+`;
2400    int c = `+h[1]+`;
2401    int rp1 = r + 1;
2402    int cp1 = c + 1;
2403
2404    bool cEdge = cp1 >= `+u+`;
2405    bool rEdge = rp1 >= `+c+`;
2406  `}(t,r[r.length-1],r[r.length-2],e),i=function(s,u){var c=s.length,l=function(h,f){for(var p=[],d=0;d<=1;d++)for(var g=0;g<=1;g++){for(var v=(d===0?"r":"rp1")+", "+(g===0?"c":"cp1"),m=2;m<h;m++)v=f[f.length-1-m]+","+v;p.push(v)}return p}(c,u);return c===1?`getA(rc),
2407            rc + 1 >= `+s[0]+` ? 0. : getA(rc + 1),
2408            0, 0`:"getA("+l[0]+`),
2409          cEdge ? 0. : getA(`+l[1]+`),
2410          rEdge ? 0. : getA(`+l[2]+`),
2411          rEdge || cEdge ? 0. : getA(`+l[3]+")"}(r,e);this.userCode=`
2412        void main() {
2413          `+n+` rc = getOutputCoords();
2414
2415          if(`+o+`) {
2416            setOutput(vec4(0));
2417          } else {
2418            `+a+`
2419
2420            setOutput(vec4(`+i+`));
2421          }
2422        }
2423      `}},$f=function(r,t,e){this.variableNames=["x"],this.outputShape=t.map(function(u,c){return u[0]+r[c]+u[1]});var n=r.length,o=be(n),a=t.map(function(u){return u[0]}).join(","),i=t.map(function(u,c){return u[0]+r[c]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=n!==1?`
2424      `+o+" start = "+o+"("+a+`);
2425      `+o+" end = "+o+"("+i+`);
2426
2427      void main() {
2428        `+o+` outC = getOutputCoords();
2429        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
2430          setOutput(float(`+e+`));
2431        } else {
2432          `+o+` coords = outC - start;
2433          setOutput(getX(`+s+`));
2434        }
2435      }
2436    `:`
2437        int start = `+a+`;
2438        int end = `+i+`;
2439
2440        void main() {
2441          int outC = getOutputCoords();
2442          if (outC < start || outC >= end) {
2443            setOutput(float(`+e+`));
2444          } else {
2445            setOutput(getX(outC - start));
2446          }
2447        }
2448      `},Yf=function(r,t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(function(v,m){return v[0]+r[m]+v[1]});for(var n=r.length,o=be(n),a=t.map(function(v){return v[0]}).join(","),i=t.map(function(v,m){return v[0]+r[m]}).join(","),s=Qe("rc",n),u=Qe("source",n),c=s[n-1]+" < "+this.outputShape[n-1],l=n===1?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[n-1]+` += 1;
2449       if(`+c+`) {
2450      `,n===1?"":`}
2451       rc = outputLoc;
2452       `+s[n-2]+` += 1;
2453       if(`+s[n-2]+" < "+this.outputShape[n-2]+") {",n===1?"":"  "+s[n-1]+` += 1;
2454         if(`+c+") {"],f=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",p="",d=0,g=n===1?2:4;d<g;d++)p+=`
2455        `+h[d]+`
2456        if (`+f+`) {
2457          result[`+d+"] = float("+e+`);
2458        } else {
2459          `+o+` source = rc - start;
2460          result[`+d+"] = getChannel(getX("+u.join()+"), "+l+`);
2461        }
2462      `;p+=n===1?"} ":"}}",this.userCode=`
2463      const `+o+" start = "+o+"("+a+`);
2464      const `+o+" end = "+o+"("+i+`);
2465
2466      void main() {
2467        `+o+` outputLoc = getOutputCoords();
2468        vec4 result = vec4(0.);
2469        `+p+`
2470        setOutput(result);
2471      }
2472    `},Oo=function(r,t,e){if(this.variableNames=["x"],t==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var n=r.filterWidth,o=r.strideHeight,a=r.strideWidth,i=r.dilationHeight,s=r.dilationWidth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,l=r.padInfo.top,h=r.padInfo.left;this.outputShape=r.outShape;var f=t==="avg",p="0.0";if(f||(p="-1.0 / 1e-20"),e)this.userCode=`
2473        const ivec2 strides = ivec2(`+o+", "+a+`);
2474        const ivec2 pads = ivec2(`+l+", "+h+`);
2475
2476        void main() {
2477          ivec4 coords = getOutputCoords();
2478          int batch = coords[0];
2479          int d = coords[3];
2480
2481          ivec2 xRCCorner = coords.yz * strides - pads;
2482          int xRCorner = xRCCorner.x;
2483          int xCCorner = xRCCorner.y;
2484
2485          // max/min x(?, ?, d) to get y(yR, yC, d).
2486          // ? = to be determined
2487          float minMaxValue = 0.0;
2488          float minMaxValueFound = 0.0;
2489          int minMaxPosition = 0;
2490          float avgValue = 0.0;
2491
2492          for (int wR = 0; wR < `+u+`;
2493              wR += `+i+`) {
2494            int xR = xRCorner + wR;
2495
2496            if (xR < 0 || xR >= `+r.inHeight+`) {
2497              continue;
2498            }
2499
2500            for (int wC = 0; wC < `+c+`;
2501                wC += `+s+`) {
2502              int xC = xCCorner + wC;
2503
2504              if (xC < 0 || xC >= `+r.inWidth+`) {
2505                continue;
2506              }
2507
2508              float value = getX(batch, xR, xC, d);
2509
2510              // If a min / max value has already been found, use it. If not,
2511              // use the current value.
2512              float currMinMaxValue = mix(
2513                  value, minMaxValue, minMaxValueFound);
2514              if (value >= currMinMaxValue) {
2515                minMaxValue = value;
2516                minMaxValueFound = 1.0;
2517                minMaxPosition = wR * `+c+` + wC;
2518              }
2519            }
2520          }
2521          setOutput(float(minMaxPosition));
2522        }
2523      `;else{var d=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(d="avgValue / count");var g=4*Math.floor(n/4),v=n%4,m=`
2524      if (`+f+`) {
2525        avgValue += dot(values, ones);
2526      } else {
2527        minMaxValue = max(values, minMaxValue);
2528      }
2529    `;this.userCode=`
2530      const ivec2 strides = ivec2(`+o+", "+a+`);
2531      const ivec2 pads = ivec2(`+l+", "+h+`);
2532      const float initializationValue = `+p+`;
2533      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2534
2535      float count = 0.0;
2536
2537      float getValue(int batch, int xR, int xC, int d) {
2538        if (xC < 0 || xC >= `+r.inWidth+`) {
2539          return initializationValue;
2540        }
2541        count += 1.0;
2542        return getX(batch, xR, xC, d);
2543      }
2544
2545      void main() {
2546        ivec4 coords = getOutputCoords();
2547        int batch = coords[0];
2548        int d = coords[3];
2549
2550        ivec2 xRCCorner = coords.yz * strides - pads;
2551        int xRCorner = xRCCorner.x;
2552        int xCCorner = xRCCorner.y;
2553
2554        // max/min x(?, ?, d) to get y(yR, yC, d).
2555        // ? = to be determined
2556        vec4 minMaxValue = vec4(`+p+`);
2557        float avgValue = 0.0;
2558        count = 0.0;
2559
2560        for (int wR = 0; wR < `+u+`;
2561            wR += `+i+`) {
2562          int xR = xRCorner + wR;
2563
2564          if (xR < 0 || xR >= `+r.inHeight+`) {
2565            continue;
2566          }
2567
2568          for (int wC = 0; wC < `+g+`; wC += 4) {
2569            int xC = xCCorner + wC * `+s+`;
2570
2571            vec4 values = vec4(
2572              getValue(batch, xR, xC, d),
2573              getValue(batch, xR, xC + `+s+`, d),
2574              getValue(batch, xR, xC + 2 * `+s+`, d),
2575              getValue(batch, xR, xC + 3 * `+s+`, d)
2576            );
2577
2578            `+m+`
2579          }
2580
2581          int xC = xCCorner + `+g+`;
2582          if (`+(v===1)+`) {
2583            vec4 values = vec4(
2584              getValue(batch, xR, xC, d),
2585              initializationValue,
2586              initializationValue,
2587              initializationValue
2588            );
2589
2590            `+m+`
2591          } else if (`+(v===2)+`) {
2592            vec4 values = vec4(
2593              getValue(batch, xR, xC, d),
2594              getValue(batch, xR, xC + `+s+`, d),
2595              initializationValue,
2596              initializationValue
2597            );
2598
2599            `+m+`
2600          } else if (`+(v===3)+`) {
2601            vec4 values = vec4(
2602              getValue(batch, xR, xC, d),
2603              getValue(batch, xR, xC + `+s+`, d),
2604              getValue(batch, xR, xC + 2 * `+s+`, d),
2605              initializationValue
2606            );
2607
2608            `+m+`
2609          }
2610        }
2611        setOutput(`+d+`);
2612      }
2613    `}},Bo=function(r,t,e){if(this.variableNames=["x"],t==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,p=r.padInfo.front,d=r.padInfo.top,g=r.padInfo.left;this.outputShape=r.outShape;var v=t==="avg",m="0.0";if(v||(m="-1.0 / 1e-20"),e)this.userCode=`
2614        const ivec3 strides =
2615            ivec3(`+o+", "+a+", "+i+`);
2616        const ivec3 pads = ivec3(`+p+", "+d+", "+g+`);
2617
2618        void main() {
2619          ivec5 coords = getOutputCoords();
2620          int batch = coords.x;
2621          int ch = coords.u;
2622
2623          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
2624          int xDCorner = xCorner.x;
2625          int xRCorner = xCorner.y;
2626          int xCCorner = xCorner.z;
2627
2628          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
2629          // ? = to be determined
2630          float minMaxValue = 0.0;
2631          float minMaxValueFound = 0.0;
2632          int minMaxPosition = 0;
2633
2634          for (int wD = 0; wD < `+l+`;
2635              wD += `+s+`) {
2636            int xD = xDCorner + wD;
2637
2638            if (xD < 0 || xD >= `+r.inDepth+`) {
2639              continue;
2640            }
2641
2642            for (int wR = 0; wR < `+h+`;
2643                wR += `+u+`) {
2644              int xR = xRCorner + wR;
2645
2646              if (xR < 0 || xR >= `+r.inHeight+`) {
2647                continue;
2648              }
2649
2650              for (int wC = 0; wC < `+f+`;
2651                  wC += `+c+`) {
2652                int xC = xCCorner + wC;
2653
2654                if (xC < 0 || xC >= `+r.inWidth+`) {
2655                  continue;
2656                }
2657
2658                float value = getX(batch, xD, xR, xC, ch);
2659
2660                // If a min / max value has already been found, use it. If not,
2661                // use the current value.
2662                float currMinMaxValue = mix(
2663                    value, minMaxValue, minMaxValueFound);
2664                if (value >= currMinMaxValue) {
2665                  minMaxValue = value;
2666                  minMaxValueFound = 1.0;
2667                  minMaxPosition =
2668                      wD * `+h+" * "+f+` +
2669                      wR * `+f+` + wC;;
2670                }
2671              }
2672            }
2673          }
2674          setOutput(float(minMaxPosition));
2675        }
2676      `;else{var x=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(x="avgValue / count");var b=4*Math.floor(n/4),y=n%4,w=`
2677      if (`+v+`) {
2678        avgValue += dot(values, ones);
2679      } else {
2680        minMaxValue = max(values, minMaxValue);
2681      }
2682    `;this.userCode=`
2683      const ivec3 strides =
2684        ivec3(`+o+", "+a+", "+i+`);
2685      const ivec3 pads = ivec3(`+p+", "+d+", "+g+`);
2686      const float initializationValue = `+m+`;
2687      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2688
2689      float count = 0.0;
2690
2691      float getValue(int batch, int xD, int xR, int xC, int ch) {
2692        if (xC < 0 || xC >= `+r.inWidth+`) {
2693          return initializationValue;
2694        }
2695        count += 1.0;
2696        return getX(batch, xD, xR, xC, ch);
2697      }
2698
2699      void main() {
2700        ivec5 coords = getOutputCoords();
2701        int batch = coords.x;
2702        int ch = coords.u;
2703
2704        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
2705        int xDCorner = xCorner.x;
2706        int xRCorner = xCorner.y;
2707        int xCCorner = xCorner.z;
2708
2709        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
2710        // ? = to be determined
2711        vec4 minMaxValue = vec4(`+m+`);
2712        float avgValue = 0.0;
2713        count = 0.0;
2714
2715        for (int wD = 0; wD < `+l+`;
2716            wD += `+s+`) {
2717          int xD = xDCorner + wD;
2718
2719          if (xD < 0 || xD >= `+r.inDepth+`) {
2720            continue;
2721          }
2722
2723          for (int wR = 0; wR < `+h+`;
2724            wR += `+u+`) {
2725            int xR = xRCorner + wR;
2726
2727            if (xR < 0 || xR >= `+r.inHeight+`) {
2728              continue;
2729            }
2730
2731            for (int wC = 0; wC < `+b+`; wC += 4) {
2732              int xC = xCCorner + wC * `+c+`;
2733
2734              vec4 values = vec4(
2735                getValue(batch, xD, xR, xC, ch),
2736                getValue(batch, xD, xR, xC + `+c+`, ch),
2737                getValue(batch, xD, xR, xC + 2 * `+c+`, ch),
2738                getValue(batch, xD, xR, xC + 3 * `+c+`, ch)
2739              );
2740
2741              `+w+`
2742            }
2743
2744            int xC = xCCorner + `+b+`;
2745            if (`+(y===1)+`) {
2746              vec4 values = vec4(
2747                getValue(batch, xD, xR, xC, ch),
2748                initializationValue,
2749                initializationValue,
2750                initializationValue
2751              );
2752
2753              `+w+`
2754            } else if (`+(y===2)+`) {
2755              vec4 values = vec4(
2756                getValue(batch, xD, xR, xC, ch),
2757                getValue(batch, xD, xR, xC + `+c+`, ch),
2758                initializationValue,
2759                initializationValue
2760              );
2761
2762              `+w+`
2763            } else if (`+(y===3)+`) {
2764              vec4 values = vec4(
2765                getValue(batch, xD, xR, xC, ch),
2766                getValue(batch, xD, xR, xC + `+c+`, ch),
2767                getValue(batch, xD, xR, xC + 2 * `+c+`, ch),
2768                initializationValue
2769              );
2770
2771              `+w+`
2772            }
2773          }
2774          setOutput(`+x+`);
2775        }
2776      }
2777    `}},Jf=function(r,t){this.variableNames=["x"];var e=r.windowSize,n=r.batchSize,o=r.inSize,a=Math.ceil(o/e);this.outputShape=[n,a];var i="0.0",s="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",s="min"):t==="max"&&(i="-1.0 / 1e-20",s="max");var u=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");var c=4*Math.floor(e/4),l=e%4,h=`
2778      if (`+(t==="sum")+`) {
2779        sumValue += dot(values, ones);
2780      } else if (`+(t==="prod")+`) {
2781        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
2782        prodValue *= tmp[0] * tmp[1];
2783      } else {
2784        minMaxValue = `+s+`(values, minMaxValue);
2785      }
2786    `,f="vec4";t==="all"?(i="1.0",h=`
2787        bool reducedAllValue = all(values);
2788        float floatedReducedAllValue = float(reducedAllValue);
2789        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
2790      `,f="bvec4"):t==="any"&&(i="0.0",h=`
2791        bool reducedAnyValue = any(values);
2792        float floatedReducedAnyValue = float(reducedAnyValue);
2793        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
2794      `,f="bvec4");var p="";o%e>0&&(p=`
2795        if (inIdx < 0 || inIdx >= `+o+`) {
2796          return initializationValue;
2797        }
2798      `),this.userCode=`
2799      const float initializationValue = `+i+`;
2800      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2801
2802      float getValue(int batch, int inIdx) {
2803        `+p+`
2804        return getX(batch, inIdx);
2805      }
2806
2807      void main() {
2808        ivec2 coords = getOutputCoords();
2809        int batch = coords[0];
2810        int outIdx = coords[1];
2811        int inOffset = outIdx * `+e+`;
2812
2813        vec4 minMaxValue = vec4(`+i+`);
2814        float prodValue = 1.0;
2815        float sumValue = 0.0;
2816        float allValue = 1.0;
2817        float anyValue = 0.0;
2818
2819        for (int i = 0; i < `+c+`; i += 4) {
2820          int inIdx = inOffset + i;
2821          `+f+" values = "+f+`(
2822            getValue(batch, inIdx),
2823            getValue(batch, inIdx + 1),
2824            getValue(batch, inIdx + 2),
2825            getValue(batch, inIdx + 3)
2826          );
2827
2828          `+h+`
2829        }
2830
2831        int inIdx = inOffset + `+c+`;
2832        if (`+(l===1)+`) {
2833          `+f+" values = "+f+`(
2834            getValue(batch, inIdx),
2835            initializationValue,
2836            initializationValue,
2837            initializationValue
2838          );
2839
2840          `+h+`
2841        } else if (`+(l===2)+`) {
2842          `+f+" values = "+f+`(
2843            getValue(batch, inIdx),
2844            getValue(batch, inIdx + 1),
2845            initializationValue,
2846            initializationValue
2847          );
2848
2849          `+h+`
2850        } else if (`+(l===3)+`) {
2851          `+f+" values = "+f+`(
2852            getValue(batch, inIdx),
2853            getValue(batch, inIdx + 1),
2854            getValue(batch, inIdx + 2),
2855            initializationValue
2856          );
2857
2858          `+h+`
2859        }
2860        setOutput(`+u+`);
2861      }
2862    `},Qf=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var e="",n=0;n<4;n++){var o="thisRC = rc;";n%2==1&&(o+="thisRC.z += 1;"),n>1&&(o+="thisRC.y += 1;"),e+=`
2863        `+o+`
2864        `+(n>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+`
2865          int flatIndex = getFlatIndex(thisRC);
2866
2867          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
2868          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
2869
2870          result[`+n+`] =
2871            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
2872        `+(n>0?"}":"")+`
2873      `}this.userCode=`
2874      
2875    ivec3 inputCoordsFromReshapedOutCoords(int index) {
2876      `+fn(["r","c","d"],t)+`
2877      return ivec3(r, c, d);
2878    }
2879  
2880      `+Ta(r)+`
2881
2882      void main() {
2883        ivec3 rc = getOutputCoords();
2884
2885        vec4 result = vec4(0.);
2886
2887        ivec3 thisRC;
2888        int rows = `+r[1]+`;
2889        int cols = `+r[2]+`;
2890
2891        `+e+`
2892
2893        setOutput(result);
2894      }
2895    `},Zf=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?o-1:o,e&&u>1?a-1:a],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],p=1/h,d=1/f,g=2*Math.ceil(p)+2,v=2*Math.ceil(d)+2;this.userCode=`
2896      void main() {
2897        ivec4 coords = getOutputCoords();
2898        int b = coords[0];
2899        int d = coords[3];
2900        int r = coords[1];
2901        int c = coords[2];
2902
2903        float accumulator = 0.0;
2904
2905        const float heightScale = float(`+h+`);
2906        const float widthScale = float(`+f+`);
2907
2908        const float invHeightScale = float(`+p+`);
2909        const float invWidthScale = float(`+d+`);
2910
2911        const int winHeight = int(`+g+`);
2912        const int winWidth = int(`+v+`);
2913
2914        // Compute bounds for where in dy we will look
2915        float startRLerp = floor(float(r) * invHeightScale);
2916        int startDyR = int(startRLerp - float(winHeight / 2));
2917
2918        float startCLerp = floor(float(c) * invWidthScale);
2919        int startDyC = int(startCLerp - float(winWidth / 2));
2920
2921        // Loop over dy
2922        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
2923          int dyR = dyROffset + startDyR;
2924
2925          // Guard against the window exceeding the bounds of dy
2926          if (dyR < 0 || dyR >= `+s+`) {
2927            continue;
2928          }
2929
2930          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
2931            int dyC = dyCOffset + startDyC;
2932
2933            // Guard against the window exceeding the bounds of dy
2934            if (dyC < 0 || dyC >= `+u+`) {
2935              continue;
2936            }
2937
2938            float dxR = float(dyR) * heightScale;
2939            int topDxRIndex = int(floor(dxR));
2940            int bottomDxRIndex = int(min(ceil(dxR), `+(o-1)+`.0));
2941            float dxRLerp = dxR - float(topDxRIndex);
2942            float inverseDxRLerp = 1.0 - dxRLerp;
2943
2944            float dxC = float(dyC) * widthScale;
2945            int leftDxCIndex = int(floor(dxC));
2946            int rightDxCIndex = int(min(ceil(dxC), `+(a-1)+`.0));
2947            float dxCLerp = dxC - float(leftDxCIndex);
2948            float inverseDxCLerp = 1.0 - dxCLerp;
2949
2950            if (r == topDxRIndex && c == leftDxCIndex) {
2951              // topLeft
2952              accumulator +=
2953                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
2954            }
2955
2956            if (r == topDxRIndex && c == rightDxCIndex) {
2957              // topRight
2958              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
2959            }
2960
2961            if (r == bottomDxRIndex && c == leftDxCIndex) {
2962              // bottomLeft
2963              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
2964            }
2965
2966            if (r == bottomDxRIndex && c == rightDxCIndex) {
2967              // bottomRight
2968              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
2969            }
2970          }
2971        }
2972        // End loop over dy
2973
2974        setOutput(accumulator);
2975      }
2976    `},ep=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n&&e>1?e-1:e];this.userCode=`
2977      const vec2 effectiveInputOverOutputRatioRC = vec2(
2978          `+u[0]/c[0]+`,
2979          `+u[1]/c[1]+`);
2980      const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.0);
2981
2982      void main() {
2983        ivec4 coords = getOutputCoords();
2984        int b = coords[0];
2985        int d = coords[3];
2986        ivec2 yRC = coords.yz;
2987
2988        // Fractional source index.
2989        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
2990
2991        // Compute the four integer indices.
2992        ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
2993        ivec2 sourceCeilRC = ivec2(
2994          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2995
2996        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
2997        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
2998        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
2999        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
3000
3001        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
3002
3003        float top = topLeft + (topRight - topLeft) * fracRC.y;
3004        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
3005        float newValue = top + (bottom - top) * fracRC.x;
3006
3007        setOutput(newValue);
3008      }
3009    `},tp=function(r,t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n
vendor: 3,103 bytes, lines 3009-3086
3009&&e>1?e-1:e];this.userCode=`
3010      const vec3 effectiveInputOverOutputRatioRC = vec3(
3011          `+u[0]/c[0]+`,
3012          `+u[1]/c[1]+`,
3013          `+u[1]/c[1]+`);
3014      const vec3 inputShapeRC = vec3(`+a+".0, "+i+`.0,
3015                                     `+i+`.0);
3016
3017      float getAValue(int b, int r, int c, int d) {
3018        return getChannel(getA(b, r, c, d), vec2(c, d));
3019      }
3020
3021      void main() {
3022        ivec4 coords = getOutputCoords();
3023        int b = coords[0];
3024        int d = coords[3];
3025        // Calculate values for next column in yRC.z.
3026        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
3027
3028        // Fractional source index.
3029        vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
3030
3031        // Compute the four integer indices.
3032        ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
3033        ivec3 sourceCeilRC = ivec3(
3034          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
3035
3036        // Should we calculate next column and row elements in 2x2 packed cell.
3037        bool hasNextCol = d < `+(s-1)+`;
3038        bool hasNextRow = coords.z < `+(e-1)+`;
3039
3040        // In parallel, construct four corners for all four components in
3041        // packed 2x2 cell.
3042        vec4 topLeft = vec4(
3043          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
3044          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
3045                     : 0.0,
3046          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
3047                     : 0.0,
3048          (hasNextRow && hasNextCol) ?
3049            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
3050
3051        vec4 bottomLeft = vec4(
3052          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
3053          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
3054                     : 0.0,
3055          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
3056                     : 0.0,
3057          (hasNextRow && hasNextCol) ?
3058            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
3059
3060        vec4 topRight = vec4(
3061          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
3062          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
3063                     : 0.0,
3064          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
3065                     : 0.0,
3066          (hasNextRow && hasNextCol) ?
3067            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
3068
3069        vec4 bottomRight = vec4(
3070          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
3071          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
3072                     : 0.0,
3073          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
3074                     : 0.0,
3075          (hasNextRow && hasNextCol) ?
3076            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
3077
3078        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
3079
3080        vec4 top = mix(topLeft, topRight, fracRC.yyzz);
3081        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
3082        vec4 newValue = mix(top, bottom, fracRC.x);
3083
3084        setOutput(newValue);
3085      }
3086    `},
vendor: 6,055 bytes, lines 3086-3223
3086np=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?o-1:o,e&&u>1?a-1:a],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],p=1/h,d=1/f,g=2*Math.ceil(p)+2,v=2*Math.ceil(d)+2;this.userCode=`
3087      void main() {
3088        ivec4 coords = getOutputCoords();
3089        int b = coords[0];
3090        int d = coords[3];
3091        int r = coords[1];
3092        int c = coords[2];
3093
3094        float accumulator = 0.0;
3095
3096        const float heightScale = float(`+h+`);
3097        const float widthScale = float(`+f+`);
3098
3099        const float invHeightScale = float(`+p+`);
3100        const float invWidthScale = float(`+d+`);
3101
3102        const int winHeight = int(`+g+`);
3103        const int winWidth = int(`+v+`);
3104
3105        // Compute bounds for where in dy we will look
3106        float startRLerp = floor(float(r) * invHeightScale);
3107        int startDyR = int(floor(startRLerp - float(winHeight / 2)));
3108
3109        float startCLerp = floor(float(c) * invWidthScale);
3110        int startDyC = int(floor(startCLerp - float(winWidth / 2)));
3111
3112        // Loop over dy
3113        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
3114          int dyR = dyROffset + startDyR;
3115
3116          // Guard against the window exceeding the bounds of dy
3117          if (dyR < 0 || dyR >= `+s+`) {
3118            continue;
3119          }
3120
3121          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
3122            int dyC = dyCOffset + startDyC;
3123
3124            // Guard against the window exceeding the bounds of dy
3125            if (dyC < 0 || dyC >= `+u+`) {
3126              continue;
3127            }
3128
3129            float sourceFracRow =
3130              float(`+c[0]+`) *
3131                (float(dyR) / float(`+l[0]+`));
3132
3133            float sourceFracCol =
3134                float(`+c[1]+`) *
3135                  (float(dyC) / float(`+l[1]+`));
3136
3137            int sourceNearestRow = int(min(
3138                float(int(`+o+`) - 1),
3139                `+e+` ? float(round(sourceFracRow)) :
3140                                  float(floor(sourceFracRow))));
3141
3142            int sourceNearestCol = int(min(
3143                float(int(`+a+`) - 1),
3144                `+e+` ? float(round(sourceFracCol)) :
3145                                  float(floor(sourceFracCol))));
3146
3147            if (r == sourceNearestRow && c == sourceNearestCol) {
3148              accumulator += getDy(b, dyR, dyC, d);
3149            }
3150          }
3151        }
3152        // End loop over dy
3153
3154        setOutput(accumulator);
3155      }
3156    `},rp=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n&&e>1?e-1:e],l=n?"0.5":"0.0";this.userCode=`
3157      const vec2 effectiveInputOverOutputRatioRC = vec2(
3158          `+u[0]/c[0]+`,
3159          `+u[1]/c[1]+`);
3160      const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.0);
3161
3162      void main() {
3163        ivec4 coords = getOutputCoords();
3164        int b = coords[0];
3165        int d = coords[3];
3166        ivec2 yRC = coords.yz;
3167
3168        // Fractional source index.
3169        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
3170
3171        // Compute the coordinators of nearest neighbor point.
3172        ivec2 sourceNearestRC = ivec2(
3173          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + `+l+`)));
3174
3175        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
3176
3177        setOutput(newValue);
3178      }
3179    `},op=function(r,t){this.variableNames=["x"];var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=r,e!==1){var n=r.map(function(a,i){return function(s){return t.indexOf(s)!==-1&&r[s]!==1?r[s]+" - coords["+s+"] - 1":"coords["+s+"]"}(i)}).join(","),o=be(e);this.userCode=`
3180      void main() {
3181        `+o+` coords = getOutputCoords();
3182        setOutput(getX(`+n+`));
3183      }
3184    `}else this.userCode=`
3185        void main() {
3186          int coord = getOutputCoords();
3187          setOutput(getX(`+r[0]+` - coord - 1));
3188        }
3189      `},ap=function(r,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");this.outputShape=r;var n=Qe("rc",e),o=n[e-1]+" + 1 < "+this.outputShape[e-1],a=n[e-2]+" + 1 < "+this.outputShape[e-2],i=be(e);function s(u){var c=r.map(function(l,h){return function(f,p){return t.indexOf(f)!==-1&&r[f]!==1?r[f]+" - "+p[f]+" - 1":""+p[f]}(h,u)});return"getChannel(getX("+c.join(",")+"), vec2("+c.slice(-2).join(",")+"))"}this.userCode=e===1?`
3190        void main(){
3191          int rc = getOutputCoords();
3192          vec4 result = vec4(0.);
3193          result.r = getChannel(getX(`+r[0]+` - rc - 1),
3194            `+r[0]+` - rc - 1);
3195          if(`+o+`){
3196              result.g = getChannel(getX(`+r[0]+` - (rc  + 1) - 1),
3197                `+r[0]+` - (rc  + 1) - 1);
3198          }
3199          setOutput(result);
3200        }
3201      `:`
3202        void main() {
3203          `+i+` rc = getOutputCoords();
3204          vec4 result = vec4(0.);
3205          result.r = `+function(u){return s(u)}(n.slice())+`;
3206          if(`+o+`){
3207            result.g = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",s(u)}(n.slice())+`;
3208          }
3209          if(`+a+`) {
3210            result.b = `+function(u){return u[e-2]="("+u[e-2]+" + 1)",s(u)}(n.slice())+`;
3211            if(`+o+`) {
3212              result.a = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",u[e-2]="("+u[e-2]+" + 1)",s(u)}(n.slice())+`;
3213            }
3214          }
3215          setOutput(result);
3216        }
3217    `},qi=function(r,t,e,n,o,a,i){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=be(o.length),u=be(a.length),c="";e===1?c="i":e===2&&(c="i, j");var l="getIndices("+c+")",h="";n===1?h="i":n===2&&(h="i, coords[1]");var f="getUpdates("+h+")",p=t>1?"strides[j]":"strides";this.userCode=`
3218        `+s+" strides = "+s+"("+o+`);
3219
3220        void main() {
3221          `+u+` coords = getOutputCoords();
3222          float sum = 0.0;
3223          bool found = false;
3224          for (int i = 0; i < `+r+`; i++) {
3225            int flattenedIndex = 0;
3226            for (int j = 0; j < `+t+`; j++) {
3227              int index = round(`+l+`);
3228              flattenedIndex += index * `+p+`;
3229            }
3230            if (flattenedIndex == coords[0]) {
3231              sum += `+f+`;
3232              found = true;
3233            }
3234          }
3235          setOutput(mix(getDefaultValue(), sum, float(found)));
3236        }
3237      `},ip=function(r,t){this.variableNames=["x","segmentIds"];var e=r.windowSize,n=r.batchSize,o=r.inSize,a=r.numSegments,i=a*Math.ceil(o/e);this.outputShape=[n,i];var s=4*Math.floor(e/4),u=e%4,c=`
3238        sumValue += dot(values, segFilter);
3239    `,l="";o%e>0&&(l=`
3240        if (inIdx < 0 || inIdx >= `+o+`) {
3241          return initializationValue;
3242        }
3243      `);var h="";o%e>0&&(h=`
3244        if (inIdx < 0 || inIdx >= `+o+`) {
3245          return -1.0;
3246        }
3247      `),this.userCode=`
3248      const float initializationValue = 0.0;
3249
3250      float getValue(int batch, int inIdx) {
3251        `+l+`
3252        return getX(batch, inIdx);
3253      }
3254
3255      float getSegmentIdAtIndex(int inIdx) {
3256        `+h+`
3257        return getSegmentIds(inIdx);
3258      }
3259
3260      void main() {
3261        ivec2 coords = getOutputCoords();
3262        int batch = coords[0];
3263        int outIdx = coords[1];
3264        int inOffset = int(floor(float(outIdx) / float(
3265          `+a+")) * float("+e+`));
3266        int currentSeg = int(mod(float(outIdx), float(`+a+`)));
3267
3268        float sumValue = 0.0;
3269
3270        for (int i = 0; i < `+s+`; i += 4) {
3271          int inIdx = inOffset + i;
3272          vec4 values = vec4(
3273            getValue(batch, inIdx),
3274            getValue(batch, inIdx + 1),
3275            getValue(batch, inIdx + 2),
3276            getValue(batch, inIdx + 3)
3277          );
3278
3279          vec4 segFilter = vec4(
3280            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
3281            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
3282            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
3283            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
3284          );
3285
3286          `+c+`
3287        }
3288
3289        int inIdx = inOffset + `+s+`;
3290        if (`+(u===1)+`) {
3291          vec4 values = vec4(
3292            getValue(batch, inIdx),
3293            initializationValue,
3294            initializationValue,
3295            initializationValue
3296          );
3297
3298          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
3299
3300          vec4 segFilter = vec4(
3301            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
3302            0,
3303            0,
3304            0
3305          );
3306
3307          `+c+`
3308        } else if (`+(u===2)+`) {
3309          vec4 values = vec4(
3310            getValue(batch, inIdx),
3311            getValue(batch, inIdx + 1),
3312            initializationValue,
3313            initializationValue
3314          );
3315
3316          vec4 segFilter = vec4(
3317            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
3318            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
3319              0,
3320              0
3321          );
3322
3323          `+c+`
3324        } else if (`+(u===3)+`) {
3325          vec4 values = vec4(
3326            getValue(batch, inIdx),
3327            getValue(batch, inIdx + 1),
3328            getValue(batch, inIdx + 2),
3329            initializationValue
3330          );
3331
3332          vec4 segFilter = vec4(
3333            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
3334            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
3335            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
3336            0
3337          );
3338
3339          `+c+`
3340        }
3341        setOutput(sumValue);
3342      }
3343    `},sp=function(r,t,e){var n,o;if(this.variableNames=["c","a","b"],this.outputShape=t,e>4)throw Error("Where for rank "+e+" is not yet supported");if(e===1)o="resRC",n="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<t.length;u++)s.push(""+a[u]),u<r&&i.push(""+a[u]);n=i.join(),o=s.join()}var c=be(e);this.userCode=`
3344      void main() {
3345        `+c+` resRC = getOutputCoords();
3346        float cVal = getC(`+n+`);
3347        if (cVal >= 1.0) {
3348          setOutput(getA(`+o+`));
3349        } else {
3350          setOutput(getB(`+o+`));
3351        }
3352      }
3353    `},up=function(){function r(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=be(this.rank),o="uniform int start["+this.rank+"];",a=function(i){if(i===1)return"sourceLoc";if(i<=6)return Lo.slice(0,i).map(function(s){return"sourceLoc."+s}).join(",");throw Error("Slicing for rank "+i+" is not yet supported")}(this.rank);e=`
3354        `+n+` sourceLoc;
3355        `+n+` coords = getOutputCoords();
3356        `+t.map(function(i,s){return"sourceLoc."+Lo[s]+" = start["+s+"] + coords."+Lo[s]+";"}).join(`
3357`)+`
3358      `,this.userCode=`
3359      `+o+`
3360      void main() {
3361        `+e+`
3362        setOutput(getSource(`+a+`));
3363      }
3364    `}return r.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,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r}(),Lo=["x","y","z","w","u","v"],cp=function(){function r(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=be(this.rank),n=Qe("coords",this.rank),o=Qe("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+o.slice(-2).join()+")",i="getChannel(getSource("+o.join()+"), "+a+")",s=`
3365      result.x = `+i+`;
3366      if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) {
3367        ++`+o[this.rank-1]+`;
3368        result.y = `+i+`;
3369        --`+o[this.rank-1]+`;
3370      }
3371    `,u=this.rank===1?"":`
3372      --`+n[this.rank-1]+`;
3373      if (++`+n[this.rank-2]+" < "+t[this.rank-2]+`) {
3374        ++`+o[this.rank-2]+`;
3375        result.z = `+i+`;
3376        if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) {
3377          ++`+o[this.rank-1]+`;
3378          result.w = `+i+`;
3379        }
3380      }
3381    `,c=this.rank<=4?`sourceLoc = coords +
3382            `+e+"("+t.map(function(l,h){return"start["+h+"]"}).join()+");":t.map(function(l,h){return o[h]+" = "+n[h]+" + start["+h+"];"}).join(`
3383`);this.userCode=`
3384      uniform int start[`+this.rank+`];
3385      void main() {
3386        `+e+` coords = getOutputCoords();
3387        `+e+` sourceLoc;
3388        `+c+`
3389        vec4 result = vec4(0.);
3390        `+s+`
3391        `+u+`
3392        setOutput(result);
3393      }
3394    `}return r.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,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r}(),lp=function(r,t,e){this.variableNames=["x"],this.outputShape=e;var n=e.length,o=be(e.length),a=be(e.length),i="";if(n===1)i="coords * strides + begin";else{var s=0;i=e.map(function(u,c){return s++,e.length===1?"coords * strides["+c+"] + begin["+c+"]":"coords["+(s-1)+"] * strides["+c+"] + begin["+c+"]"}).join(",")}this.userCode=`
3395      `+o+" begin = "+o+"("+r+`);
3396      `+o+" strides = "+o+"("+t+`);
3397
3398      void main() {
3399        `+a+` coords = getOutputCoords();
3400        setOutput(getX(`+i+`));
3401      }
3402    `},hp=function(){function r(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return r.prototype.acquireTexture=function(t,e,n){var o,a=ji(e,n),i=Ki(t,a,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 s=this.freeTextures[i].shift();return this.usedTextures[i].push(s),s}return this.numUsedTextures++,this.log(),a===at.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):a===at.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):a===at.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):a===at.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):a===at.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(o),o},r.prototype.releaseTexture=function(t,e,n,o){if(this.freeTextures!=null){var a=Ki(e,ji(n,o),o);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],s=i.indexOf(t);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(s,1),this.log()}},r.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},r.prototype.getNumUsedTextures=function(){return this.numUsedTextures},r.prototype.getNumFreeTextures=function(){return this.numFreeTextures},r.prototype.dispose=function(){var t=this;if(this.freeTextures!=null){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(n){t.gpgpu.deleteMatrixTexture(n)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(o){t.gpgpu.deleteMatrixTexture(o)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},r}();function ji(r,t){if(r===it.UPLOAD)return at.PACKED_2X2_FLOAT32;if(r===it.RENDER||r==null)return function(e){return M().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?at.PACKED_2X2_FLOAT32:at.UNPACKED_FLOAT32:e?at.PACKED_2X2_FLOAT16:at.UNPACKED_FLOAT16}(t);if(r===it.DOWNLOAD||r===it.PIXELS)return at.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+r)}function Ki(r,t,e){return r[0]+"_"+r[1]+"_"+t+"_"+e}var fp=function(r,t){this.variableNames=["A"];for(var e=new Array(r.length),n=0;n<e.length;n++)e[n]=r[n]*t[n];this.outputShape=e,this.rank=e.length;var o=be(this.rank),a=function(i){var s=i.length;if(s>5)throw Error("Tile for rank "+s+" is not yet supported");if(s===1)return"imod(resRC, "+i[0]+")";for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],c=[],l=0;l<i.length;l++)c.push("imod("+u[l]+", "+i[l]+")");return c.join()}(r);this.userCode=`
3403      void main() {
3404        `+o+` resRC = getOutputCoords();
3405        setOutput(getA(`+a+`));
3406      }
3407    `},pp=function(r,t){this.variableNames=["A"];for(var e=new Array(r.length),n=0;n<e.length;n++)e[n]=r[t[n]];this.outputShape=e,this.rank=e.length;var o=be(this.rank),a=function(i){var s=i.length;if(s>6)throw Error("Transpose for rank "+s+" is not yet supported");for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],c=new Array(s),l=0;l<i.length;l++)c[i[l]]=u[l];return c.join()}(t);this.userCode=`
3408    void main() {
3409      `+o+` resRC = getOutputCoords();
3410      setOutput(getA(`+a+`));
3411    }
3412    `},dp=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var e=new Array(r.length),n=0;n<e.length;n++)e[n]=r[t[n]];if(this.outputShape=e,this.rank=e.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=be(this.rank),a=su("rc",this.rank),i=new Array(this.rank);for(n=0;n<t.length;n++)i[t[n]]=a[n];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+e[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode=`
3413    void main() {
3414      `+o+` rc = getOutputCoords();
3415      vec4 result = vec4(0.);
3416      result[0] = `+c+`;
3417      if(`+u+`) {
3418        result[1] = `+c+`;
3419      }
3420      --`+a[this.rank-1]+`;
3421      if(++`+a[this.rank-2]+" < "+e[this.rank-2]+`) {
3422        result[2] = `+c+`;
3423        if(`+u+`) {
3424          result[3] = `+c+`;
3425        }
3426      }
3427      setOutput(result);
3428    }
3429    `},Na=1.7580993408473768,Fa=1.0507009873554805,ae=function(r,t){this.variableNames=["A"],this.outputShape=r,this.userCode=`
3430      float unaryOperation(float x) {
3431        `+t+`
3432      }
3433
3434      void main() {
3435        float x = getAAtOutCoords();
3436        float y = unaryOperation(x);
3437
3438        setOutput(y);
3439      }
3440    `},yt="if (isnan(x)) return x;",vp="return x;",Xi="return abs(x);",fu=yt+`
3441  return (x < 0.0) ? 0.0 : x;
3442`,pu=yt+`
3443  return (x < 0.0) ? 0.0 : min(6.0, x);
3444`,du="return (x >= 0.0) ? x : (exp(x) - 1.0);",mp=`
3445  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
3446  // see: https://arxiv.org/abs/1706.02515
3447  float scaleAlpha = `+Na+`;
3448  float scale = `+Fa+`;
3449  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
3450`,$i="return -x;",Yi="return ceil(x);",Ji="return floor(x);",Qi="return exp(x);",Zi="return exp(x) - 1.0;",gp=yt+`
3451  return sin(x);
3452`,yp=yt+`
3453  return cos(x);
3454`,xp=yt+`
3455  if (abs(x) > 1.) {
3456    return NAN;
3457  }
3458  return asin(x);
3459`,bp=yt+`
3460  if (abs(x) > 1.) {
3461    return NAN;
3462  }
3463  return acos(x);
3464`,wp=yt+`
3465  return atan(x);
3466`,Cp=yt+"return log(x + sqrt(x * x + 1.0));",_p=yt+`
3467  if (x < 1.0) return NAN;
3468  return log(x + sqrt(x * x - 1.0));`,Ep=yt+`
3469  if ((x < -1.0) || (x > 1.0)) return NAN;
3470  return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,_r="return x;",Ip="return x;",vu=`
3471  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
3472  bvec4 isNaN = isnan(x);
3473
3474  result.r = isNaN.r ? x.r : result.r;
3475  result.g = isNaN.g ? x.g : result.g;
3476  result.b = isNaN.b ? x.b : result.b;
3477  result.a = isNaN.a ? x.a : result.a;
3478
3479  return result;
3480`,mu=`
3481  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
3482  bvec4 isNaN = isnan(x);
3483
3484  result.r = isNaN.r ? x.r : result.r;
3485  result.g = isNaN.g ? x.g : result.g;
3486  result.b = isNaN.b ? x.b : result.b;
3487  result.a = isNaN.a ? x.a : result.a;
3488
3489  return result;
3490`,gu=`
3491  vec4 result;
3492
3493  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
3494  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
3495  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
3496  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
3497
3498  return result;
3499`,Jn=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.userCode=`
3500      vec4 unaryOperation(vec4 x) {
3501        `+t+`
3502      }
3503
3504      void main() {
3505        vec4 x = getAAtOutCoords();
3506        vec4 y = unaryOperation(x);
3507
3508        setOutput(y);
3509      }
3510    `},Rp=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=r;var t=r.length,e=Qe("rc",t),n=be(t),o=function(s,u){if(s===1)return"rc";for(var c="",l=0;l<s;l++)c+=u[l],l<s-1&&(c+=",");return c}(t,e),a=e.slice(-2),i=t<=1?"rc":"vec2("+a.join(",")+")";this.userCode=`
3511      void main() {
3512        `+n+` rc = getOutputCoords();
3513        vec4 packedInput = getA(`+o+`);
3514
3515        setOutput(getChannel(packedInput, `+i+`));
3516      }
3517    `},Er={};function Ir(r,t){if(t===void 0&&(t=!1),r==="linear")return t?Ip:vp;if(r==="relu")return t?vu:fu;if(r==="elu")return t?gu:du;if(r==="relu6")return t?mu:pu;if(r==="prelu")return t?hu:lu;throw new Error("Activation "+r+" has not been implemented for the WebGL backend.")}var kp=600,Sp=function(r){function t(e){var n,o=r.call(this)||this;if(o.pendingRead=new WeakMap,o.pendingDisposal=new WeakSet,o.dataRefCount=new WeakMap,o.numBytesInGPU=0,o.uploadWaitMs=0,o.downloadWaitMs=0,o.warnedAboutMemory=!1,o.pendingDeletes=0,o.disposed=!1,!M().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){var a=Nt(M().getNumber("WEBGL_VERSION"));o.binaryCache=((n=M().getNumber("WEBGL_VERSION"))in Er||(Er[n]={}),Er[n]),o.gpgpu=new Wf(a),o.canvas=a.canvas,o.gpgpuCreatedLocally=!0}else o.gpgpu=e,o.binaryCache={},o.gpgpuCreatedLocally=!1,o.canvas=e.gl.canvas;return o.textureManager=new hp(o.gpgpu),o.numMBBeforeWarning=M().global.screen==null?1024:M().global.screen.height*M().global.screen.width*window.devicePixelRatio*kp/1024/1024,o.texData=new Qs(o,T),o}return gt(t,r),t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,n,o){if(M().getBool("DEBUG")&&this.checkNumericalProblems(e),o==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var a={};return this.texData.set(a,{shape:n,dtype:o,values:e,usage:it.UPLOAD}),a},t.prototype.move=function(e,n,o,a){if(M().getBool("DEBUG")&&this.checkNumericalProblems(n),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:o,dtype:a,values:n,usage:it.UPLOAD})},t.prototype.readSync=function(e){var n=this.texData.get(e),o=n.values,a=n.dtype,i=n.complexTensors,s=n.slice,u=n.shape,c=n.isPacked;if(s!=null){var l=void 0;l=c?new Jn(u,_r):new ae(u,_r);var h=this.runWebGLProgram(l,[{dataId:e,shape:u,dtype:a}],a),f=this.readSync(h.dataId);return this.disposeData(h.dataId),f}if(o!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return o;var p,d,g=this.activeTimers!=null;return g&&(p=Et()),a==="complex64"?d=la(i.real.dataSync(),i.imag.dataSync()):d=this.getValuesFromTexture(e),g&&(this.downloadWaitMs+=Et()-p),this.convertAndCacheOnCPU(e,d)},t.prototype.read=function(e){return X(this,void 0,void 0,function(){var n,o,a,i,s,u,c,l,h,f,p,d,g,v,m,x,b,y,w,C,S,k;return $(this,function(I){switch(I.label){case 0:if(this.pendingRead.has(e))return n=this.pendingRead.get(e),[2,new Promise(function(R){return n.push(R)})];if(o=this.texData.get(e),a=o.values,i=o.shape,s=o.slice,u=o.dtype,c=o.complexTensors,l=o.isPacked,s!=null)return h=void 0,h=l?new Jn(i,_r):new ae(i,_r),f=this.runWebGLProgram(h,[{dataId:e,shape:i,dtype:u}],u),p=this.read(f.dataId),this.disposeData(f.dataId),[2,p];if(a!=null)return[2,this.convertAndCacheOnCPU(e)];if(!M().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&M().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return d=null,u!=="complex64"&&M().get("WEBGL_BUFFER_SUPPORTED")&&(g=this.decode(e),v=this.texData.get(g.dataId),d=(k=this.gpgpu).createBufferFromTexture.apply(k,[v.texture].concat(Qn(i)))),this.pendingRead.set(e,[]),u==="complex64"?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:I.sent(),I.label=2;case 2:return u!=="complex64"?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return x=I.sent(),b=x[0],y=x[1],m=la(b,y),[3,5];case 4:d==null?m=this.getValuesFromTexture(e):(w=Y(i),m=this.gpgpu.downloadFloat32MatrixFromBuffer(d,w)),I.label=5;case 5:return g!=null&&this.disposeData(g.dataId),C=this.convertAndCacheOnCPU(e,m),S=this.pendingRead.get(e),this.pendingRead.delete(e),S.forEac
vendor: 22,744 bytes, lines 3517-3660
3517h(function(R){return R(C)}),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,C]}})})},t.prototype.checkNumericalProblems=function(e){if(e!=null)for(var n=0;n<e.length;n++){var o=e[n];if(!vl(o))throw M().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error("The value "+o+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'"):Error("The value "+o+" cannot be represented on this device.")}},t.prototype.getValuesFromTexture=function(e){var n,o=this.texData.get(e),a=o.shape,i=o.dtype,s=o.isPacked,u=Y(a);if(M().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var c=this.decode(e),l=this.texData.get(c.dataId),h=(n=this.gpgpu).downloadMatrixFromPackedTexture.apply(n,[l.texture].concat(Qn(a))).subarray(0,u);return this.disposeData(c.dataId),h}var f=M().getBool("WEBGL_PACK")&&s===!0,p=f?To(a):a,d=f?new vf(p):new df(p),g=this.runWebGLProgram(d,[{shape:p,dtype:i,dataId:e}],"float32"),v=this.texData.get(g.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,u);return this.disposeData(g.dataId),m},t.prototype.time=function(e){return X(this,void 0,void 0,function(){var n,o,a,i,s,u,c;return $(this,function(l){switch(l.label){case 0:return n=this.activeTimers,o=[],a=!1,this.programTimersStack==null?(this.programTimersStack=o,a=!0):this.activeTimers.push(o),this.activeTimers=o,e(),i=zn(this.activeTimers.map(function(h){return h.query})).filter(function(h){return h!=null}),s=zn(this.activeTimers.map(function(h){return h.name})).filter(function(h){return h!=null}),this.activeTimers=n,a&&(this.programTimersStack=null),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(i)]:[3,2];case 1:return c=l.sent(),u.kernelMs=$c(c),u.getExtraProfileInfo=function(){return c.map(function(h,f){return{name:s[f],ms:h}}).map(function(h){return h.name+": "+h.ms}).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},l.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Et(),endMs:null}},t.prototype.endTimer=function(e){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Et(),e)},t.prototype.getQueryTime=function(e){return X(this,void 0,void 0,function(){var n;return $(this,function(o){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]})})},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var n=this.texData.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var n=this.texData.get(e),o=n.texture,a=n.dtype,i=n.texShape,s=n.usage,u=n.isPacked,c=n.slice,l=c&&c.origDataId||e,h=this.dataRefCount.get(l);h>1?this.dataRefCount.set(l,h-1):(this.dataRefCount.delete(l),o!=null&&(this.numBytesInGPU-=this.computeBytes(i,a),this.textureManager.releaseTexture(o,i,s,u)));var f=this.texData.get(e);f.texture=null,f.texShape=null,f.isPacked=!1,f.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return M().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=T.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,n){var o=this;return n===void 0&&(n=128),this.getCPUBackend()!=null&&e.every(function(a){return o.texData.get(a.dataId).texture==null&&a.size<n})},t.prototype.getGPGPUContext=function(){return this.gpgpu},t.prototype.complex=function(e,n){var o=this.makeOutput(e.shape,"complex64");return this.texData.get(o.dataId).complexTensors={real:T.keep(e.clone()),imag:T.keep(n.clone())},o},t.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,n,o){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,n,o);if(Y(o)===0)return Ge([],o,e.dtype);var a=this.texData.get(e.dataId).isPacked,i=Ys(e.shape,n,o);if(a||!i){var s=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cp(o):new up(o),u=s.getCustomSetupFunc(n);return this.compileAndRun(s,[e],null,u)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,n,o)},t.prototype.shallowSlice=function(e,n,o){var a=this.texData.get(e.dataId),i=this.makeOutput(o,e.dtype),s=this.texData.get(i.dataId);Object.assign(s,a),s.shape=o,s.dtype=e.dtype;var u=Js(n,e.strides);a.slice&&(u+=a.slice.flatOffset),s.slice={flatOffset:u,origDataId:a.slice&&a.slice.origDataId||e.dataId};var c=this.dataRefCount.get(s.slice.origDataId)||1;return this.dataRefCount.set(s.slice.origDataId,c+1),i},t.prototype.stridedSlice=function(e,n,o,a){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,n,o,a);var i=Ra(n,o,a);if(i.some(function(u){return u===0}))return Ge([],i);var s=new lp(n,a,i);return this.compileAndRun(s,[e])},t.prototype.reverse=function(e,n){var o=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ap(e.shape,n):new op(e.shape,n);return this.compileAndRun(o,[e])},t.prototype.concat=function(e,n){if(e[0].dtype==="complex64"){var o=e.map(function(p){return ht(p)}),a=e.map(function(p){return Rt(p)});return Ve(this.concat(o,n),this.concat(a,n))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,n);if(e.length===1)return e[0];if(e.length>M().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),s=this.concat(e.slice(0,i),n),u=this.concat(e.slice(i),n);return this.concat([s,u],n)}if(M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var c=new Zh(e.map(function(p){return p.shape}),n);return this.compileAndRun(c,e)}var l=Hn(e.map(function(p){return p.shape}),n),h=e.map(function(p){return p.as2D(-1,Y(p.shape.slice(n)))}),f=new Qh(h.map(function(p){return p.shape}));return this.compileAndRun(f,h).reshape(l)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,$i,e.dtype);var n=new ae(e.shape,$i);return this.compileAndRun(n,[e])},t.prototype.batchMatMul=function(e,n,o,a){var i=o?e.shape[2]:e.shape[1],s=a?n.shape[1]:n.shape[2],u=o?e.shape[1]:e.shape[2],c=e.shape[0];if((i===1||s===1)&&u>1e3){o&&(e=e.transpose([0,2,1])),a&&(n=n.transpose([0,2,1]));var l=s===1?e:e.as3D(c,u,1),h=s===1?2:1,f=s===1?n.as3D(c,1,u):n;return this.multiply(l,f).sum(h,!0)}var p=ze(e.dtype,n.dtype),d=new Mo(e.shape,[c,i,s],o,a);return this.compileAndRun(d,[e,n],p)},t.prototype.fusedBatchMatMul=function(e){var n=e.a,o=e.b,a=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=a?n.shape[2]:n.shape[1],h=i?o.shape[1]:o.shape[2],f=n.shape[0],p=ze(n.dtype,o.dtype),d=s!=null,g=c!=null,v=u?Ir(u,!0):null,m=new Mo(n.shape,[f,l,h],a,i,d,v,g),x=[n,o];return s&&x.push(s),c&&x.push(c),this.compileAndRun(m,x,p)},t.prototype.multiply=function(e,n){if(e.dtype==="complex64"){var o=this.texData.get(e.dataId),a=this.texData.get(n.dataId),i=new Bi(Kh,e.shape,n.shape),s=new Bi(Xh,e.shape,n.shape),u=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag),this.makeComplexComponentTensorInfo(n,a.complexTensors.real),this.makeComplexComponentTensorInfo(n,a.complexTensors.imag)],c=this.compileAndRun(i,u),l=this.compileAndRun(s,u),h=this.complex(c,l);return c.dispose(),l.dispose(),h}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Li,e.dtype);var f=new Se(Li,e.shape,n.shape);return this.compileAndRun(f,[e,n],e.dtype)},t.prototype.batchNormalization=function(e,n,o,a,i,s){var u=[e,n,o],c=null;s!=null&&(c=s.shape,u.push(s));var l=null;if(i!=null&&(l=i.shape,u.push(i)),M().getBool("WEBGL_PACK_NORMALIZATION")){var h=new jh(e.shape,n.shape,o.shape,c,l,a);return this.compileAndRun(h,u)}var f=new qh(e.shape,n.shape,o.shape,c,l,a);return this.compileAndRun(f,u)},t.prototype.localResponseNormalization4D=function(e,n,o,a,i){var s=M().getBool("WEBGL_PACK_NORMALIZATION")?new Gf(e.shape,n,o,a,i):new Vf(e.shape,n,o,a,i);return this.compileAndRun(s,[e])},t.prototype.LRNGrad=function(e,n,o,a,i,s,u){var c=new zf(n.shape,a,i,s,u);return this.compileAndRun(c,[n,o,e])},t.prototype.tile=function(e,n){if(e.dtype==="string"){var o=this.readSync(e.dataId).map(function(i){return Mr(i)});return au(oe(e.shape,e.dtype,o),n)}var a=new fp(e.shape,n);return this.compileAndRun(a,[e])},t.prototype.pad=function(e,n,o){var a=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Yf(e.shape,n,o):new $f(e.shape,n,o);return this.compileAndRun(a,[e])},t.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var o=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new dp(e.shape,n):new pp(e.shape,n);return this.compileAndRun(o,[e])},t.prototype.gather=function(e,n,o){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.gather(e,n,o);var a=new wf(e.shape,n.size,o);return this.compileAndRun(a,[e,n])},t.prototype.batchToSpaceND=function(e,n,o){E(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var a=n.reduce(function(h,f){return h*f}),i=Vr(e.shape,n,a),s=zr(i.length,n.length),u=Gr(e.shape,n,a),c=js(o,n.length),l=Ks(u,o,n.length);return e.reshape(i).transpose(s).reshape(u).slice(c,l)},t.prototype.spaceToBatchND=function(e,n,o){E(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var a=n.reduce(function(f,p){return f*p}),i=[[0,0]];i.push.apply(i,o);for(var s=1+n.length;s<e.shape.length;++s)i.push([0,0]);var u=e.pad(i),c=Vr(u.shape,n,a,!1),l=zr(c.length,n.length,!1),h=Gr(u.shape,n,a,!1);return u.reshape(c).transpose(l).reshape(h)},t.prototype.reduce=function(e,n,o){var a=e.shape[0],i=e.shape[1],s=No(i),u=new Jf({windowSize:s,inSize:i,batchSize:a},n),c=this.compileAndRun(u,[e],o);return c.shape[1]===1?c:this.reduce(c,n,o)},t.prototype.argReduce=function(e,n,o){o===void 0&&(o=null);var a=e.shape[0],i=e.shape[1];o!=null&&(a=o.shape[0],i=o.shape[1]);var s=No(i),u=new Oh({windowSize:s,inSize:i,batchSize:a},n,o==null),c=[e];o!=null&&c.push(o);var l=this.compileAndRun(u,c,"int32");return l.shape[1]===1?l:this.argReduce(e,n,l)},t.prototype.argReducePacked=function(e,n,o){o===void 0&&(o=null);var a=o!=null?o.shape:e.shape,i=No(a[a.length-1]),s=new zh(a,i,n,o==null),u=o==null?[e]:[e,o],c=this.compileAndRun(s,u,"int32");return c.rank===e.rank?this.argReducePacked(e,n,c):c},t.prototype.sum=function(e,n){ot("sum",n,e.rank);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i),u=Eo(e.dtype);return this.reduce(s,"sum",u).reshape(a)},t.prototype.prod=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,n);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i),u=Eo(e.dtype);return this.reduce(s,"prod",u).reshape(a)},t.prototype.unsortedSegmentSum=function(e,n,o){var a=0,i=Ft([a],e.rank),s=e;i!=null&&(s=e.transpose(i),a=Pt(1,e.rank)[0]);var u=function(p,d,g){for(var v=[],m=p.length,x=0;x<m;x++)x!==d?v.push(p[x]):v.push(g);return v}(s.shape,a,o),c=Y([s.shape[a]]),l=s.as2D(-1,c),h=Eo(e.dtype),f=this.segOpCompute(l,"unsortedSegmentSum",n,h,o).reshape(u);return i!=null&&(f=f.transpose(Ca(i))),f},t.prototype.segOpCompute=function(e,n,o,a,i){var s=e.shape[0],u=e.shape[1],c=function(f,p){var d,g=!1;for(f<=$s?(d=f,g=!0):d=ta(f,Math.floor(Math.sqrt(f)));!g;)d>p||d===f?g=!0:d=ta(f,d+1);return d}(u,i),l=new ip({windowSize:c,inSize:u,batchSize:s,numSegments:i}),h=this.compileAndRun(l,[e,o],a);return h.shape[1]===i?h:(o=Ur(0,i).tile([u/c]),this.segOpCompute(h,n,o,a,i))},t.prototype.argMinMaxReduce=function(e,n,o){var a=[n];if(ot("arg"+o.charAt(0).toUpperCase()+o.slice(1),a,e.rank),!M().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var i=He(e.shape,a),s=i[0],u=Y(i[1]),c=e.as2D(-1,u);return this.argReduce(c,o).reshape(s)}return this.argReducePacked(e,o)},t.prototype.argMin=function(e,n){return this.argMinMaxReduce(e,n,"min")},t.prototype.argMax=function(e,n){return this.argMinMaxReduce(e,n,"max")},t.prototype.cumsum=function(e,n,o,a){if(n!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+n);var i=new cf(e.shape,o,a);return this.compileAndRun(i,[e])},t.prototype.equal=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3518  return vec4(equal(a, b));
3519`,"bool");var o=new Se("return float(a == b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.notEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3520  return vec4(notEqual(a, b));
3521`,"bool");var o=new Se("return float(a != b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3522  return vec4(lessThan(a, b));
3523`,"bool");var o=new Se("return float(a < b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.lessEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3524  return vec4(lessThanEqual(a, b));
3525`,"bool");var o=new Se("return float(a <= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3526  return vec4(greaterThan(a, b));
3527`,"bool");var o=new Se("return float(a > b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greaterEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3528  return vec4(greaterThanEqual(a, b));
3529`,"bool");var o=new Se("return float(a >= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalNot=function(e){var n=new ae(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(n,[e])},t.prototype.logicalAnd=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3530  return vec4(
3531    vec4(greaterThanEqual(a, vec4(1.0))) *
3532    vec4(greaterThanEqual(b, vec4(1.0))));
3533`,"bool");var o=new Se("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalOr=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3534  return min(
3535    vec4(greaterThanEqual(a, vec4(1.0))) +
3536    vec4(greaterThanEqual(b, vec4(1.0))),
3537    vec4(1.0));
3538`,"bool");var o=new Se("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.select=function(e,n,o){var a=new sp(e.rank,n.shape,n.rank);return this.compileAndRun(a,[e,n,o],ze(n.dtype,o.dtype))},t.prototype.where=function(e){Lr("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var n=e.dataSync();return Aa(e.shape,n)},t.prototype.topk=function(e,n,o){return iu(e.dataSync(),e.shape,e.dtype,n)},t.prototype.min=function(e,n){ot("min",n,e.rank);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i);return this.reduce(s,"min",s.dtype).reshape(a)},t.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3539  vec4 result = vec4(min(a, b));
3540  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
3541  
3542  result.r = isNaN.r > 0. ? NAN : result.r;
3543  result.g = isNaN.g > 0. ? NAN : result.g;
3544  result.b = isNaN.b > 0. ? NAN : result.b;
3545  result.a = isNaN.a > 0. ? NAN : result.a;
3546
3547  return result;
3548`,e.shape,n.shape):new Se(`
3549  if (isnan(a)) return a;
3550  if (isnan(b)) return b;
3551
3552  return min(a, b);
3553`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.mod=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3554  vec4 result = mod(a, b);
3555  vec4 isNaN = vec4(equal(b, vec4(0.0)));
3556  
3557  result.r = isNaN.r > 0. ? NAN : result.r;
3558  result.g = isNaN.g > 0. ? NAN : result.g;
3559  result.b = isNaN.b > 0. ? NAN : result.b;
3560  result.a = isNaN.a > 0. ? NAN : result.a;
3561
3562  return result;
3563`,e.shape,n.shape):new Se(`if (b == 0.0) return NAN;
3564  return mod(a, b);`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.max=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,n);ot("max",n,e.rank);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i);return this.reduce(s,"max",s.dtype).reshape(a)},t.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3565  vec4 result = vec4(max(a, b));
3566  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
3567  
3568  result.r = isNaN.r > 0. ? NAN : result.r;
3569  result.g = isNaN.g > 0. ? NAN : result.g;
3570  result.b = isNaN.b > 0. ? NAN : result.b;
3571  result.a = isNaN.a > 0. ? NAN : result.a;
3572
3573  return result;
3574`,e.shape,n.shape):new Se(`
3575  if (isnan(a)) return a;
3576  if (isnan(b)) return b;
3577
3578  return max(a, b);
3579`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.all=function(e,n){ot("all",n,e.rank);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i);return this.reduce(s,"all",s.dtype).reshape(a)},t.prototype.any=function(e,n){ot("any",n,e.rank);var o=He(e.shape,n),a=o[0],i=Y(o[1]),s=e.as2D(-1,i);return this.reduce(s,"any",s.dtype).reshape(a)},t.prototype.realDivide=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3580  // vec4 one = vec4(equal(a, b));
3581  // return one + (vec4(1.0) - one) * a / b;
3582  vec4 result = a / b;
3583  if(a.x == b.x) {
3584    result.x = 1.;
3585  }
3586  if(a.y == b.y) {
3587    result.y = 1.;
3588  }
3589  if(a.z == b.z) {
3590    result.z = 1.;
3591  }
3592  if(a.w == b.w) {
3593    result.w = 1.;
3594  }
3595
3596  return result;
3597`,"float32",!0);var o=new Se(`
3598if (a == b) {
3599  return 1.0;
3600};
3601return a / b;`,e.shape,n.shape);return this.compileAndRun(o,[e,n],"float32")},t.prototype.floorDiv=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,`
3602  ivec4 ia = round(a);
3603  ivec4 ib = round(b);
3604  bvec4 cond = notEqual(ib, ivec4(0));
3605  ivec4 result = ivec4(0);
3606  vec4 s = sign(a) * sign(b);
3607
3608  // Windows (D3D) wants guaranteed non-zero int division at compile-time.
3609  if (cond[0]) {
3610    result[0] = idiv(ia[0], ib[0], s[0]);
3611  }
3612  if (cond[1]) {
3613    result[1] = idiv(ia[1], ib[1], s[1]);
3614  }
3615  if (cond[2]) {
3616    result[2] = idiv(ia[2], ib[2], s[2]);
3617  }
3618  if (cond[3]) {
3619    result[3] = idiv(ia[3], ib[3], s[3]);
3620  }
3621  return vec4(result);
3622`,"int32");var o=new Se(`
3623  float s = sign(a) * sign(b);
3624  int ia = round(a);
3625  int ib = round(b);
3626  if (ib != 0) {
3627    // Windows (D3D) wants guaranteed non-zero int division at compile-time.
3628    return float(idiv(ia, ib, s));
3629  } else {
3630    return NAN;
3631  }
3632`,e.shape,n.shape);return this.compileAndRun(o,[e,n],"int32")},t.prototype.add=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,Fo);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var o=ze(e.dtype,n.dtype);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Fo,o);var a=new Se(Fo,e.shape,n.shape);return this.compileAndRun(a,[e,n],o)},t.prototype.packedUnaryOp=function(e,n,o){var a=new Jn(e.shape,n);return this.compileAndRun(a,[e],o)},t.prototype.packedBinaryOp=function(e,n,o,a,i){i===void 0&&(i=!1);var s=new Ut(o,e.shape,n.shape,i);return this.compileAndRun(s,[e,n],a)},t.prototype.complexSeparableBinaryOp=function(e,n,o){var a=this,i=this.texData.get(e.dataId),s=this.texData.get(n.dataId),u=[[i.complexTensors.real,s.complexTensors.real],[i.complexTensors.imag,s.complexTensors.imag]].map(function(f){var p=f[0],d=f[1],g=a.makeComplexComponentTensorInfo(e,p),v=a.makeComplexComponentTensorInfo(n,d),m=new Se(o,e.shape,n.shape);return a.compileAndRun(m,[g,v],ze(p.dtype,d.dtype))}),c=u[0],l=u[1],h=this.complex(c,l);return c.dispose(),l.dispose(),h},t.prototype.makeComplexComponentTensorInfo=function(e,n){return{dataId:n.dataId,dtype:n.dtype,shape:e.shape}},t.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>M().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),o=this.addN(e.slice(0,n)),a=this.addN(e.slice(n));return this.addN([o,a])}var i=e.map(function(c){return c.dtype}).reduce(function(c,l){return ze(c,l)}),s=e.map(function(c){return c.shape}),u=M().getBool("WEBGL_PACK")?new Mh(e[0].shape,s):new Ph(e[0].shape,s);return this.compileAndRun(u,e,i)},t.prototype.subtract=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,Po);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var o=ze(e.dtype,n.dtype);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Po,e.dtype);var a=new Se(Po,e.shape,n.shape);return this.compileAndRun(a,[e,n],o)},t.prototype.pow=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3633  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
3634  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
3635  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
3636  vec4 result = multiplier * pow(abs(a), b);
3637
3638  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
3639  bvec4 isExpZero = equal(b, vec4(0.0));
3640  result.r = isExpZero.r ? 1.0 : result.r;
3641  result.g = isExpZero.g ? 1.0 : result.g;
3642  result.b = isExpZero.b ? 1.0 : result.b;
3643  result.a = isExpZero.a ? 1.0 : result.a;
3644
3645  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
3646  
3647  result.r = isNaN.r > 0. ? NAN : result.r;
3648  result.g = isNaN.g > 0. ? NAN : result.g;
3649  result.b = isNaN.b > 0. ? NAN : result.b;
3650  result.a = isNaN.a > 0. ? NAN : result.a;
3651
3652  return result;
3653`,e.shape,n.shape):new Se(`
3654if(a < 0.0 && floor(b) < b){
3655  return NAN;
3656}
3657if (b == 0.0) {
3658  return 1.0;
3659}
3660return (round(mod(b, 2.0)) != 1) ?
3661    pow(abs(a), b) : sign(a) * pow(abs(a), b);
3662`,e.shape,n.shape),a=ze(e.dtype,n.dtype);return this.compileAndRun(o,[e,n],a)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Yi,e.dtype);var n=new ae(e.shape,Yi);return this.compileAndRun(n,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ji,e.dtype);var n=new ae(e.shape,Ji);return this.compileAndRun(n,[e])},t.prototype.sign=function(e){var n=new ae(e.shape,`
3663  if (isnan(x)) { return 0.0; }
3664  return sign(x);
3665`);return this.compileAndRun(n,[e])},t.prototype.isNaN=function(e){var n=new ae(e.shape,"return float(isnan(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isInf=function(e){var n=new ae(e.shape,"return float(isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isFinite=function(e){var n=new ae(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.round=function(e){var n=new ae(e.shape,`
3666  // OpenGL ES does not support round function.
3667  // The algorithm is based on banker's rounding.
3668  float base = floor(x);
3669  if ((x - base) < 0.5) {
3670    return floor(x);
3671  } else if ((x - base) > 0.5) {
3672    return ceil(x);
3673  } else {
3674    if (mod(base, 2.0) == 0.0) {
3675      return base;
3676    } else {
3677      return base + 1.0;
3678    }
3679  }
3680`);return this.compileAndRun(n,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Qi,e.dtype);var n=new ae(e.shape,Qi);return this.compileAndRun(n,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Zi,e.dtype);var n=new ae(e.shape,Zi);return this.compileAndRun(n,[e])},t.prototype.softmax=function(e,n){var o=Be([n],e.shape),a=this.max(e,o),i=et(a.shape,o),s=this.subtract(e,a.reshape(i)),u=this.exp(s),c=this.sum(u,o).reshape(i);return this.realDivide(u,c)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,`
3681  vec4 result = log(x);
3682  vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
3683  result.r = isNaN.r == 1.0 ? NAN : result.r;
3684  result.g = isNaN.g == 1.0 ? NAN : result.g;
3685  result.b = isNaN.b == 1.0 ? NAN : result.b;
3686  result.a = isNaN.a == 1.0 ? NAN : result.a;
3687
3688  return result;
3689`,e.dtype);var n=new ae(e.shape,`if (x < 0.0) return NAN;
3690  return log(x);`);return this.compileAndRun(n,[e])},t.prototype.log1p=function(e){var n=new ae(e.shape,"return log(1.0 + x);");return this.compileAndRun(n,[e])},t.prototype.sqrt=function(e){var n=new ae(e.shape,"return sqrt(x);");return this.compileAndRun(n,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var n=new ae(e.shape,"return inversesqrt(x);");return this.compileAndRun(n,[e])},t.prototype.reciprocal=function(e){var n=new ae(e.shape,"return 1.0 / x;");return this.compileAndRun(n,[e])},t.prototype.relu=function(e){var n;return n=M().getBool("WEBGL_PACK")?new Jn(e.shape,vu):new ae(e.shape,fu),this.compileAndRun(n,[e])},t.prototype.relu6=function(e){var n;return n=M().getBool("WEBGL_PACK")?new Jn(e.shape,mu):new ae(e.shape,pu),this.compileAndRun(n,[e])},t.prototype.prelu=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(hu,e.shape,n.shape):new Se(lu,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.elu=function(e){if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,gu,e.dtype);var n=new ae(e.shape,du);return this.compileAndRun(n,[e])},t.prototype.eluDer=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3691  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
3692  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
3693`,e.shape,n.shape):new Se("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.selu=function(e){var n=new ae(e.shape,mp);return this.compileAndRun(n,[e])},t.prototype.int=function(e){var n=new ae(e.shape,"return float(int(x));");return this.compileAndRun(n,[e],"int32")},t.prototype.clip=function(e,n,o){var a,i=(a=M().getBool("WEBGL_PACK_CLIP")?new Yh(e.shape):new $h(e.shape)).getCustomSetupFunc(n,o);return this.compileAndRun(a,[e],null,i)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Xi,e.dtype);var n=new ae(e.shape,Xi);return this.compileAndRun(n,[e])},t.prototype.complexAbs=function(e){var n=this.texData.get(e.dataId),o=new Jh(e.shape),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)];return this.compileAndRun(o,a)},t.prototype.sigmoid=function(e){var n=new ae(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(n,[e])},t.prototype.softplus=function(e){var n=new ae(e.shape,`
3694  float epsilon = 1.1920928955078125e-7;
3695  float threshold = log(epsilon) + 2.0;
3696
3697  bool too_large = x > -threshold;
3698  bool too_small = x < threshold;
3699
3700  float result;
3701  float exp_x = exp(x);
3702
3703  if (too_large){
3704    result = x;
3705  }
3706  else if (too_small){
3707    result = exp_x;
3708  }
3709  else{
3710    result = log(exp_x + 1.0);
3711  }
3712  return result;
3713`);return this.compileAndRun(n,[e])},t.prototype.sin=function(e){var n=new ae(e.shape,gp);return this.compileAndRun(n,[e])},t.prototype.cos=function(e){var n=new ae(e.shape,yp);return this.compileAndRun(n,[e])},t.prototype.tan=function(e){var n=new ae(e.shape,"return tan(x);");return this.compileAndRun(n,[e])},t.prototype.asin=function(e){var n=new ae(e.shape,xp);return this.compileAndRun(n,[e])},t.prototype.acos=function(e){var n=new ae(e.shape,bp);return this.compileAndRun(n,[e])},t.prototype.atan=function(e){var n=new ae(e.shape,wp);return this.compileAndRun(n,[e])},t.prototype.atan2=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut(`
3714  vec4 result = atan(a, b);
3715  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
3716  
3717  result.r = isNaN.r > 0. ? NAN : result.r;
3718  result.g = isNaN.g > 0. ? NAN : result.g;
3719  result.b = isNaN.b > 0. ? NAN : result.b;
3720  result.a = isNaN.a > 0. ? NAN : result.a;
3721
3722  return result;
3723`,e.shape,n.shape):new Se(`
3724  if (isnan(a)) return a;
3725  if (isnan(b)) return b;
3726
3727  return atan(a, b);
3728`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.sinh=function(e){var n=new ae(e.shape,`
3729  float e2x = exp(x);
3730  return (e2x - 1.0 / e2x) / 2.0;
3731`);return this.compileAndRun(n,[e])},t.prototype.cosh=function(e){var n=new ae(e.shape,`
3732  float e2x = exp(-x);
3733  return (e2x + 1.0 / e2x) / 2.0;
3734`);return this.compileAndRun(n,[e])},t.prototype.tanh=function(e){var n=new ae(e.shape,`
3735  float e2x = exp(-2.0 * abs(x));
3736  return sign(x) * (1.0 - e2x) / (1.0 + e2x);
3737`);return this.compileAndRun(n,[e])},t.prototype.asinh=function(e){var n=new ae(e.shape,Cp);return this.compileAndRun(n,[e])},t.prototype.acosh=function(e){var n=new ae(e.shape,_p);return this.compileAndRun(n,[e])},t.prototype.atanh=function(e){var n=new ae(e.shape,Ep);return this.compileAndRun(n,[e])},t.prototype.erf=function(e){var n=new ae(e.shape,`
3738  // Error function is calculated approximately with elementary function.
3739  // See "Handbook of Mathematical Functions with Formulas,
3740  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
3741  float p = 0.3275911;
3742  float a1 = 0.254829592;
3743  float a2 = -0.284496736;
3744  float a3 = 1.421413741;
3745  float a4 = -1.453152027;
3746  float a5 = 1.061405429;
3747
3748  float sign = sign(x);
3749  x = abs(x);
3750  float t = 1.0 / (1.0 + p * x);
3751  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
3752`);return this.compileAndRun(n,[e])},t.prototype.step=function(e,n){var o=new ae(e.shape,function(a){return a===void 0&&(a=0),yt+`
3753    return x > 0.0 ? 1.0 : float(`+a+`);
3754  `}(n));return this.compileAndRun(o,[e])},t.prototype.conv2dByMatMul=function(e,n,o,a,i,s){var u=e.shape,c=this.texData.get(e.dataId),l=o.inChannels,h=u[0]*u[1]*u[2],f=o.outChannels,p=o.dataFormat==="channelsLast",d=(h===1||f===1)&&l>1e3,g=u[2]%2!=0&&!!c.isPacked;if(d||!M().getBool("WEBGL_LAZILY_UNPACK")||!M().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!g){var v=p?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],m=this.reshape(e,[1,v,o.inChannels]),x=this.reshape(n,[1,o.inChannels,o.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:x,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),o.outShape)}var b=p?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),y={dataId:e.dataId,shape:[1,b,o.inChannels],dtype:e.dtype},w=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,E(wr(c.shape,y.shape),function(){return"packed reshape "+c.shape+" to "+y.shape+" isn't free"});var C=this.reshape(n,[1,o.inChannels,o.outChannels]),S=this.fusedBatchMatMul({a:y,b:C,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),k=this.texData.get(S.dataId);return E(k.isPacked,function(){return"batchMatMul result is expected to be packed"}),c.shape=w,k.shape=o.outShape,T.makeTensorFromDataId(S.dataId,o.outShape,S.dtype)},t.prototype.conv2dWithIm2Row=function(e,n,o,a,i,s){var u=o.filterWidth,c=o.filterHeight,l=o.inChannels,h=o.outWidth,f=o.outHeight,p=o.dataFormat==="channelsLast",d=u*c*l,g=f*h,v=[d,g],m=e.squeeze([0]),x=n.reshape([1,d,-1]),b=new Uf(v,m.shape,o),y=this.compileAndRun(b,[m]).reshape([1,v[0],v[1]]),w=a!=null,C=s!=null,S=i?Ir(i,!0):null,k=new Mo(y.shape,[1,g,o.outChannels],!0,!1,w,S,C),I=[y,x];a&&I.push(a),C&&I.push(s);var R=this.compileAndRun(k,I);return p?R.reshape([1,f,h,o.outChannels]):R.reshape([1,o.outChannels,f,h])},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,a=e.convInfo,i=e.b
vendor: 15,453 bytes, line 3754
3754ias,s=e.activation,u=e.preluActivationWeights;if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(n,o,a,i,s,u);if(M().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)return this.conv2dWithIm2Row(n,o,a,i,s,u);var c=i!=null,l=u!=null,h=s?Ir(s,!1):null,f=new Wi(a,c,h,l),p=[n,o];return i&&p.push(i),u&&p.push(u),this.compileAndRun(f,p)},t.prototype.conv2d=function(e,n,o){if(o.filterHeight===1&&o.filterWidth===1&&o.dilationHeight===1&&o.dilationWidth===1&&o.strideHeight===1&&o.strideWidth===1&&(o.padInfo.type==="SAME"||o.padInfo.type==="VALID"))return this.conv2dByMatMul(e,n,o);if(M().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,n,o);var a=new Wi(o);return this.compileAndRun(a,[e,n])},t.prototype.conv2dDerInput=function(e,n,o){var a=new tf(o);return this.compileAndRun(a,[e,n])},t.prototype.conv2dDerFilter=function(e,n,o){var a=new ef(o);return this.compileAndRun(a,[e,n])},t.prototype.fusedDepthwiseConv2D=function(e){var n,o=e.input,a=e.filter,i=e.convInfo,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=M().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,h=u?Ir(u,l):null,f=[o,a],p=s!=null,d=c!=null;return p&&f.push(s),d&&f.push(c),l?(n=new Vi(i,p,h,d),this.compileAndRun(n,f)):(n=new Ui(i,p,h,d),this.compileAndRun(n,f))},t.prototype.depthwiseConv2D=function(e,n,o){var a;return M().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1?(a=new Vi(o),this.compileAndRun(a,[e,n])):(a=new Ui(o),this.compileAndRun(a,[e,n]))},t.prototype.depthwiseConv2DDerInput=function(e,n,o){var a=new af(o);return this.compileAndRun(a,[e,n])},t.prototype.depthwiseConv2DDerFilter=function(e,n,o){var a=new of(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3d=function(e,n,o){var a=new sf(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3dDerInput=function(e,n,o){var a=new rf(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3dDerFilter=function(e,n,o){var a=new nf(o);return this.compileAndRun(a,[e,n])},t.prototype.maxPool=function(e,n){var o=new Oo(n,"max",!1);return this.compileAndRun(o,[e])},t.prototype.avgPool=function(e,n){var o=new Oo(n,"avg",!1);return this.compileAndRun(o,[e],"float32")},t.prototype.maxPoolBackprop=function(e,n,o,a){var i=new Oo(a,"max",!0),s=this.compileAndRun(i,[n]),u=new Hf(a),c=this.compileAndRun(u,[e,s],n.dtype);return s.dispose(),c},t.prototype.avgPoolBackprop=function(e,n,o){var a=new Gh(o);return this.compileAndRun(a,[e],n.dtype)},t.prototype.cast=function(e,n){return tu(e,n,this)},t.prototype.unstack=function(e,n){for(var o=e.shape[n],a=new Array(e.rank-1),i=0,s=0;s<e.rank;s++)s!==n&&(a[i++]=e.shape[s]);var u=new Array(e.rank).fill(0),c=e.shape.slice();c[n]=1;var l=new Array(o);for(s=0;s<l.length;s++)u[n]=s,l[s]=this.slice(e,u,c).reshape(a);return l},t.prototype.avgPool3d=function(e,n){var o=new Bo(n,"avg",!1);return this.compileAndRun(o,[e],"float32")},t.prototype.avgPool3dBackprop=function(e,n,o){var a=new Hh(o);return this.compileAndRun(a,[e],n.dtype)},t.prototype.maxPool3d=function(e,n){var o=new Bo(n,"max",!1);return this.compileAndRun(o,[e],"float32")},t.prototype.maxPool3dBackprop=function(e,n,o,a){var i=new Bo(a,"max",!0),s=this.compileAndRun(i,[n]),u=new qf(a),c=this.compileAndRun(u,[e,s],n.dtype);return s.dispose(),c},t.prototype.reshape=function(e,n){var o=this.texData.get(e.dataId);if(o.isPacked&&!wr(e.shape,n)&&(o.texture===null||!wr(o.shape,n))){var a=this.packedReshape(e,n);return T.makeTensorFromDataId(a.dataId,a.shape,a.dtype)}return ca(e,n)},t.prototype.resizeBilinear=function(e,n,o,a){var i=M().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new tp(e.shape,n,o,a):new ep(e.shape,n,o,a);return this.compileAndRun(i,[e],"float32")},t.prototype.resizeBilinearBackprop=function(e,n,o){var a=new Zf(e,n,o);return this.compileAndRun(a,[e])},t.prototype.resizeNearestNeighbor=function(e,n,o,a){var i=new rp(e.shape,n,o,a);return this.compileAndRun(i,[e])},t.prototype.resizeNearestNeighborBackprop=function(e,n,o){var a=new np(e,n,o);return this.compileAndRun(a,[e])},t.prototype.multinomial=function(e,n,o,a){var i=n?e:Gt(e),s=i.shape[0],u=i.shape[1],c=new jf(s,u,o),l=c.getCustomSetupFunc(a);return this.compileAndRun(c,[i],"int32",l)},t.prototype.oneHot=function(e,n,o,a){var i=new Kf(e.size,n,o,a);return this.compileAndRun(i,[e])},t.prototype.diag=function(e){var n=new pf(e.size);return this.compileAndRun(n,[e])},t.prototype.nonMaxSuppression=function(e,n,o,a,i){return Lr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Sa(e.dataSync(),n.dataSync(),o,a,i)},t.prototype.cropAndResize=function(e,n,o,a,i,s){var u=new uf(e.shape,n.shape,a,i,s);return this.compileAndRun(u,[e,n,o],"float32")},t.prototype.depthToSpace=function(e,n,o){E(n>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+n});var a=e.shape[0],i=o==="NHWC"?e.shape[1]:e.shape[2],s=o==="NHWC"?e.shape[2]:e.shape[3],u=o==="NHWC"?e.shape[3]:e.shape[1],c=i*n,l=s*n,h=u/(n*n),f=new ff(o==="NHWC"?[a,c,l,h]:[a,h,c,l],n,o);return this.compileAndRun(f,[e])},t.prototype.split=function(e,n,o){return ou(e,n,o)},t.prototype.scatterND=function(e,n,o){var a=Hr(0,e,o),i=a.sliceRank,s=a.numUpdates,u=a.sliceSize,c=a.strides,l=a.outputSize,h=[l/u,u],f=e.reshape([s,i]),p=n.reshape([s,u]);if(l===0)return ca(Ge([]),o);var d=q(0),g=new qi(s,i,f.rank,p.rank,c,h);return this.compileAndRun(g,[p,f,d]).reshape(o)},t.prototype.sparseToDense=function(e,n,o,a){var i=Hr(0,e,o),s=i.sliceRank,u=i.numUpdates,c=i.strides,l=i.outputSize,h=new qi(u,s,e.rank,n.rank,c,[l,1]);return this.compileAndRun(h,[n,e,a]).reshape(o)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,n){var o=this.texData.get(e.dataId),a=new Gi(yf,e.shape,n),i=new Gi(xf,e.shape,n),s=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag)],u=this.compileAndRun(a,s),c=this.compileAndRun(i,s),l=this.complex(u,c).as2D(e.shape[0],e.shape[1]);return u.dispose(),c.dispose(),l},t.prototype.gatherND=function(e,n){var o=n.shape,a=o[o.length-1],i=Xs(e,n),s=i[0],u=i[1],c=i[2],l=i[3],h=n.reshape([u,a]),f=e.reshape([e.size/c,c]),p=new Cf(a,l,[u,c]);return this.compileAndRun(p,[f,h]).reshape(s)},t.prototype.fill=function(e,n,o){if((o=o||ur(n))==="string"){var a=Pr(o,Y(e));return a.fill(n),T.makeTensor(a,e,o,this)}var i=new bf(e,n),s=i.getCustomSetupFunc(n);return this.compileAndRun(i,[],o,s)},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},t.prototype.linspace=function(e,n,o){return nu(e,n,o)},t.prototype.makeTensorInfo=function(e,n){var o=this.write(null,e,n);return this.texData.get(o).usage=null,{dataId:o,shape:e,dtype:n}},t.prototype.makeOutput=function(e,n){var o=this.makeTensorInfo(e,n).dataId;return T.makeTensorFromDataId(o,e,n,this)},t.prototype.unpackTensor=function(e){var n=new Rp(e.shape);return this.runWebGLProgram(n,[e],e.dtype)},t.prototype.packTensor=function(e){var n=new Xf(e.shape);return this.runWebGLProgram(n,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,n){var o=[Or(e.shape)].concat(Br(e.shape)),a={dtype:e.dtype,shape:o,dataId:e.dataId},i=[Or(n)].concat(Br(n)),s=new Qf(i,o),u=this.runWebGLProgram(s,[a],e.dtype,null,!0);return{dataId:u.dataId,shape:n,dtype:u.dtype}},t.prototype.decode=function(e){var n,o=this.texData.get(e),a=o.isPacked,i=o.shape,s=o.dtype,u=To(i);return n=a?new hf(u):new lf(u),{dtype:s,shape:i,dataId:this.runWebGLProgram(n,[{shape:u,dtype:s,dataId:e}],s,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,n,o,a,i){var s=this;i===void 0&&(i=!1);var u=this.makeTensorInfo(e.outputShape,o),c=this.texData.get(u.dataId);if(e.packedOutput&&(c.isPacked=!0),e.outPackingScheme===rr.DENSE){var l=Qn(e.outputShape);c.texShape=l.map(function(b){return 2*b})}if(e.outTexUsage!=null&&(c.usage=e.outTexUsage),Y(u.shape)===0)return c.values=tr(u.dtype,0),u;var h=[],f=n.map(function(b){if(b.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var y=s.texData.get(b.dataId);if(y.texture==null){if(!e.packedInputs&&Y(b.shape)<=M().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:b.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=b.shape)}else if(!!y.isPacked!=!!e.packedInputs)b=y.isPacked?s.unpackTensor(b):s.packTensor(b),h.push(b),y=s.texData.get(b.dataId);else if(y.isPacked&&!wr(y.shape,b.shape)){var w=b,C=b.shape;b.shape=y.shape,b=s.packedReshape(b,C),h.push(b),y=s.texData.get(b.dataId),w.shape=C}return s.uploadToGPU(b.dataId),{shape:b.shape,texData:y,isUniform:!1}});this.uploadToGPU(u.dataId);var p,d={shape:u.shape,texData:c,isUniform:!1},g=function(b,y,w){var C="";y.concat(w).forEach(function(I){var R=I.texData!=null&&I.texData.slice!=null&&I.texData.slice.flatOffset>0,N=I.isUniform?"uniform":I.texData.texShape;C+=I.shape+"_"+N+"_"+R});var S=b.userCode,k=b.constructor.name;return k+="_"+C+"_"+S}(e,f,d),v=this.getAndSaveBinary(g,function(){return function(b,y,w,C){var S=y.userCode,k=w.map(function(W,G){var H={logicalShape:W.shape,texShape:W.isUniform?null:W.texData.texShape,isUniform:W.isUniform,isPacked:!W.isUniform&&W.texData.isPacked,flatOffset:null};return W.texData!=null&&W.texData.slice!=null&&W.texData.slice.flatOffset>0&&(H.flatOffset=W.texData.slice.flatOffset),{name:y.variableNames[G],shapeInfo:H}}),I=k.map(function(W){return W.shapeInfo}),R={logicalShape:C.shape,texShape:C.texData.texShape,isUniform:!1,isPacked:C.texData.isPacked,flatOffset:null},N=Bh(k,R,S,y.packedInputs),A=b.createProgram(N),L=null,O=b.getUniformLocation(A,"NAN",!1);M().getNumber("WEBGL_VERSION")===1&&(L=b.getUniformLocation(A,"INFINITY",!1));for(var B={},V=0;V<y.variableNames.length;V++){var U=y.variableNames[V];B[U]=b.getUniformLocation(A,U,!1),B["offset"+U]=b.getUniformLocation(A,"offset"+U,!1)}return{program:y,source:N,webGLProgram:A,uniformLocations:B,inShapeInfos:I,outShapeInfo:R,infLoc:L,nanLoc:O}}(s.gpgpu,e,f,d)}),m=this.activeTimers!=null;if(m&&(p=this.startTimer()),function(b,y,w,C,S){Hi(y.inShapeInfos,w),Hi([y.outShapeInfo],[C]);var k=C.texData.texture,I=C.texData.texShape;C.texData.isPacked?b.setOutputPackedMatrixTexture(k,I[0],I[1]):b.setOutputMatrixTexture(k,I[0],I[1]),b.setProgram(y.webGLProgram),M().getNumber("WEBGL_VERSION")===1&&y.infLoc!==null&&b.gl.uniform1f(y.infLoc,1/0),y.nanLoc!==null&&b.gl.uniform1f(y.nanLoc,NaN),w.forEach(function(R,N){var A=y.program.variableNames[N],L=y.uniformLocations[A],O=y.uniformLocations["offset"+A];if(L!=null)if(R.isUniform)if(Y(R.shape)<2)b.gl.uniform1f(L,R.uniformValues[0]);else{var B=R.uniformValues;B instanceof Float32Array||(B=new Float32Array(B)),b.gl.uniform1fv(L,B)}else R.texData.slice!=null&&O!=null&&b.gl.uniform1i(O,R.texData.slice.flatOffset),b.setInputMatrixTexture(R.texData.texture,L,N)}),S!=null&&S(b,y.webGLProgram),b.executeProgram()}(this.gpgpu,v,f,d,a),h.forEach(function(b){return s.disposeData(b.dataId)}),m&&(p=this.endTimer(p),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(p)})),!M().getBool("WEBGL_LAZILY_UNPACK")&&c.isPacked&&i===!1){var x=this.unpackTensor(u);return this.disposeData(u.dataId),x}return u},t.prototype.compileAndRun=function(e,n,o,a,i){i===void 0&&(i=!1),o=o||n[0].dtype;var s=this.runWebGLProgram(e,n,o,a,i);return T.makeTensorFromDataId(s.dataId,s.shape,s.dtype)},t.prototype.getAndSaveBinary=function(e,n){return e in this.binaryCache||(this.binaryCache[e]=n()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;this.disposed||(M().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(function(n){e.gpgpu.deleteProgram(e.binaryCache[n].webGLProgram),delete e.binaryCache[n]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},t.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue==null&&(this.floatPrecisionValue=K(function(){if(!M().get("WEBGL_RENDER_FLOAT32_ENABLED")){var n=M().getBool("DEBUG");M().set("DEBUG",!1);var o=e.abs(q(1e-8)).dataSync()[0];if(M().set("DEBUG",n),o>0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var n,o=this.texData.get(e),a=o.shape,i=o.dtype,s=o.values,u=o.texture,c=o.usage,l=o.isPacked;if(u==null){var h,f=this.activeTimers!=null;f&&(h=Et());var p=o.texShape;if(p==null&&(p=Fl(a,l),o.texShape=p),s!=null){var d=To(a),g=void 0,v=p[1],m=p[0],x=s instanceof Uint8Array;l?(v=(n=lr(p[0],p[1]))[0],m=n[1],g=new gf(d,[m,v],x)):g=new mf(d,[m,v],x);var b=this.makeTensorInfo([m,v],i);this.texData.get(b.dataId).usage=x?it.PIXELS:it.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),v,m,s);var y=this.runWebGLProgram(g,[b],i,null,!0),w=this.texData.get(y.dataId);o.texture=w.texture,o.texShape=w.texShape,o.isPacked=w.isPacked,o.usage=w.usage,this.disposeData(b.dataId),this.texData.delete(y.dataId),o.values=null,f&&(this.uploadWaitMs+=Et()-h)}else{var C=this.acquireTexture(p,c,i,l);o.texture=C}}},t.prototype.convertAndCacheOnCPU=function(e,n){var o=this.texData.get(e),a=o.dtype;return this.releaseGPUData(e),n!=null&&(o.values=function(i,s){if(s==="float32"||s==="complex64")return i;if(s==="int32"||s==="bool"){for(var u=s==="int32"?new Int32Array(i.length):new Uint8Array(i.length),c=0;c<u.length;++c)u[c]=Math.round(i[c]);return u}throw new Error("Unknown dtype "+s)}(n,a)),o.values},t.prototype.acquireTexture=function(e,n,o,a){if(this.numBytesInGPU+=this.computeBytes(e,o),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,n,a)},t.prototype.computeBytes=function(e,n){return e[0]*e[1]*As(n)},t}(Zs);Bs()&&T.registerBackend("webgl",function(){return new Sp},2);var Dp=D({square_:function(r){var t=_(r,"x","square"),e=[t];return T.runKernelFunc(function(n,o){return o([t]),n.square(t)},{x:t},null,"Square",{},e,[])}}),ar="SquaredDifference",yu=D({squaredDifference_:function(r,t){var e,n=_(r,"a","squaredDifference"),o=_(t,"b","squaredDifference");e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape);var a={a:n,b:o},i=[n,o];return T.runKernelFunc(function(s,u){var c=s.squaredDifference(n,o);return u([n,o]),c},a,function(s,u){var c=u[0],l=u[1],h=q(2);return{a:function(){return s.mul(c.sub(l).mul(h))},b:function(){return s.mul(l.sub(c).mul(h))}}},ar,{},i,[])}}),Ap=D({abs_:function(r){var t=_(r,"x","abs");return t.dtype==="complex64"?T.runKernelFunc(function(e){return e.complexAbs(t)},{$x:t}):T.runKernelFunc(function(e,n){var o=e.abs(t);return n([t]),o},{x:t},function(e,n){var o=n[0];
vendor: 1,161 bytes, line 3754
3754return{x:function(){return e.mul(o.toFloat().step(-1))}}},"Abs")}}),Tp=D({acos_:function(r){var t=_(r,"x","acos");return T.runKernelFunc(function(e,n){var o=e.acos(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).sub(o.toFloat().square()).sqrt()).neg()}}})}}),Np=D({acosh_:function(r){var t=_(r,"x","acosh");return T.runKernelFunc(function(e,n){var o=e.acosh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(o.toFloat().square().sub(1).sqrt())}}})}}),Fp=D({asin_:function(r){var t=_(r,"x","asin");return T.runKernelFunc(function(e,n){var o=e.asin(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).sub(o.toFloat().square()).sqrt())}}})}}),Pp=D({asinh_:function(r){var t=_(r,"x","asinh");return T.runKernelFunc(function(e,n){var o=e.asinh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).add(o.toFloat().square()).sqrt())}}})}}),Mp=D({atan_:function(r){var t=_(r,"x","atan");return T.runKernelFunc(function(e,n){var o=e.atan(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];
vendor: 2,389 bytes, line 3754
3754return{$x:function(){return e.div(o.toFloat().square().add(1))}}})}}),Op=D({atanh_:function(r){var t=_(r,"x","atanh");return T.runKernelFunc(function(e,n){var o=e.atanh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(q(1).sub(o.toFloat().square()))}}})}}),Bp=D({ceil_:function(r){var t=_(r,"x","ceil");return T.runKernelFunc(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),Pa=D({clipByValue_:function(r,t,e){var n=_(r,"x","clipByValue");E(t<=e,function(){return"Error in clip: min ("+t+") must be less than or equal to max ("+e+")."});var o=[n],a={min:t,max:e};return T.runKernelFunc(function(i,s){var u=i.clip(n,t,e);return s([n]),u},{x:n},function(i,s){var u=s[0];return{x:function(){return i.where(u.greaterEqual(t).logicalAnd(u.lessEqual(e)),ve(i))}}},"ClipByValue",a,o)}}),Lp=D({cos_:function(r){var t=_(r,"x","cos"),e=[t];return T.runKernelFunc(function(n,o){var a=n.cos(t);return o([t]),a},{x:t},function(n,o){var a=o[0];return{x:function(){return a.toFloat().sin().neg().mul(n)}}},"Cos",{},e)}}),Wp=D({cosh_:function(r){var t=_(r,"x","cosh");return T.runKernelFunc(function(e,n){var o=e.cosh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return o.toFloat().sinh().mulStrict(e)}}})}}),Up=D({erf_:function(r){var t=_(r,"x","erf");return E(t.dtype==="int32"||t.dtype==="float32",function(){return"Input dtype must be `int32` or `float32`."}),t.dtype==="int32"&&(t=t.toFloat()),T.runKernelFunc(function(e,n){var o=e.erf(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),ha=D({exp_:function(r){var t=_(r,"x","exp");return T.runKernelFunc(function(e,n){var o=e.exp(t);return n([o]),o},{x:t},function(e,n){return{x:function(){return e.mulStrict(n[0])}}},"Exp",{},[],[!0])}}),Vp=D({expm1_:function(r){var t=_(r,"x","expm1");return T.runKernelFunc(function(e,n){var o=e.expm1(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.exp())}}})}}),zp=D({floor_:function(r){var t=_(r,"x","floor");return T.runKernelFunc(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),Gp=D({log_:function(r){var t=_(r,"x","log"),e=[t];return T.runKernelFunc(function(n,o){var a=n.log(t);return o([t]),a},{x:t},function(n,o){var a=o[0];
vendor: 2,003 bytes, line 3754
3754return{x:function(){return n.div(a.toFloat())}}},"Log",{},e)}}),Hp=D({log1p_:function(r){var t=_(r,"x","log1p");return T.runKernelFunc(function(e,n){var o=e.log1p(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.add(1))}}})}}),qp=D({logSigmoid_:function(r){var t=_(r,"x","logSigmoid");return T.runKernelFunc(function(e,n){var o=e.softplus(t.neg()).neg();return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.neg().sigmoid())}}})}}),Xr=D({neg_:function(r){var t=_(r,"x","neg"),e=[t];return T.runKernelFunc(function(n){return n.neg(t)},{x:t},function(n){return{x:function(){return n.neg()}}},"Neg",{},e)}}),jp=D({reciprocal_:function(r){var t=_(r,"x","reciprocal");return T.runKernelFunc(function(e,n){var o=e.reciprocal(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.square().neg())}}})}}),Kp=D({round_:function(r){var t=_(r,"x","round");return T.runKernelFunc(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),xu=D({rsqrt_:function(r){var t=_(r,"x","rsqrt"),e=[t];return T.runKernelFunc(function(n,o){var a=n.rsqrt(t);return o([t]),a},{x:t},function(n,o){var a=o[0];return{x:function(){return n.div(a.pow(1.5).mul(2)).neg()}}},"Rsqrt",{},e)}}),bu=D({sigmoid_:function(r){var t=_(r,"x","sigmoid");return T.runKernelFunc(function(e,n){var o=e.sigmoid(t);return n([o]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return e.mul(o.mul(q(1).sub(o)))}}},"Sigmoid")}}),Xp=D({sign_:function(r){var t=_(r,"x","sign");return T.runKernelFunc(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),$p=D({isNaN_:function(r){var t=_(r,"x","isNaN");return T.runKernelFunc(function(e){return e.isNaN(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),Yp=D({isInf_:function(r){var t=_(r,"x","isInf");return T.runKernelFunc(function(e){return e.isInf(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}
vendor: 19,914 bytes, line 3754
3754),Jp=D({isFinite_:function(r){var t=_(r,"x","isFinite");return T.runKernelFunc(function(e){return e.isFinite(t)},{$x:t},function(e){return{$x:function(){return ve(e)}}})}}),Qp=D({sin_:function(r){var t=_(r,"x","sin"),e=[t];return T.runKernelFunc(function(n,o){var a=n.sin(t);return o([t]),a},{x:t},function(n,o){var a=o[0];return{x:function(){return a.toFloat().cos().mul(n)}}},"Sin",{},e)}}),Zp=D({sinh_:function(r){var t=_(r,"x","sinh");return T.runKernelFunc(function(e,n){var o=e.sinh(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return o.toFloat().cosh().mulStrict(e)}}})}}),ed=D({softplus_:function(r){var t=_(r,"x","softplus");return T.runKernelFunc(function(e,n){var o=e.softplus(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.mul(o.sigmoid())}}})}}),td=D({sqrt_:function(r){var t=_(r,"x","sqrt");return T.runKernelFunc(function(e,n){var o=e.sqrt(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.toFloat().sqrt().mul(2))}}})}}),nd=D({step_:function(r,t){t===void 0&&(t=0);var e=_(r,"x","step");return T.runKernelFunc(function(n){return n.step(e,t)},{$x:e},function(n){return{$x:function(){return ve(n)}}})}}),rd=D({tan_:function(r){var t=_(r,"x","tan");return T.runKernelFunc(function(e,n){var o=e.tan(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return e.div(o.cos().square())}}})}}),od=D({tanh_:function(r){var t=_(r,"x","tanh");return T.runKernelFunc(function(e,n){var o=e.tanh(t);return n([o]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return q(1).sub(o.square()).mulStrict(e)}}},"Tanh",{},null,[!0])}});function wu(r,t,e,n,o,a){var i,s,u=_(r,"x","batchNorm"),c=_(t,"mean","batchNorm"),l=_(e,"variance","batchNorm");return o!=null&&(i=_(o,"scale","batchNorm")),n!=null&&(s=_(n,"offset","batchNorm")),E(u.rank===2,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),E(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),E(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),i!=null&&E(i.rank===2||i.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),s!=null&&E(s.rank===2||s.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),fr(u,c,l,s,i,a)}function Cu(r,t,e,n,o,a){var i,s,u=_(r,"x","batchNorm"),c=_(t,"mean","batchNorm"),l=_(e,"variance","batchNorm");return o!=null&&(i=_(o,"scale","batchNorm")),n!=null&&(s=_(n,"offset","batchNorm")),E(u.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),E(c.rank===3||c.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),E(l.rank===3||l.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),i!=null&&E(i.rank===3||i.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),s!=null&&E(s.rank===3||s.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),fr(u,c,l,s,i,a)}function _u(r,t,e,n,o,a){var i,s,u=_(r,"x","batchNorm"),c=_(t,"mean","batchNorm"),l=_(e,"variance","batchNorm");return o!=null&&(i=_(o,"scale","batchNorm")),n!=null&&(s=_(n,"offset","batchNorm")),E(u.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),E(c.rank===4||c.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),E(l.rank===4||l.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),i!=null&&E(i.rank===4||i.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),s!=null&&E(s.rank===4||s.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),fr(u,c,l,s,i,a)}function fr(r,t,e,n,o,a){a==null&&(a=.001);var i,s,u,c=_(r,"x","batchNorm"),l=_(t,"mean","batchNorm"),h=_(e,"variance","batchNorm");o!=null&&(i=_(o,"scale","batchNorm")),n!=null&&(s=_(n,"offset","batchNorm")),E(l.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),E(s==null||l.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),E(i==null||l.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=c.rank===0||c.rank===1?c.as4D(1,1,1,c.size):c.rank===2?c.as4D(1,1,c.shape[0],c.shape[1]):c.rank===3?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var f=[c,l,h,i];return T.runKernelFunc(function(p,d){var g=p.batchNormalization(u,Rr(l),Rr(h),a,Rr(i),Rr(s));return d([c,l,h,i]),g},{x:c,mean:l,variance:h,scale:i,offset:s},function(p,d){var g=d,v=g[0],m=g[1],x=g[2],b=g[3],y=b??q(1),w=Me(m.shape,u.shape),C=[];if(m.rank===1){for(var S=0;S<u.shape.length-1;++S)C.push(u.shape[S]);C.push(1)}var k=v.sub(m),I=p.mul(y),R=xu(x.add(q(a))),N=R.mul(R).mul(R).mul(q(-.5));return{x:function(){return m.rank===1?p.mul(Mn(R.as4D(1,1,1,m.shape[0]),C)).mul(y).reshape(v.shape):p.mul(R).mul(y).reshape(v.shape)},mean:function(){var A=R.mul(q(-1)).mul(I);return m.rank===1&&(A=A.sum(w)),A.reshape(m.shape)},variance:function(){var A=N.mul(k).mul(I);return m.rank===1&&(A=A.sum(w)),A.reshape(m.shape)},scale:function(){var A=k.mul(R),L=p.mul(A);return m.rank===1&&(L=L.sum(w)),L.reshape(m.shape)},offset:function(){var A=p;return m.rank===1&&(A=A.sum(w)),A.reshape(m.shape)}}},"BatchNormalization",{varianceEpsilon:a},f).reshape(c.shape)}function Rr(r){return r==null?null:r.rank===0?r.as1D():r.rank===1?r:r.rank===2?r.as4D(1,1,r.shape[0],r.shape[1]):r.rank===3?r.as4D(1,r.shape[0],r.shape[1],r.shape[2]):r}function ao(){Ls("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var ad=D({batchNormalization2d_:function(r,t,e,n,o,a){return n===void 0&&(n=.001),ao(),wu(r,t,e,a,o,n)}}),id=D({batchNormalization3d_:function(r,t,e,n,o,a){return n===void 0&&(n=.001),ao(),Cu(r,t,e,a,o,n)}}),sd=D({batchNormalization4d_:function(r,t,e,n,o,a){return n===void 0&&(n=.001),ao(),_u(r,t,e,a,o,n)}}),ud=D({batchNormalization_:function(r,t,e,n,o,a){return n===void 0&&(n=.001),ao(),fr(r,t,e,a,o,n)}}),Eu=D({batchNorm_:fr}),cd=D({batchNorm2d_:wu}),ld=D({batchNorm3d_:Cu}),hd=D({batchNorm4d_:_u}),io=D({logicalAnd_:function(r,t){var e=_(r,"a","logicalAnd","bool"),n=_(t,"b","logicalAnd","bool");return le(e.shape,n.shape),T.runKernelFunc(function(o){return o.logicalAnd(e,n)},{a:e,b:n},null,"LogicalAnd")}}),fd=D({logicalNot_:function(r){var t=_(r,"x","logicalNot","bool");return T.runKernelFunc(function(e){return e.logicalNot(t)},{$x:t})}}),Iu=D({logicalOr_:function(r,t){var e=_(r,"a","logicalOr","bool"),n=_(t,"b","logicalOr","bool");return le(e.shape,n.shape),T.runKernelFunc(function(o){return o.logicalOr(e,n)},{$a:e,$b:n})}}),pd=D({logicalXor_:function(r,t){var e=_(r,"a","logicalXor","bool"),n=_(t,"b","logicalXor","bool");return le(e.shape,n.shape),Iu(r,t).logicalAnd(io(r,t).logicalNot())}}),vn=D({where_:function(r,t,e){var n=_(t,"a","where"),o=_(e,"b","where"),a=_(r,"condition","where","bool");return ye(n.shape,o.shape,"Error in where: "),a.rank===1?E(a.shape[0]===n.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):ye(a.shape,o.shape,"Error in where: "),T.runKernelFunc(function(i,s){var u=i.select(a,n,o);return s([a]),u},{$condition:a,$a:n,$b:o},function(i,s){var u=s[0];return{$condition:function(){return ve(u).toFloat()},$a:function(){return i.mul(u.cast(i.dtype))},$b:function(){return i.mul(u.logicalNot().cast(i.dtype))}}})}}),Ru=function(r){return X(this,void 0,void 0,function(){var t,e,n;return $(this,function(o){switch(o.label){case 0:return[4,(t=_(r,"condition","whereAsync","bool")).data()];case 1:return e=o.sent(),n=Aa(t.shape,e),r!==t&&t.dispose(),[2,n]}})})},ue=D({add_:function(r,t){var e,n=_(r,"a","add"),o=_(t,"b","add");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i){return i.add(n,o)},{a:n,b:o},function(i){return{a:function(){var s=i,u=Me(n.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=i,u=Me(o.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(o.shape)}}},"Add")}}),dd=D({addN_:function(r){E(Array.isArray(r),function(){return"The argument passed to tf.addN() must be a list of tensors"}),E(r.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+r.length});var t=r.map(function(o,a){return _(o,"tensors"+a,"addN")}),e=t[0];t.forEach(function(o){if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(o){if(!We(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var n=t;return T.runKernelFunc(function(o){return o.addN(t)},n,function(o){var a={};return t.forEach(function(i,s){a[s]=function(){return o.clone()}}),a},"AddN")}}),vd=D({addStrict_:function(r,t){var e=_(r,"a","addStrict"),n=_(t,"b","addStrict");return ye(e.shape,n.shape,"Error in addStrict: "),e.add(n)}}),md=D({atan2_:function(r,t){var e,n=_(r,"a","atan2"),o=_(t,"b","atan2");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i,s){var u=i.atan2(n,o);return s([n,o]),u},{$a:n,$b:o},function(i,s){var u=s[0],c=s[1];return{$a:function(){var l=ue(u.square(),c.square()),h=i.mul(c.div(l)),f=Me(u.shape,a);return f.length>0&&(h=h.sum(f)),h.reshape(u.shape)},$b:function(){var l=ue(u.square(),c.square()),h=Xr(i.mul(u.div(l))),f=Me(c.shape,a);return f.length>0&&(h=h.sum(f)),h.reshape(c.shape)}}})}}),dt=D({div_:function(r,t){var e,n=_(r,"a","div"),o=_(t,"b","div");if(e=Re(n,o),n=e[0],o=e[1],n.dtype==="int32"&&o.dtype==="int32")return ku(n,o);var a=le(n.shape,o.shape);return T.runKernelFunc(function(i,s){var u=i.realDivide(n,o);return s([n,o]),u},{a:n,b:o},function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.div(c.toFloat()),h=Me(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Me(c.shape,a);h.length>0&&(l=l.sum(h).reshape(c.shape));var f=c.square();return l.div(f.toFloat()).neg()}}},"Div")}}),gd=D({divNoNan_:function(r,t){var e,n=_(r,"a","div"),o=_(t,"b","div");n=(e=Re(n,o))[0],o=e[1];var a=dt(n,o),i=ve(a),s=o.equal(i);return vn(s,i,a)}}),yd=D({divStrict_:function(r,t){var e=_(r,"a","div"),n=_(t,"b","div");return ye(e.shape,n.shape,"Error in divideStrict: "),e.div(n)}}),ku=D({floorDiv_:function(r,t){var e,n=_(r,"a","floorDiv"),o=_(t,"b","floorDiv");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i,s){var u=i.floorDiv(n,o);return s([n,o]),u},{a:n,b:o},function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.div(c.toFloat()),h=Me(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Me(c.shape,a);h.length>0&&(l=l.sum(h).reshape(c.shape));var f=c.square();return l.div(f.toFloat()).neg()}}},"FloorDiv")}}),Ma=D({maximum_:function(r,t){var e,n=_(r,"a","maximum"),o=_(t,"b","maximum");return e=Re(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),le(n.shape,o.shape),T.runKernelFunc(function(a,i){var s=a.maximum(n,o);return i([n,o]),s},{a:n,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.greaterEqual(u).toFloat())},b:function(){return a.mul(s.less(u).toFloat())}}},"Maximum")}}),xd=D({maximumStrict_:function(r,t){var e=_(r,"a","maximumStrict"),n=_(t,"b","maximumStrict");return ye(e.shape,n.shape,"Error in maximumStrict: "),e.maximum(n)}}),Su=D({minimum_:function(r,t){var e,n=_(r,"a","minimum"),o=_(t,"b","minimum");return e=Re(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),le(n.shape,o.shape),T.runKernelFunc(function(a,i){var s=a.minimum(n,o);return i([n,o]),s},{a:n,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.lessEqual(u).toFloat())},b:function(){return a.mul(s.greater(u).toFloat())}}},"Minimum")}}),bd=D({minimumStrict_:function(r,t){var e=_(r,"a","minimumStrict"),n=_(t,"b","minimumStrict");return ye(e.shape,n.shape,"Error in minimumStrict: "),e.minimum(n)}}),wd=D({mod_:function(r,t){var e,n=_(r,"a","mod"),o=_(t,"b","mod");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i,s){var u=i.mod(n,o);return s([n,o]),u},{$a:n,$b:o},function(i,s){var u=s[0],c=s[1];return{$a:function(){var l=Me(u.shape,a);return l.length>0?i.sum(l).reshape(u.shape):i},$b:function(){var l=i.mul(u.div(c).floor().neg()),h=Me(c.shape,a);return h.length>0?l.sum(h).reshape(c.shape):l}}})}}),Cd=D({modStrict_:function(r,t){var e=_(r,"a","modStrict"),n=_(t,"b","modStrict");return ye(e.shape,n.shape,"Error in modStrict: "),e.mod(n)}}),Xe=D({mul_:function(r,t){var e,n=_(r,"a","mul"),o=_(t,"b","mul");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i,s){var u=i.multiply(n,o);return s([n,o]),u},{a:n,b:o},function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.mul(c.toFloat()),h=Me(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Me(c.shape,a);return h.length>0?l.sum(h).reshape(c.shape):l}}},"Mul")}}),_d=D({mulStrict_:function(r,t){var e=_(r,"a","mul"),n=_(t,"b","mul");return ye(e.shape,n.shape,"Error in multiplyStrict: "),e.mul(n)}}),$r=D({pow_:function(r,t){var e,n=_(r,"base","pow"),o=_(t,"exp","pow");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape),i=[n,o];return T.runKernelFunc(function(s,u){var c=s.pow(n,o);return u([n,o,c]),c},{a:n,b:o},function(s,u){var c=u[0],l=u[1],h=u[2];return{a:function(){var f=l.toFloat(),p=s.mul(f.mul(c.pow(f.sub(q(1))))),d=Me(c.shape,a);return d.length>0&&(p=p.sum(d)),p.reshape(c.shape)},b:function(){var f=c.greater(0),p=c.log().where(f,ve(c)),d=s.mul(h.mul(p)),g=Me(l.shape,a);return g.length>0&&(d=d.sum(g)),d.reshape(l.shape)}}},"Pow",{},i,[!0])}}),Ed=D({powStrict_:function(r,t){return ye(r.shape,t.shape,"Error in powStrict: "),r.pow(t)}}),Id=D({squaredDifferenceStrict_:function(r,t){var e=_(r,"a","squaredDifferenceStrict"),n=_(t,"b","squaredDifferenceStrict");return ye(e.shape,n.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(n)}}),Oe=D({sub_:function(r,t){var e,n=_(r,"a","sub"),o=_(t,"b","sub");e=Re(n,o),n=e[0],o=e[1];var a=le(n.shape,o.shape);return T.runKernelFunc(function(i){return i.subtract(n,o)},{a:n,b:o},function(i){return{a:function(){var s=i,u=Me(n.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=i,u=Me(o.shape,a);return u.length>0&&(s=s.sum(u)),s.neg().reshape(o.shape)}}},"Sub")}}),Rd=D({subStrict_:function(r,t){var e=_(r,"a","subStrict"),n=_(t,"b","subStrict");return ye(e.shape,n.shape,"Error in subStrict: "),e.sub(n)}}),Du=D({equal_:function(r,t){var e,n=_(r,"a","equal"),o=_(t,"b","equal");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a){return a.equal(n,o)},{$a:n,$b:o})}}),kd=D({equalStrict_:function(r,t){var e=_(r,"a","equalStrict"),n=_(t,"b","equalStrict");return ye(e.shape,n.shape,"Error in equalStrict: "),e.equal(n)}}),Sd=D({greater_:function(r,t){var e,n=_(r,"a","greater"),o=_(t,"b","greater");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a){return a.greater(n,o)},{a:n,b:o},null,"Greater")}}),Au=D({greaterEqual_:function(r,t){var e,n=_(r,"a","greaterEqual"),o=_(t,"b","greaterEqual");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a,i){var s=a.greaterEqual(n,o);return i([n,o]),s},{a:n,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return ve(s)},b:function(){return ve(u)}}},"GreaterEqual")}}),Dd=D({greaterEqualStrict_:function(r,t){var e=_(r,"a","greaterEqualStrict"),n=_(t,"b","greaterEqualStrict");return ye(e.shape,n.shape,"Error in greaterEqualStrict: "),e.greaterEqual(n)}}),Ad=D({greaterStrict_:function(r,t){var e=_(r,"a","greaterStrict"),n=_(t,"b","greaterStrict");return ye(e.shape,n.shape,"Error in greaterStrict: "),e.greater(n)}}),Td=D({less_:function(r,t){var e,n=_(r,"a","less"),o=_(t,"b","less");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a){return a.less(n,o)},{a:n,b:o},null,"Less")}}),Nd=D({lessEqual_:function(r,t){var e,n=_(r,"a","lessEqual"),o=_(t,"b","lessEqual");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a,i){var s=a.lessEqual(n,o);return i([n,o]),s},{a:n,b:o},null,"LessEqual")}}),Fd=D({lessEqualStrict_:function(r,t){var e=_(r,"a","lessEqualStrict"),n=_(t,"b","lessEqualStrict");return ye(e.shape,n.shape,"Error in lessEqualStrict: "),e.lessEqual(n)}}),Pd=D({lessStrict_:function(r,t){var e=_(r,"a","lessStrict"),n=_(t,"b","lessStrict");return ye(e.shape,n.shape,"Error in lessStrict: "),e.less(n)}}),Md=D({notEqual_:function(r,t){var e,n=_(r,"a","notEqual"),o=_(t,"b","notEqual");return e=Re(n,o),n=e[0],o=e[1],le(n.shape,o.shape),T.runKernelFunc(function(a){return a.notEqual(n,o)},{a:n,b:o},null,"NotEqual")}}),Od=D({notEqualStrict_:function(r,t){var e=_(r,"a","notEqualStrict"),n=_(t,"b","notEqualStrict");return ye(e.shape,n.shape,"Error in notEqualStrict: "),e.notEqual(n)}});function es(r,t){for(var e=[],n=r;n<t;++n)e.push(n);return e}function ts(r){for(var t=[],e=0;e<r.length;++e)for(var n=0;n<r[e].length;++n)t.push(r[e][n]);return t}var Oa=D({gather_:function(r,t,e){e===void 0&&(e=0);var n=_(r,"x","gather"),o=_(t,"indices","gather","int32");e=Be(e,n.shape)[0];var a=function(i,s,u){for(var c=i.shape[u],l=[],h=1,f=1,p=0;p<u;p++)l.push(i.shape[p]),h*=i.shape[p];for(p=0;p<s.rank;p++)l.push(s.shape[p]);for(p=u+1;p<i.rank;p++)l.push(i.shape[p]),f*=i.shape[p];return{batchSize:h,sliceSize:f,dimSize:c,outputShape:l}}(n,o,e);return T.runKernelFunc(function(i,s){var u=i.gather(n,o.flatten(),e);return s([o]),u},{x:n,indices:o},function(i,s){var u=s[0];return{x:function(){var c=n.shape,l=u.size,h=c.slice(0,e),f=h.length,p=c.slice(e,c.length).slice(1),d=p.length,g=es(0,f),v=es(f+1,f+1+d),m=ts([h,[l],p]),x=i.reshape(m),b=u.reshape([l]),y=ts([[f],g,v]),w=x.transpose(y),C=Tu(w,b,n.shape[e]),S=Ca(y);return C=C.transpose(S)},indices:function(){return u}}},"Gather",{axis:e}).reshape(a.outputShape)}}),Tu=D({unsortedSegmentSum_:function(r,t,e){var n=_(r,"x","unsortedSegmentSum"),o=_(t,"segmentIds","unsortedSegmentSum","int32");return E(Ae(e),function(){return"numSegments must be of dtype int"}),T.runKernelFunc(function(a,i){var s=a.unsortedSegmentSum(n,o,e);return i([o]),s},{$x:n},function(a,i){var s=i[0];return{$x:function(){return function(u,c){for(var l=Ma(c,ve(c)),h=Oa(u,l),f=Au(c,q(0,"int32")),p=h.rank-f.rank,d=0;d<p;++d)f=lt(f,d+1);f=io(f,Kn(h.shape,"bool"));var g=ve(h);return vn(f,h,g)}(a,s)}}})}}),Bd=function(r,t,e){return X(this,void 0,void 0,function(){var n,o,a,i,s,u,c,l,h,f,p,d,g;return $(this,function(v){switch(v.label){case 0:for(n=_(r,"tensor","boolMask"),o=_(t,"mask","boolMask","bool"),a=e??0,i=o.rank,s=n.shape,E(i>0,function(){return"mask cannot be scalar"}),ye(s.slice(a,a+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,c=a;c<a+i;c++)u*=s[c];return l=s.slice(0,a).concat([u],s.slice(a+i)),h=n.reshape(l),f=o.reshape([-1]),[4,Ru(f)];case 1:return p=v.sent(),d=p.squeeze([1]),g=Oa(h,d,a),r!==n&&n.dispose(),t!==o&&o.dispose(),d.dispose(),h.dispose(),f.dispose(),p.dispose(),[2,g]}})})};function Nu(r,t,e,n,o,a,i){a===void 0&&(a="NHWC"),E(r.length===t.rank,function(){return"Length of inShape ("+r.length+") and rank of dy ("+t.rank+") must match"});var s=r,u=t,c=!1;t.rank===3&&(c=!0,u=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),s=[1,r[0],r[1],r[2]]),E(s.length===4,function(){return"Error in conv2dDerIn
3754put: inShape must be length 4, but got length "+s.length+"."}),E(u.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank}),E(e.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+e.rank});var l=a==="NHWC"?s[3]:s[1],h=a==="NHWC"?u.shape[3]:u.shape[1];E(l===e.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+e.shape[2]+"."}),E(h===e.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+e.shape[3]+"."}),i!=null&&E(Ae(o),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var f=ka(a),p=bn(s,e.shape,n,1,o,i,!1,f),d=T.runKernelFunc(function(g,v){var m=g.conv2dDerInput(u,e,p);return v([e,u]),m},{dy4D:u,filter:e},function(g,v){var m=v[0],x=v[1];return{dy4D:function(){return pt(g,m,n,o,a,1,i)},filter:function(){return Ba(g,x,m.shape,n,o,a,i)}}});return c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function Wo(r){var t=function(a){return typeof a=="number"?[a,a,a]:a.length===2?[a[0],a[1],1]:a}(r),e=t[0],n=t[1],o=t[2];return e===1&&n===1&&o===1}function Fu(r,t,e,n,o){E(r.length===t.rank,function(){return"Length of inShape ("+r.length+") and rank of dy ("+t.rank+") must match"});var a=r,i=t,s=!1;t.rank===4&&(s=!0,i=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),a=[1,r[0],r[1],r[2],r[3]]);var u=a[4],c=i.shape[4];E(a.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."}),E(i.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank}),E(e.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+e.rank}),E(u===e.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+e.shape[3]+"."}),E(c===e.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+e.shape[4]+"."});var l=jr(a,e.shape,n,1,o),h=T.runKernelFunc(function(f){return f.conv3dDerInput(i,e,l)},{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var Ld=D({conv1d_:function(r,t,e,n,o,a,i){o===void 0&&(o="NWC"),a===void 0&&(a=1);var s=_(r,"x","conv1d"),u=_(t,"filter","conv1d"),c=s,l=!1;s.rank===2&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),E(c.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."}),E(u.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),i!=null&&E(Ae(n),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+"."}),E(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]+"."}),E(tt(e,a),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+e+" and dilation '"+a+"'"}),E(o==="NWC",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=pt(f,h,[1,e],n,"NHWC",[1,a],i);return l?p.as2D(p.shape[2],p.shape[3]):p.as3D(p.shape[0],p.shape[2],p.shape[3])}}),pt=D({conv2d_:function(r,t,e,n,o,a,i){o===void 0&&(o="NHWC"),a===void 0&&(a=[1,1]);var s=_(r,"x","conv2d"),u=_(t,"filter","conv2d"),c=s,l=!1;s.rank===3&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),E(c.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."}),E(u.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),i!=null&&E(Ae(n),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+"."});var h=o==="NHWC"?c.shape[3]:c.shape[1];E(h===u.shape[2],function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."}),E(tt(e,a),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+a+"'"});var f=ka(o),p=bn(c.shape,u.shape,e,a,n,i,!1,f),d=[u,c],g=T.runKernelFunc(function(v,m){var x=v.conv2d(c,u,p);return m([u,c]),x},{x:c,filter:u},function(v,m){var x=m,b=x[0],y=x[1];return E(qn(a),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"}),{x:function(){return Pu(y.shape,v,b,e,n,o)},filter:function(){return Ba(y,v,b.shape,e,n,o)}}},"Conv2D",p,d);return l?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),Wd=D({conv3d_:function(r,t,e,n,o,a){o===void 0&&(o="NDHWC"),a===void 0&&(a=[1,1,1]);var i=_(r,"x","conv3d"),s=_(t,"filter","conv3d"),u=i,c=!1;i.rank===4&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),E(u.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),E(s.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),E(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]+"."}),E(function(f,p){return Wo(f)||Wo(p)}(e,a),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+a+"'"}),E(o==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."});var l=jr(u.shape,s.shape,e,a,n),h=T.runKernelFunc(function(f,p){var d=f.conv3d(u,s,l);return p([u,s]),d},{x:u,$filter:s},function(f,p){E(Wo(a),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"});var d=p[0],g=p[1];return{x:function(){return Fu(d.shape,f,g,e,n)}
vendor: 54,893 bytes, lines 3754-3755
3754,$filter:function(){return function(v,m,x,b,y){var w=v;v.rank===4&&(w=v.as5D(1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]));var C=m;C.rank===4&&(C=m.as5D(1,m.shape[0],m.shape[1],m.shape[2],m.shape[3])),E(w.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+w.shape+"."}),E(C.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+C.shape+"."}),E(x.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+x+"."}),E(w.shape[4]===x[3],function(){return"Error in conv3dDerFilter: depth of input "+w.shape[4]+") must match input depth in filter ("+x[3]+"."}),E(C.shape[4]===x[4],function(){return"Error in conv3dDerFilter: depth of dy ("+C.shape[4]+") must match output depth for filter ("+x[4]+")."});var S=jr(w.shape,x,b,1,y);return T.runKernelFunc(function(k){return k.conv3dDerFilter(w,C,S)},{x5D:w,dy5D:C})}(d,f,g.shape,e,n)}}});return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Ba=D({conv2dDerFilter_:function(r,t,e,n,o,a,i){a===void 0&&(a="NHWC");var s=r;r.rank===3&&(s=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var u=t;u.rank===3&&(u=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),E(s.rank===4,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."}),E(u.rank===4,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."}),E(e.length===4,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+e+"."});var c=a==="NHWC"?s.shape[3]:s.shape[1],l=a==="NHWC"?u.shape[3]:u.shape[1];E(c===e[2],function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+e[2]+"."}),E(l===e[3],function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+e[3]+")."}),i!=null&&E(Ae(o),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var h=ka(a),f=bn(s.shape,e,n,1,o,i,!1,h);return T.runKernelFunc(function(p){return p.conv2dDerFilter(s,u,f)},{x4D:s,dy4D:u})}}),Pu=D({conv2dDerInput_:Nu}),so=D({depthwiseConv2d_:function(r,t,e,n,o,a,i){a===void 0&&(a=[1,1]);var s=_(r,"x","depthwiseConv2d"),u=_(t,"filter","depthwiseConv2d"),c=s,l=!1;s.rank===3&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),E(c.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."}),E(u.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),E(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]+"."}),a==null&&(a=[1,1]),E(tt(e,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+a+"'"}),i!=null&&E(Ae(n),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+"."});var h=bn(c.shape,u.shape,e,a,n,i,!0),f=[c,u],p=T.runKernelFunc(function(d,g){var v=d.depthwiseConv2D(c,u,h);return g([c,u]),v},{x:c,filter:u},function(d,g){E(qn(a),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+a+"'"});var v=g[0],m=g[1];return{x:function(){return Mu(v.shape,d,m,h)},filter:function(){return Ou(v,d,m.shape,h)}}},"DepthwiseConv2dNative",h,f);return l?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),Mu=D({depthwiseConv2dDerInput_:function(r,t,e,n){var o=t,a=!1;t.rank===3&&(a=!0,o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=T.runKernelFunc(function(s){return s.depthwiseConv2DDerInput(o,e,n)},{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),Ou=D({depthwiseConv2dDerFilter_:function(r,t,e,n){var o=r;r.rank===3&&(o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=t;return a.rank===3&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),T.runKernelFunc(function(i){return i.depthwiseConv2DDerFilter(o,a,n)},{x4D:o,dy4D:a})}}),La=D({separableConv2d_:function(r,t,e,n,o,a,i){a===void 0&&(a=[1,1]),i===void 0&&(i="NHWC");var s=_(r,"x","separableConv2d"),u=_(t,"depthwiseFilter","separableConv2d"),c=_(e,"pointwiseFilter","separableConv2d"),l=s,h=!1;if(s.rank===3&&(h=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");E(l.rank===4,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."}),E(u.rank===4,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),E(c.rank===4,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),E(c.shape[0]===1,function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+c.shape[0]+"."}),E(c.shape[1]===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];E(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=so(l,u,n,o,i,a),g=pt(d,c,1,"valid",i);return h?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),Ud=D({conv2dTranspose_:function(r,t,e,n,o,a){return Nu(e,_(r,"x","conv2dTranspose"),_(t,"filter","conv2dTranspose"),n,o,"NHWC",a)}}),Vd=D({conv3dTranspose_:function(r,t,e,n,o){return Fu(e,_(r,"x","conv3dTranspose"),_(t,"filter","conv3dTranspose"),n,o)}}),uo=D({matMul_:function(r,t,e,n){var o;e===void 0&&(e=!1),n===void 0&&(n=!1);var a=_(r,"a","matMul"),i=_(t,"b","matMul");o=Re(a,i),a=o[0],i=o[1];var s=e?a.shape[a.rank-2]:a.shape[a.rank-1],u=n?i.shape[i.rank-1]:i.shape[i.rank-2],c=e?a.shape[a.rank-1]:a.shape[a.rank-2],l=n?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),f=i.shape.slice(0,-2),p=Y(h),d=Y(f);E(a.rank>=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),E(We(h,f),function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),E(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+e+" and transposeB="+n+" must match."});var g=a.shape.slice(0,-2).concat([c,l]),v=e?a.as3D(p,s,c):a.as3D(p,c,s),m=n?i.as3D(d,l,u):i.as3D(d,u,l),x={transposeA:e,transposeB:n};return T.runKernelFunc(function(b,y){var w=b.batchMatMul(v,m,e,n);return y([v,m]),w},{a:v,b:m},function(b,y){var w=y,C=w[0],S=w[1];return e||n?!e&&n?{a:function(){return b.matMul(S,!1,!1)},b:function(){return b.matMul(C,!0,!1)}}:e&&!n?{a:function(){return S.matMul(b,!1,!0)},b:function(){return C.matMul(b,!1,!1)}}:{a:function(){return S.matMul(b,!0,!0)},b:function(){return b.matMul(C,!0,!0)}}:{a:function(){return b.matMul(S,!1,!0)},b:function(){return C.matMul(b,!0,!1)}}},"BatchMatMul",x).reshape(g)}}),zd=D({dot_:function(r,t){var e=_(r,"t1","dot"),n=_(t,"t2","dot");E(!(e.rank!==1&&e.rank!==2||n.rank!==1&&n.rank!==2),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+n.rank+"."});var o=e.rank===1?e.size:e.shape[1],a=n.rank===1?n.size:n.shape[0];return E(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),e.rank===1&&n.rank===1?e.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():e.rank===1&&n.rank===2?e.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():e.rank===2&&n.rank===1?e.matMul(n.as2D(-1,1)).as1D():e.matMul(n.as2D(n.shape[0],n.shape[1]))}}),Gd=D({outerProduct_:function(r,t){var e=_(r,"v1","outerProduct"),n=_(t,"v2","outerProduct");return E(e.rank===1&&n.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+n.rank+"."}),e.as2D(-1,1).matMul(n.as2D(1,-1))}}),pr=D({reverse_:function(r,t){var e=_(r,"x","reverse");if(e.rank===0)return e.clone();var n=Be(t,e.shape);return T.runKernelFunc(function(o){return o.reverse(e,n)},{$x:e},function(o){return{$x:function(){return o.reverse(n)}}}).reshapeAs(e)}}),Hd=D({reverse1d_:function(r){var t=_(r,"x","reverse");return E(t.rank===1,function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."}),pr(t,0)}}),qd=D({reverse2d_:function(r,t){var e=_(r,"x","reverse");return E(e.rank===2,function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."}),pr(e,t)}}),jd=D({reverse3d_:function(r,t){var e=_(r,"x","reverse");return E(e.rank===3,function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."}),pr(e,t)}}),Kd=D({reverse4d_:function(r,t){var e=_(r,"x","reverse");return E(e.rank===4,function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."}),pr(e,t)}});function Bu(r,t,e,n,o,a){var i=_(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(s.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),E(tt(e,n),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"}),a!=null&&E(Ae(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var c=or(s.shape,t,e,n,o,a);if(c.filterWidth===1&&c.filterHeight===1&&We(c.inShape,c.outShape))return i.clone();var l=[s],h=T.runKernelFunc(function(f,p){var d=f.maxPool(s,c);return p([s,d]),d},{x:s},function(f,p){var d=p[0],g=p[1];return{x:function(){return function(v,m,x,b,y,w,C,S){var k=_(v,"dy","maxPoolBackprop"),I=_(m,"input","maxPoolBackprop"),R=_(x,"output","maxPoolBackprop");E(I.rank===k.rank,function(){return"Rank of input ("+I.rank+") does not match rank of dy ("+k.rank+")"}),E(tt(y,w),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+y+" and dilations '"+w+"'"}),E(k.rank===4,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+k.rank+"."}),E(I.rank===4,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+I.rank+"."});var N=or(I.shape,b,y,w,C,S);return T.runKernelFunc(function(A){return A.maxPoolBackprop(k,I,R,N)},{$dy:k,$input:I})}(f,d,g,t,e,n,o)}}},"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function Lu(r,t,e,n,o,a){var i=_(r,"x","avgPool","float32");E(tt(e,n),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"});var s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(s.rank===4,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),a!=null&&E(Ae(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var c=or(s.shape,t,e,n,o,a);if(c.filterWidth===1&&c.filterHeight===1&&We(c.inShape,c.outShape))return i.clone();var l=T.runKernelFunc(function(h){return h.avgPool(s,c)},{x:s},function(h){return{x:function(){return function(f,p,d,g,v,m){var x=_(f,"dy","avgPoolBackprop"),b=_(p,"input","avgPoolBackprop");E(b.rank===x.rank,function(){return"Rank of input ("+b.rank+") does not match rank of dy ("+x.rank+")"}),E(tt(g,v),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+g+" and dilations '"+v+"'"});var y=b,w=x,C=!1;b.rank===3&&(C=!0,y=b.as4D(1,b.shape[0],b.shape[1],b.shape[2]),w=x.as4D(1,x.shape[0],x.shape[1],x.shape[2])),E(w.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+w.rank+"."}),E(y.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+y.rank+"."});var S=or(y.shape,d,g,v,m),k=T.runKernelFunc(function(I){return I.avgPoolBackprop(w,y,S)},{dy4D:w,input4D:y});return C?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k}(h,s,t,e,n,o)}}},"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var Le=D({maxPool_:function(r,t,e,n,o){return Bu(r,t,e,1,n,o)}}),dr=D({avgPool_:function(r,t,e,n,o){return Lu(r,t,e,1,n,o)}}),Xd=D({pool_:function(r,t,e,n,o,a){o==null&&(o=[1,1]),a==null&&(a=1),n===0&&(n="valid");var i=_(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(tt(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var c,l=or(s.shape,t,a,o,n),h=[l.dilationHeight,l.dilationWidth];c=n==="same"?function(y,w){var C=y.map(function(I,R){return I+(I-1)*(w[R]-1)}).map(function(I){return I-1}),S=C.map(function(I){return Math.floor(I/2)}),k=C.map(function(I,R){return I-S[R]});return C.map(function(I,R){return[S[R],k[R]]})}([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var f=h[0]===1&&h[1]===1,p=function(y,w,C){var S=C.map(function(O){return O[0]}),k=C.map(function(O){return O[1]}),I=y.concat(S,k),R=w.map(function(O,B){return(O-I[B]%O)%O}),N=k.map(function(O,B){return O+R[B]}),A=w.map(function(O,B){return[S[B],N[B]]}),L=w.map(function(O,B){return[0,R[B]]});return[A,L]}([l.inHeight,l.inWidth],h,c),d=p[0],g=p[1],v=f?n:"valid",m=f?s:Hs(s,h,d),x=(e==="avg"?function(){return Lu(m,t,a,1,v)}:function(){return Bu(m,t,a,1,v)})(),b=f?x:Vs(x,h,g);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),$d=D({maxPool3d_:function(r,t,e,n,o,a,i){a===void 0&&(a="NDHWC");var s=_(r,"x","maxPool3d"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),E(u.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),E(a==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),E(tt(e,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),o!=null&&E(Ae(n),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."});var l=qr(u.shape,t,e,i,n,o,a),h=T.runKernelFunc(function(f,p){var d=f.maxPool3d(u,l);return p([u,d]),d},{x:u},function(f,p){var d=p[0],g=p[1];return{x:function(){return function(v,m,x,b,y,w,C,S){var k=_(v,"dy","maxPool3dBackprop"),I=_(m,"input","maxPool3dBackprop"),R=_(x,"output","maxPool3dBackprop"),N=k,A=I,L=R,O=!1;I.rank===4&&(O=!0,N=k.as5D(1,k.shape[0],k.shape[1],k.shape[2],k.shape[3]),A=I.as5D(1,I.shape[0],I.shape[1],I.shape[2],I.shape[3]),L=R.as5D(1,R.shape[0],R.shape[1],R.shape[2],R.shape[3])),E(N.rank===5,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+N.rank+"."}),E(A.rank===5,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+A.rank+"."}),E(L.rank===5,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+L.rank+"."}),w==null&&(w=[1,1,1]),E(tt(y,w),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+y+" and dilations '"+w+"'"}),S!=null&&E(Ae(C),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+S+" but got pad "+C+"."});var B=qr(A.shape,b,y,w,C,S),V=T.runKernelFunc(function(U){return U.maxPool3dBackprop(N,A,L,B)},{dy5D:N,input5D:A});return O?V.as4D(V.shape[1],V.shape[2],V.shape[3],V.shape[4]):V}(f,d,g,t,e,i,n,o)}}});return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Yd=D({avgPool3d_:function(r,t,e,n,o,a,i){a===void 0&&(a="NDHWC");var s=_(r,"x","avgPool3d","float32"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),E(u.rank===5,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),E(a==="NDHWC",function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),E(tt(e,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),o!=null&&E(Ae(n),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."});var l=qr(u.shape,t,e,i,n,o,a),h=T.runKernelFunc(function(f){return f.avgPool3d(u,l)},{x:u},function(f){return{x:function(){return function(p,d,g,v,m,x,b){var y=_(p,"dy","avgPool3dBackprop"),w=_(d,"input","avgPool3dBackprop"),C=y,S=w,k=!1;w.rank===4&&(k=!0,C=y.as5D(1,y.shape[0],y.shape[1],y.shape[2],y.shape[3]),S=w.as5D(1,w.shape[0],w.shape[1],w.shape[2],w.shape[3])),E(C.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+C.rank+"."}),E(S.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+S.rank+"."}),m==null&&(m=[1,1,1]),E(tt(v,m),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+v+" and dilations '"+m+"'"}),b!=null&&E(Ae(x),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+b+" but got pad "+x+"."});var I=qr(S.shape,g,v,m,x,b),R=T.runKernelFunc(function(N){return N.avgPool3dBackprop(C,S,I)},{dy5D:C,input5D:S});return k?R.as4D(R.shape[1],R.shape[2],R.shape[3],R.shape[4]):R}(f,u,t,e,i,n,o)}}});return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Tt=D({slice_:function(r,t,e){var n,o,a=_(r,"x","slice");if(a.rank===0)throw new Error("Slicing scalar is not possible");(n=typeof t=="number"?[t].concat(new Array(a.rank-1).fill(0)):t.length<a.rank?t.concat(new Array(a.rank-t.length).fill(0)):t.slice()).forEach(function(u){E(u!==-1,function(){return"slice() does not support negative begin indexing."})}),o=(o=e==null?new Array(a.rank).fill(-1):typeof e=="number"?[e].concat(new Array(a.rank-1).fill(-1)):e.length<a.rank?e.concat(new Array(a.rank-e.length).fill(-1)):e).map(function(u,c){return u>=0?u:(E(u===-1,function(){return"Negative size values should be exactly -1 but got "+u+" for the slice() size at index "+c+"."}),a.shape[c]-n[c])}),_h(a,n,o);var i=a.shape,s={begin:n,size:o};return T.runKernelFunc(function(u){return u.slice(a,n,o)},{x:a},function(u){for(var c=[],l=0;l<u.rank;l++)c.push([n[l],i[l]-n[l]-o[l]]);return{x:function(){return u.pad(c)}}},"Slice",s)}}),Jd=D({slice1d_:function(r,t,e){var n=_(r,"x","slice1d");return E(n.rank===1,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+n.rank+" tensor"}),Tt(n,[t],[e])}}),Qd=D({slice2d_:function(r,t,e){var n=_(r,"x","slice2d");return E(n.rank===2,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+n.rank+" tensor"}),Tt(n,t,e)}}),Wu=D({slice3d_:function(r,t,e){var n=_(r,"x","slice3d");return E(n.rank===3,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+n.rank+" tensor"}),Tt(n,t,e)}}),Zd=D({slice4d_:function(r,t,e){var n=_(r,"x","slice4d");return E(n.rank===4,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+n.rank+" tensor"}),Tt(n,t,e)}});function Uu(r,t,e,n,o){return t.rank<e.rank&&(t=t.reshape(et(t.shape,n))),r.rank<e.rank&&(r=r.reshape(et(r.shape,n))),{x:function(){var a=r.mul(e.equal(t).cast(r.dtype));return o==null?a:a.transpose(o)}}}var ev=D({all_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","all","bool"),o=Be(t,n.shape),a=o,i=Ft(a,n.rank);i!=null&&(n=n.transpose(i),a=Pt(a.length,n.rank));var s=T.runKernelFunc(function(c){return c.all(n,a)},{$x:n});if(e){var u=et(s.shape,o);return s.reshape(u)}return s}}),tv=D({any_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","any","bool"),o=Be(t,n.shape),a=o,i=Ft(a,n.rank);i!=null&&(n=n.transpose(i),a=Pt(a.length,n.rank));var s=T.runKernelFunc(function(c){return c.any(n,a)},{$x:n});if(e){var u=et(s.shape,o);return s.reshape(u)}return s}}),nv=D({argMax_:function(r,t){t===void 0&&(t=0);var e=_(r,"x","argMax");t==null&&(t=0);var n=Be(t,e.shape),o=Ft(n,e.rank);o!=null&&(e=e.transpose(o),n=Pt(n.length,e.rank));var a={axis:n[0]},i=[e];return T.runKernelFunc(function(s,u){var c=s.argMax(e,n[0]);return u([e]),c},{x:e},function(s,u){var c=u[0];return{x:function(){return ve(c)}}},"ArgMax",a,i)}}),rv=D({argMin_:function(r,t){t===void 0&&(t=0);var e=_(r,"x","argMin");t==null&&(t=0);var n=Be(t,e.shape),o=Ft(n,e.rank);return o!=null&&(e=e.transpose(o),n=Pt(n.length,e.rank)),T.runKernelFunc(function(a,i){var s=a.argMin(e,n[0]);return i([e]),s},{$x:e},function(a,i){var s=i[0];return{$x:function(){return ve(s)}}})}}),ov=D({logSumExp_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","logSumExp"),o=Be(t,n.shape),a=n.max(o,!0),i=n.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(e){var u=et(s.shape,o);return s.reshape(u)}return s}}),co=D({max_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","max"),o=n,a=Be(t,n.shape),i=a,s=Ft(i,n.rank);s!=null&&(n=n.transpose(s),i=Pt(i.length,n.rank));var u=[n],c=T.runKernelFunc(function(h,f){var p=h.max(n,i);return f([o,p]),p},{x:n},function(h,f){return Uu(h,f[1],f[0],a,s)},"Max",{axes:i},u,[!0]);if(e){var l=et(c.shape,a);c=c.reshape(l)}return c}}),av=D({mean_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","mean"),o=Be(t,n.shape),a=Y(He(n.shape,o)[1]);return oo(function(i){var s=q(a);return{value:(s.dtype===i.dtype?i:i.cast(s.dtype)).div(s).sum(t,e),gradFunc:function(u){var c=i.shape.slice();return o.forEach(function(l){c[l]=1}),u.reshape(c).mul(Kn(i.shape,"float32")).div(a)}}})(n)}}),iv=D({min_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","min"),o=n,a=Be(t,n.shape),i=a,s=Ft(i,n.rank);s!=null&&(n=n.transpose(s),i=Pt(i.length,n.rank));var u=[n],c=T.runKernelFunc(function(h,f){var p=h.min(n,i);return f([o,p]),p},{x:n},function(h,f){return Uu(h,f[1],f[0],a,s)},"Min",{axes:i},u,[!0]);if(e){var l=et(c.shape,a);c=c.reshape(l)}return c}}),sv=D({moments_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=Be(t,(r=_(r,"x","moments")).shape),o=r.mean(n,e),a=o.shape;e||(a=et(o.shape,n));var i=r.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(n,e)}}}),Vu=D({sum_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","sum");n.dtype==="bool"&&(n=n.toInt());var o=Be(t,n.shape);return oo(function(a){var i=Ft(o,a.rank),s=o,u=a;i!=null&&(u=a.transpose(i),s=Pt(s.length,a.rank));var c=function(p){var d=a.shape.slice();return o.forEach(function(g){d[g]=1}),p.reshape(d).mul(Kn(a.shape,"float32"))},l={axes:s},h=T.runKernelFunc(function(p){return p.sum(u,s)},{x:u},function(p){return{x:function(){return c(p)}}},"Sum",l);if(e){var f=et(h.shape,o);h=h.reshape(f)}return{value:h,gradFunc:c}})(n)}}),uv=D({prod_:function(r,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var n=_(r,"x","prod");n.dtype==="bool"&&(n=n.toInt());var o=Be(t,n.shape),a=Ft(o,n.rank),i=o,s=n;a!=null&&(s=n.transpose(a),i=Pt(i.length,n.rank));var u=T.runKernelFunc(function(l){return l.prod(s,i)},{permutedX:s});if(e){var c=et(u.shape,o);u=u.reshape(c)}return u}}),zu=D({elu_:function(r){var t=_(r,"x","elu");return T.runKernelFunc(function(e,n){var o=e.elu(t);return n([o]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){return T.runKernelFunc(function(a){return a.eluDer(e,o)},{dy:e,y:o})}}})}}),cv=D({leakyRelu_:function(r,t){t===void 0&&(t=.2);var e=_(r,"x","leakyRelu");return Ma(q(t).mul(e),e)}}),Gu=D({prelu_:function(r,t){var e=_(r,"x","prelu"),n=_(t,"alpha","prelu");return T.runKernelFunc(function(o,a){var i=o.prelu(e,n);return a([e,n]),i},{x:e,alpha:n},function(o,a){var i=a[0],s=a[1],u=i.greater(0);return{x:function(){return vn(u,o,o.mul(s))},alpha:function(){var c=vn(u,ve(o),o.mul(i)),l=Me(s.shape,o.shape);return l.length>0&&(c=c.sum(l)),c.reshape(s.shape)}}},"Prelu")}}),Ie=D({relu_:function(r){var t=_(r,"x","relu");return t.dtype==="bool"?t.toInt():T.runKernelFunc(function(e,n){var o=e.relu(t);return n([t]),o},{x:t},function(e,n){var o=n[0];return{x:function(){return e.mulStrict(o.step().toFloat())}}},"Relu")}}),Hu=D({relu6_:function(r){var t=_(r,"x","relu6");return t.dtype==="bool"?t.toInt():T.runKernelFunc(function(e,n){var o=e.relu6(t);return n([t]),o},{x:t},function(e,n){var o=n[0],a=o.lessEqual(6).mul(o.step());return{x:function(){return e.mulStrict(a.toFloat())}}},"Relu6")}}),lv=D({selu_:function(r){var t=_(r,"x","selu");return T.runKernelFunc(function(e,n){var o=e.selu(t);return n([t]),o},{$x:t},function(e,n){var o=n[0];return{$x:function(){var a=o.greater(q(0)),i=q(Na),s=q(Fa),u=e.mul(s),c=e.mul(i).mul(o.toFloat().exp());return vn(a,u,c)}}})}}),nn=D({transpose_:function(r,t){var e=_(r,"x","transpose");if(t==null&&(t=e.shape.map(function(o,a){return a}).reverse()),E(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of perm "+t+"."}),t.forEach(function(o){E(o>=0&&o<e.rank,function(){return"All entries in 'perm' must be between 0 and "+(e.rank-1)+" but got "+t})}),e.rank<=1)return e.clone();var n={perm:t};return T.runKernelFunc(function(o){return o.transpose(e,t)},{x:e},function(o){var a=Ca(t);return{x:function(){return o.transpose(a)}}},"Transpose",n)}}),hv=D({localResponseNormalization_:function(r,t,e,n,o){t===void 0&&(t=5),e===void 0&&(e=1),n===void 0&&(n=1),o===void 0&&(o=.5);var a=_(r,"x","localResponseNormalization");E(a.rank===4||a.rank===3,function(){return`Error in localResponseNormalization: x must be rank 3 or 4 but got
3755               rank `+a.rank+"."}),E(Ae(t),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+t+"."});var i=a,s=!1;a.rank===3&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=T.runKernelFunc(function(c,l){var h=c.localResponseNormalization4D(i,t,e,n,o);return l([i,h]),h},{x4D:i},function(c,l){var h=l[0],f=l[1];return{x4D:function(){return T.runKernelFunc(function(p){return p.LRNGrad(c,h,f,t,e,n,o)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),qu=D({norm_:function(r,t,e,n){t===void 0&&(t="euclidean"),e===void 0&&(e=null),n===void 0&&(n=!1);var o=function s(u,c,l){if(l===void 0&&(l=null),u.rank===0)return u.abs();if(u.rank!==1&&l===null)return s(u.reshape([-1]),c,l);if(u.rank===1||typeof l=="number"||Array.isArray(l)&&l.length===1){if(c===1)return u.abs().sum(l);if(c===1/0)return u.abs().max(l);if(c===-1/0)return u.abs().min(l);if(c==="euclidean"||c===2)return u.abs().pow(q(2,"int32")).sum(l).sqrt();throw new Error("Error in norm: invalid ord value: "+c)}if(Array.isArray(l)&&l.length===2){if(c===1)return u.abs().sum(l[0]).max(l[1]-1);if(c===1/0)return u.abs().sum(l[1]).max(l[0]);if(c===-1/0)return u.abs().sum(l[1]).min(l[0]);if(c==="fro"||c==="euclidean")return u.square().sum(l).sqrt();throw new Error("Error in norm: invalid ord value: "+c)}throw new Error("Error in norm: invalid axis: "+l)}(r=_(r,"x","norm"),t,e),a=o.shape;if(n){var i=Be(e,r.shape);a=et(o.shape,i)}return o.reshape(a)}}),fv=D({basicLSTMCell_:function(r,t,e,n,o,a){var i=_(r,"forgetBias","basicLSTMCell"),s=_(t,"lstmKernel","basicLSTMCell"),u=_(e,"lstmBias","basicLSTMCell"),c=_(n,"data","basicLSTMCell"),l=_(o,"c","basicLSTMCell"),h=_(a,"h","basicLSTMCell"),f=c.concat(h,1).matMul(s).add(u),p=f.shape[0],d=f.shape[1]/4,g=[p,d],v=f.slice([0,0],g),m=f.slice([0,d],g),x=f.slice([0,2*d],g),b=f.slice([0,3*d],g),y=v.sigmoid().mulStrict(m.tanh()).addStrict(l.mulStrict(i.add(x).sigmoid())),w=y.tanh().mulStrict(b.sigmoid());return[y,w]}}),pv=D({multiRNNCell_:function(r,t,e,n){for(var o=_(t,"data","multiRNNCell"),a=Wr(e,"c","multiRNNCell"),i=Wr(n,"h","multiRNNCell"),s=o,u=[],c=0;c<r.length;c++){var l=r[c](s,a[c],i[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]}}),dv=D({movingAverage_:function(r,t,e,n,o){o===void 0&&(o=!0);var a=_(r,"v","movingAverage"),i=_(t,"x","movingAverage"),s=_(e,"decay","movingAverage");ll(a,i),E(We(a.shape,i.shape),function(){return"Shape mismatch in v and x"});var u=q(1),c=u.sub(s),l=i.sub(a).mul(c);if(o){E(n!=null,function(){return"When using zeroDebias: true, step is required."});var h=_(n,"step","movingAverage");l=l.div(u.sub($r(s,h)))}return a.add(l)}}),vv=D({stridedSlice_:function(r,t,e,n,o,a,i,s,u){if(o===void 0&&(o=0),a===void 0&&(a=0),i===void 0&&(i=0),s===void 0&&(s=0),u===void 0&&(u=0),n==null&&(n=new Array(t.length)),i!==0)throw new Error("ellipsis mask is not yet supported");var c=_(r,"x","stridedSlice"),l=Pi(s),h=c.shape.slice();l.forEach(function(v){t[v]=0,e[v]=1,h.splice(v,0,1)}),c=c.reshape(h);for(var f=0;f<c.rank;f++)t[f]=Eh(o,t,n,c.shape,f),e[f]=Ih(a,e,n,c.shape,f),n[f]=n[f]||1;var p=Pi(u);p.forEach(function(v){e[v]=t[v]+1,n[v]=1});var d=Ra(t,e,n),g=d.filter(function(v,m){return p.indexOf(m)===-1});return n.every(function(v){return v===1})?Tt(c,t,d).reshape(g):T.runKernelFunc(function(v){return v.stridedSlice(c,t,e,n)},{$x:c}).reshape(g)}}),mv=D({topk_:function(r,t,e){t===void 0&&(t=1),e===void 0&&(e=!0);var n=_(r,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");var o=n.shape[n.shape.length-1];if(t>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+t);var a=T.runKernelFunc(function(i){return i.topk(n,t,e)},{$x:n});return{values:a[0],indices:a[1]}}}),gv=D({scatterND_:function(r,t,e){var n=_(r,"indices","scatterND","int32"),o=_(t,"updates","scatterND");return Ch(o,n,e),T.runKernelFunc(function(a){return a.scatterND(n,o,e)},{indices:n,updates:o},null,"ScatterNd",{shape:e})}}),Wa=D({fft_:function(r){E(r.dtype==="complex64",function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+r.dtype+"."});var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return T.runKernelFunc(function(o){return o.fft(n)},{input:r}).reshape(r.shape)}}),Yr=D({ifft_:function(r){E(r.dtype==="complex64",function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+r.dtype+"."});var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return T.runKernelFunc(function(o){return o.ifft(n)},{input:r}).reshape(r.shape)}}),Ua=D({rfft_:function(r,t){E(r.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+r.dtype});var e,n=r.shape[r.shape.length-1],o=r.size/n;if(t!=null&&t<n){var a=r.shape.map(function(m){return 0}),i=r.shape.map(function(m){return m});i[r.shape.length-1]=t,e=r.slice(a,i),n=t}else if(t!=null&&t>n){var s=r.shape.map(function(m){return m});s[r.shape.length-1]=t-n,e=r.concat(we(s),r.shape.length-1),n=t}else e=r;var u=e.zerosLike(),c=Ve(e,u).as2D(o,n),l=Wa(c),h=Math.floor(n/2)+1,f=ht(l),p=Rt(l),d=f.split([h,n-h],f.shape.length-1),g=p.split([h,n-h],p.shape.length-1),v=e.shape.slice();return v[e.shape.length-1]=h,Ve(d[0],g[0]).reshape(v)}}),ju=D({irfft_:function(r){var t=r.shape[r.shape.length-1],e=r.size/t;if(t<=2){var n=r.as2D(e,t),o=Yr(n);return ht(o)}var a=[e,2*(t-1)],i=ht(r).as2D(e,t),s=Rt(r).as2D(e,t),u=i.slice([0,1],[e,t-2]).reverse(1),c=s.slice([0,1],[e,t-2]).reverse(1).mul(q(-1)),l=i.concat(u,1),h=s.concat(c,1);return n=Ve(l,h).as2D(a[0],a[1]),o=Yr(n),ht(o)}}),yv=Object.freeze({fft:Wa,ifft:Yr,rfft:Ua,irfft:ju}),xv=D({sparseToDense_:function(r,t,e,n){n===void 0&&(n=0);var o=_(r,"sparseIndices","sparseToDense","int32"),a=_(t,"sparseValues","sparseToDense"),i=_(n,"defaultValue","sparseToDense",a.dtype);return function(s,u,c,l){if(s.dtype!=="int32")throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(s.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var h=s.rank>0?s.shape[0]:1,f=s.rank>1?s.shape[1]:1;if(c.length!==f)throw new Error("outputShape has incorrect number of elements:, "+c.length+", should be: "+f+".");var p=u.size;if(u.rank!==0&&(u.rank!==1||p!==h))throw new Error("sparseValues has incorrect shape "+u.shape+", should be [] or ["+h+"]");if(u.dtype!==l.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,e,i),T.runKernelFunc(function(s){return s.sparseToDense(o,a,e,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}}),bv=D({gatherND_:function(r,t){var e=_(t,"indices","gatherND","int32"),n=_(r,"x","gatherND");return T.runKernelFunc(function(o){return o.gatherND(n,e)},{x:n,indices:e},null,"GatherNd")}}),wv=D({diag_:function(r){var t=_(r,"x","diag").flatten(),e=r.shape.concat(r.shape);return T.runKernelFunc(function(n){return n.diag(t)},{$x:t}).reshape(e)}}),Cv=D({dropout_:function(r,t,e,n){var o=_(r,"x","dropout");if(E(o.dtype==="float32",function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),E(t>=0&&t<1,function(){return"rate must be a float in the range [0, 1), but got "+t+"."}),t===0)return r instanceof Ee?o.clone():o;var a=function(u,c){if(c==null)return u.shape.slice();if(We(u.shape,c))return c;if(u.shape.length===c.length){for(var l=[],h=0;h<u.shape.length;h++)c[h]==null&&u.shape[h]!=null?l.push(u.shape[h]):l.push(c[h]);return l}return c}(o,e),i=1-t,s=Gs(a,0,1,"float32",n).add(i).floor().div(i);return o.mul(s)}});function Ku(r,t,e){for(var n=1-r%2,o=new Float32Array(r),a=0;a<r;++a){var i=2*Math.PI*a/(r+n-1);o[a]=t-e*Math.cos(i)}return Te(o,"float32")}var Va=D({hannWindow_:function(r){return Ku(r,.5,.5)}}),Xu=D({hammingWindow_:function(r){return Ku(r,.54,.46)}}),za=D({frame_:function(r,t,e,n,o){n===void 0&&(n=!1),o===void 0&&(o=0);for(var a=0,i=[];a+t<=r.size;)i.push(Tt(r,a,t)),a+=e;if(n)for(;a<r.size;){var s=a+t-r.size,u=Fe([Tt(r,a,t-s),At([s],o)]);i.push(u),a+=e}return i.length===0?Zt([],[0,t]):Fe(i).as2D(i.length,t)}}),$u=D({stft_:function(r,t,e,n,o){var a;o===void 0&&(o=Va),n==null&&(a=t,n=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=za(r,t,e),s=Xe(i,o(t)),u=[],c=0;c<i.shape[0];c++)u.push(Ua(s.slice([c,0],[1,t]),n));return Fe(u)}}),_v=Object.freeze({hannWindow:Va,hammingWindow:Xu,frame:za,stft:$u}),Ke,Ev=function(r,t,e){return e===void 0&&(e=1),X(this,void 0,void 0,function(){var n,o,a,i,s,u,c,l,h,f,p,d,g,v;return $(this,function(m){switch(m.label){case 0:return n=_(r,"predictions","inTopK"),o=_(t,"targets","inTopK"),E(n.rank>1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank}),E(n.rank-1===o.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+o.rank}),ye(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=n.shape[n.shape.length-1],E(e>0&&e<=a,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+a+"), but got "+e}),[4,n.data()];case 1:return i=m.sent(),[4,o.data()];case 2:for(s=m.sent(),u=[i.length/a,a],l=u[1],h=tr("bool",c=u[0]),f=0;f<c;f++){for(p=f*l,d=i.subarray(p,p+l),g=[],v=0;v<d.length;v++)g.push({value:d[v],index:v});for(g.sort(function(x,b){return b.value-x.value}),h[f]=0,v=0;v<e;v++)if(g[v].index===s[f]){h[f]=1;break}}return r!==n&&n.dispose(),t!==o&&o.dispose(),[2,Ge(h,o.shape,"bool")]}})})};(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Ke||(Ke={}));var Iv=D({absoluteDifference_:function(r,t,e,n){n===void 0&&(n=Ke.SUM_BY_NONZERO_WEIGHTS);var o=_(r,"labels","absoluteDifference"),a=_(t,"predictions","absoluteDifference"),i=null;e!=null&&(i=_(e,"weights","absoluteDifference")),ye(o.shape,a.shape,"Error in absoluteDifference: ");var s=o.sub(a).abs();return Ht(s,i,n)}}),Ht=D({computeWeightedLoss_:function(r,t,e){e===void 0&&(e=Ke.SUM_BY_NONZERO_WEIGHTS);var n=_(r,"losses","computeWeightedLoss"),o=null;t!=null&&(o=_(t,"weights","computeWeightedLoss"));var a=o==null?n:n.mul(o);if(e===Ke.NONE)return a;if(e===Ke.SUM)return a.sum();if(e===Ke.MEAN){if(o==null)return a.mean();var i=n.size/o.size,s=a.sum().div(o.sum());return i>1?s.div(q(i)):s}if(e===Ke.SUM_BY_NONZERO_WEIGHTS){if(o==null)return a.sum().div(q(n.size));var u=o.mul(Kn(n.shape)).notEqual(q(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+e)}}),Rv=D({cosineDistance_:function(r,t,e,n,o){o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=_(r,"labels","cosineDistance"),i=_(t,"predictions","cosineDistance"),s=null;n!=null&&(s=_(n,"weights","cosineDistance")),ye(a.shape,i.shape,"Error in cosineDistance: ");var u=q(1).sub(a.mul(i).sum(e,!0));return Ht(u,s,o)}}),kv=D({hingeLoss_:function(r,t,e,n){n===void 0&&(n=Ke.SUM_BY_NONZERO_WEIGHTS);var o=_(r,"labels","hingeLoss"),a=_(t,"predictions","hingeLoss"),i=null;e!=null&&(i=_(e,"weights","hingeLoss")),ye(o.shape,a.shape,"Error in hingeLoss: ");var s=q(1);o=q(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return Ht(u,i,n)}}),Sv=D({huberLoss_:function(r,t,e,n,o){n===void 0&&(n=1),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=_(r,"labels","huberLoss"),i=_(t,"predictions","huberLoss"),s=null;e!=null&&(s=_(e,"weights","huberLoss")),ye(a.shape,i.shape,"Error in huberLoss: ");var u=q(n),c=i.sub(a).abs(),l=Su(c,u),h=c.sub(l),f=q(.5).mul(l.square()).add(u.mul(h));return Ht(f,s,o)}}),Dv=D({logLoss_:function(r,t,e,n,o){n===void 0&&(n=1e-7),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=_(r,"labels","logLoss"),i=_(t,"predictions","logLoss"),s=null;e!=null&&(s=_(e,"weights","logLoss")),ye(a.shape,i.shape,"Error in logLoss: ");var u=q(1),c=q(n),l=a.mul(i.add(c).log()).neg().sub(u.sub(a).mul(u.sub(i).add(c).log()));return Ht(l,s,o)}}),Av=D({meanSquaredError_:function(r,t,e,n){n===void 0&&(n=Ke.SUM_BY_NONZERO_WEIGHTS);var o=_(r,"labels","meanSquaredError"),a=_(t,"predictions","meanSquaredError"),i=null;e!=null&&(i=_(e,"weights","meanSquaredError")),ye(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return Ht(s,i,n)}}),Tv=D({sigmoidCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=_(r,"multiClassLabels","sigmoidCrossEntropy"),i=_(t,"logits","sigmoidCrossEntropy"),s=null;if(e!=null&&(s=_(e,"weights","sigmoidCrossEntropy")),ye(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){var u=q(n),c=q(1),l=q(.5);a=a.mul(c.sub(u)).add(l.mul(u))}var h=function(f,p){var d=_(f,"labels","sigmoidCrossEntropyWithLogits"),g=_(p,"logits","sigmoidCrossEntropyWithLogits");ye(d.shape,g.shape,"Error in sigmoidCrossEntropyWithLogits: ");var v=g.relu(),m=g.mul(d),x=g.abs().neg().exp().log1p();return v.sub(m).add(x)}(a,i);return Ht(h,s,o)}}),Nv=D({softmaxCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=_(r,"onehotLabels","softmaxCrossEntropy"),i=_(t,"logits","softmaxCrossEntropy"),s=null;if(e!=null&&(s=_(e,"weights","softmaxCrossEntropy")),ye(a.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){var u=q(n),c=q(1),l=q(a.shape[1]);a=a.mul(c.sub(u)).add(u.div(l))}var h=function(f,p,d){if(d===void 0&&(d=-1),d===-1&&(d=p.rank-1),d!==p.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+p.rank+" and dim was "+d);return oo(function(g,v,m){var x=v.logSumExp([d],!0),b=v.toFloat().sub(x);return m([g,b]),{value:b.mul(g).neg().sum([d]),gradFunc:function(y,w){var C=w[0],S=w[1],k=et(y.shape,[d]);return[y.reshape(k).mul(C.toFloat().sub(S.exp())),y.reshape(k).mul(S.exp().sub(C.toFloat()))]}}})(f,p)}(a,i);return Ht(h,s,o)}}),Fv=Object.freeze({get Reduction(){return Ke},absoluteDifference:Iv,computeWeightedLoss:Ht,cosineDistance:Rv,hingeLoss:kv,huberLoss:Sv,logLoss:Dv,meanSquaredError:Av,sigmoidCrossEntropy:Tv,softmaxCrossEntropy:Nv});function ns(r,t){return t===void 0&&(t=!1),T.tidy(function(){if(r.shape.length!==2)throw new Error("qr2d() requires a 2D Tensor, but got a "+r.shape.length+"D Tensor.");for(var e=r.shape[0],n=r.shape[1],o=zs(e),a=r.clone(),i=Zt([[1]],[1,1]),s=i.clone(),u=e>=n?n:e,c=function(h){var f,p=a,d=s,g=o;f=T.tidy(function(){var v=a.slice([h,h],[e-h,1]),m=v.norm(),x=a.slice([h,h],[1,1]),b=Zt([[-1]]).where(x.greater(0),Zt([[1]])),y=x.sub(b.mul(m)),w=v.div(y);s=w.shape[0]===1?i.clone():i.concat(w.slice([1,0],[w.shape[0]-1,w.shape[1]]),0);var C=b.matMul(y).div(m).neg(),S=a.slice([h,0],[e-h,n]),k=C.mul(s);if(h===0)a=S.sub(k.matMul(s.transpose().matMul(S)));else{var I=S.sub(k.matMul(s.transpose().matMul(S)));a=a.slice([0,0],[h,n]).concat(I,0)}var R=o.slice([0,h],[e,o.shape[1]-h]);if(h===0)o=R.sub(R.matMul(s).matMul(k.transpose()));else{var N=R.sub(R.matMul(s).matMul(k.transpose()));o=o.slice([0,0],[e,h]).concat(N,1)}return[s,a,o]}),s=f[0],a=f[1],o=f[2],Ze([p,d,g])},l=0;l<u;++l)c(l);return!t&&e>n&&(o=o.slice([0,0],[e,n]),a=a.slice([0,0],[n,n])),[o,a]})}var Pv=D({bandPart_:function(r,t,e){if(t%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+t+".");if(e%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+e+".");var n=_(r,"a","bandPart");if(n.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+n.rank+".");var o=n.shape,a=n.shape.slice(-2),i=a[0],s=a[1];if(!(t<=i))throw new Error("bandPart(): numLower ("+t+") must not be greater than the number of rows ("+i+").");if(!(e<=s))throw new Error("bandPart(): numUpper ("+e+") must not be greater than the number of columns ("+s+").");t<0&&(t=i),e<0&&(e=s);var u=Ur(0,i,1,"int32").reshape([-1,1]),c=Ur(0,s,1,"int32"),l=Oe(u,c),h=io(l.lessEqual(q(+t,"int32")),l.greaterEqual(q(-e,"int32"))),f=we([i,s],n.dtype);return ct(Pe(n.reshape([-1,i,s])).map(function(p){return vn(h,p,f)})).reshape(o)}}),Mv=D({gramSchmidt_:function(r){var t;if(Array.isArray(r)){t=!1,E(r!=null&&r.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=r[0].shape[0],n=function(u){E(r[u].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+r[u].shape[0]+" vs. "+e+")"})},o=1;o<r.length;++o)n(o)}else t=!0,r=Ea(r,r.shape[0],0).map(function(u){return qs(u,[0])});E(r.length<=r[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+r.length+") exceeds number of dimensions ("+r[0].shape[0]+")."});var a=[],i=r,s=function(u){a.push(T.tidy(function(){var c=i[u];if(u>0)for(var l=0;l<u;++l){var h=Vu(a[l].mulStrict(c)).mul(a[l]);c=c.sub(h)}return c.div(qu(c,"euclidean"))}))};for(o=0;o<r.length;++o)s(o);return t?ct(a,0):a}}),Ov=D({qr_:function(r,t){if(t===void 0&&(t=!1),r.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+r.rank);if(r.rank===2)return ns(r,t);var e=r.shape.slice(0,r.shape.length-2).reduce(function(i,s){return i*s}),n=Pe(r.reshape([e,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],a=[];return n.forEach(function(i){var s=ns(i,t),u=s[0],c=s[1];o.push(u),a.push(c)}),[ct(o,0).reshape(r.shape),ct(a,0).reshape(r.shape)]}}),Bv=Object.freeze({bandPart:Pv,gramSchmidt:Mv,qr:Ov});function lo(r,t,e,n,o,a){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),a==null&&(a=0);var i=r.shape[0];return e=Math.min(e,i),E(0<=n&&n<=1,function(){return"iouThreshold must be in [0, 1], but was '"+n+"'"}),E(r.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+r.rank+"'"}),E(r.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+r.shape[1]}),E(t.rank===1,function(){return"scores must be a 1D tensor"}),E(t.shape[0]===i,function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]}),E(0<=a&&a<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"}),{maxOutputSize:e,iouThreshold:n,scoreThreshold:o,softNmsSigma:a}}var Lv=D({resizeBilinear_:function(r,t,e){e===void 0&&(e=!1);var n=_(r,"images","resizeBilinear");E(n.rank===3||n.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."}),E(t.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."});var o=n,a=!1;n.rank===3&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=T.runKernelFunc(function(c,l){return l([o]),c.resizeBilinear(o,i,s,e)},{x:o},function(c,l){return{x:function(){return T.runKernelFunc(function(h){return h.resizeBilinearBackprop(c,l[0],e)},{})}}},"ResizeBilinear",{alignCorners:e,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Wv=D({resizeNearestNeighbor_:function(r,t,e){e===void 0&&(e=!1);var n=_(r,"images","resizeNearestNeighbor");E(n.rank===3||n.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."}),E(t.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."}),E(n.dtype==="float32"||n.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var o=n,a=!1;n.rank===3&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=T.runKernelFunc(function(c,l){return l([o]),c.resizeNearestNeighbor(o,i,s,e)},{batchImages:o},function(c,l){return{batchImages:function(){return T.runKernelFunc(function(h){return h.resizeNearestNeighborBackprop(c,l[0],e)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Uv=D({nonMaxSuppression_:function(r,t,e,n,o){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY);var a=_(r,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),s=lo(a,i,e,n,o);e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:e,iouThreshold:n,scoreThreshold:o};return T.runKernelFunc(function(c){return c.nonMaxSuppression(a,i,e,n,o)},{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),Vv=function(r,t,e,n,o){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),X(this,void 0,void 0,function(){var a,i,s,u,c,l,h;return $(this,function(f){switch(f.label){case 0:return a=_(r,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),s=lo(a,i,e,n,o),e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([a.data(),i.data()])];case 1:return u=f.sent(),c=u[0],l=u[1],h=Sa(c,l,e,n,o),a!==r&&a.dispose(),i!==t&&i.dispose(),[2,h]}})})},zv=D({nonMaxSuppressionWithScore_:function(r,t,e,n,o,a){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0);var i=_(r,"boxes","nonMaxSuppression"),s=_(t,"scores","nonMaxSuppression"),u=lo(i,s,e,n,o,a),c={maxOutputSize:e=u.maxOutputSize,iouThreshold:n=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},l=T.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),Gv=function(r,t,e,n,o,a){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0),X(this,void 0,void 0,function(){var i,s,u,c,l,h,f;return $(this,function(p){switch(p.label){case 0:return i=_(r,"boxes","nonMaxSuppressionAsync"),s=_(t,"scores","nonMaxSuppressionAsync"),u=lo(i,s,e,n,o,a),e=u.maxOutputSize,n=u.iouThreshold,o=u.scoreThreshold,a=u.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return c=p.sent(),l=c[0],h=c[1],f=Da(l,h,e,n,o,a),i!==r&&i.dispose(),s!==t&&s.dispose(),[2,f]}})})},Hv=D({cropAndResize_:function(r,t,e,n,o,a){var i=_(r,"image","cropAndResize"),s=_(t,"boxes","cropAndResize","float32"),u=_(e,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return E(i.rank===4,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),E(s.rank===2&&s.shape[1]===4,function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),E(u.rank===1&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),E(n.length===2,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."}),E(n[0]>=1&&n[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+n}),E(o==="bilinear"||o==="nearest",function(){return"method must be bilinear or nearest, but was "+o}),T.runKernelFunc(function(l,h){return l.cropAndResize(i,s,u,n,o,a)},{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:n})}}),Ga=Object.freeze({resizeBilinear:Lv,resizeNearestNeighbor:Wv,nonMaxSuppression:Uv,nonMaxSuppressionAsync:Vv,nonMaxSuppressionWithScore:zv,nonMaxSuppressionWithScoreAsync:Gv,cropAndResize:Hv}),Ha=function(r,t){return!(r>0)||t==="linear"},qa=function(r,t,e){if(e==null||e==="linear")return r;if(e==="relu")return r.mul(t.step());throw new Error("Gradient for activation "+e+" has not been implemented yet.")},ja=function(r,t){var e=t,n=Me(r.shape,t.shape);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},Ka=function(r,t,e){if(t==="linear")return r;if(t==="relu")return Ie(r);if(t==="elu")return zu(r);if(t==="relu6")return Hu(r);if(t==="prelu")return Gu(r,e);throw new Error("Unknown fused activation "+t+".")},qv=D({fusedMatMul_:function(r){var t,e=r.a,n=r.b,o=r.transposeA,a=o!==void 0&&o,i=r.transposeB,s=i!==void 0&&i,u=r.bias,c=r.activation,l=c===void 0?"linear":c,h=r.preluActivationWeights;if(Ha(T.state.gradientDepth,l)===!1){var f=uo(e,n,a,s);return u!=null&&(f=ue(f,u)),Ka(f,l,h)}var p=_(e,"a","fused matMul"),d=_(n,"b","fused matMul");t=Re(p,d),p=t[0],d=t[1];var g=a?p.shape[p.rank-2]:p.shape[p.rank-1],v=s?d.shape[d.rank-1]:d.shape[d.rank-2],m=a?p.shape[p.rank-1]:p.shape[p.rank-2],x=s?d.shape[d.rank-2]:d.shape[d.rank-1],b=p.shape.slice(0,-2),y=d.shape.slice(0,-2),w=Y(b),C=Y(y);E(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+"."}),E(We(b,y),function(){return"Error in fused matMul: outer dimensions ("+b+") and ("+y+") of Tensors with shapes "+p.shape+" and "+d.shape+" must match."}),E(g===v,function(){return"Error in fused matMul: inner shapes ("+g+") and ("+v+") of Tensors with shapes "+p.shape+" and "+d.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var S,k,I=p.shape.slice(0,-2).concat([m,x]),R=a?p.as3D(w,g,m):p.as3D(w,m,g),N=s?d.as3D(C,x,v):d.as3D(C,v,x);u!=null&&le(I,(S=Re(S=_(u,"bias","fused matMul"),p)[0]).shape),h!=null&&(k=_(h,"prelu weights","fused matMul"));var A={a:R,b:N};u!=null&&(A.bias=S),h!=null&&(A.preluActivationWeights=k);var L=[R,N];return T.runKernelFunc(function(O,B){var V=O.fusedBatchMatMul({a:R,b:N,transposeA:a,transposeB:s,bias:S,activation:l,preluActivationWeights:k});return B([R,N,V]),V},A,function(O,B){var V=B[0],U=B[1],W=B[2],G=qa(O,W,l),H={};return u!=null&&(H={bias:function(){return ja(S,G)}}),Object.assign(a||s?!a&&s?{a:function(){return G.matMul(U,!1,!1)},b:function(){return G.matMul(V,!0,!1)}}:a&&!s?{a:function(){return U.matMul(G,!1,!0)},b:function(){return V.matMul(G,!1,!1)}}:{a:function(){return U.matMul(G,!0,!0)},b:function(){return G.matMul(V,!0,!0)}}:{a:function(){return G.matMul(U,!1,!0)},b:function(){return V.matMul(G,!0,!1)}},H)},"_FusedMatMul",{transposeA:a,transposeB:s,activation:l},L,[!0]).reshape(I)}}),jv=D({fusedConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,a=r.dataFormat,i=a===void 0?"NHWC":a,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,h=r.activation,f=h===void 0?"linear":h,p=r.preluActivationWeights;if(f=f||"linear",Ha(T.state.gradientDepth,f)===!1){var d=pt(t,e,n,o,i,u,c);return l!=null&&(d=ue(d,l)),Ka(d,f,p)}var g=_(t,"x","conv2d"),v=_(e,"filter","conv2d"),m=g,x=!1;g.rank===3&&(x=!0,m=g.as4D(1,g.shape[0],g.shape[1],g.shape[2])),E(m.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+m.rank+"."}),E(v.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+v.rank+"."}),c!=null&&E(Ae(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."}),E(m.shape[3]===v.shape[2],function(){return"Error in conv2d: depth of input ("+m.shape[3]+") must match input depth for filter "+v.shape[2]+"."}),E(tt(n,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"}),E(i==="NHWC",function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var b,y,w=bn(m.shape,v.shape,n,u,o,c);l!=null&&(b=Re(b=_(l,"bias","fused conv2d"),g)[0],le(w.outShape,b.shape)),p!=null&&(y=_(p,"prelu weights","fused conv2d"));var C={x:m,filter:v};l!=null&&(C.bias=b),p!=null&&(C.preluActivationWeights=y);var S=[v,m],k=T.runKernelFunc(function(I,R){var N=I.fusedConv2d({input:m,filter:v,convInfo:w,bias:b,activation:f,preluActivationWeights:y});return R([v,m,N]),N},C,function(I,R){var N=R,A=N[0],L=N[1],O=N[2],B=qa(I,O,f);E(qn(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var V={};return l!=null&&(V={bias:function(){return ja(b,B)}}),Object.assign({x:function(){return Pu(L.shape,B,A,n,o)},filter:function(){return Ba(L,B,A.shape,n,o)}},V)},"FusedConv2D",{convInfo:w,activation:f},S,[!0]);return x?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k}}),Kv=D({fusedDepthwiseConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,a=r.dataFormat,i=a===void 0?"NHWC":a,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,h=r.activation,f=h===void 0?"linear":h,p=r.preluActivationWeights;if(Ha(T.state.gradientDepth,f)===!1){var d=so(t,e,n,o,i,u,c);return l!=null&&(d=ue(d,l)),Ka(d,f,p)}var g=_(t,"x","depthwiseConv2d"),v=_(e,"filter","depthwiseConv2d"),m=g,x=!1;g.rank===3&&(x=!0,m=g.as4D(1,g.shape[0],g.shape[1],g.shape[2])),E(m.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+m.rank+"."}),E(v.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+v.rank+"."}),E(m.shape[3]===v.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+m.shape[3]+") must match the inChannels dimension in filter "+v.shape[2]+"."}),u==null&&(u=[1,1]),E(tt(n,u),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"}),c!=null&&E(Ae(o),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."});var b,y,w=bn(m.shape,v.shape,n,u,o,c,!0);l!=null&&(b=Re(b=_(l,"bias","fused conv2d"),g)[0],le(w.outShape,b.shape)),p!=null&&(y=_(p,"prelu weights","fused depthwiseConv2d"));var C={x:m,filter:v};l!=null&&(C.bias=b),p!=null&&(C.preluActivationWeights=y);var S=[v,m],k=T.runKernelFunc(function(I,R){var N=I.fusedDepthwiseConv2D({input:m,filter:v,convInfo:w,bias:b,activation:f,preluActivationWeights:y});return R([v,m,N]),N},C,function(I,R){E(qn(u),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"});var N=R[0],A=R[1],L=R[2],O=qa(I,L,f),B={};return l!=null&&(B={bias:function(){return ja(b,O)}}),Object.assign({x:function(){return Mu(A.shape,O,N,w)},filter:function(){return Ou(A,O,N.shape,w)}},B)},"FusedDepthwiseConv2D",{convInfo:w,activation:f},S,[!0]);
3755return x?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k}}),Xv=Object.freeze({matMul:qv,conv2d:jv,depthwiseConv2d:Kv}),$v=Object.freeze({image:Ga,linalg:Bv,losses:Fv,spectral:yv,fused:Xv,signal:_v,square:Dp,squaredDifference:yu,conv1d:Ld,conv2d:pt,conv3d:Wd,depthwiseConv2d:so,separableConv2d:La,conv2dTranspose:Ud,conv3dTranspose:Vd,op:D,batchNormalization2d:ad,batchNormalization3d:id,batchNormalization4d:sd,batchNormalization:ud,batchNorm:Eu,batchNorm2d:cd,batchNorm3d:ld,batchNorm4d:hd,booleanMaskAsync:Bd,complex:Ve,real:ht,imag:Rt,concat:Fe,concat1d:Kl,concat2d:Xl,concat3d:$l,concat4d:Yl,split:Ea,matMul:uo,dot:zd,outerProduct:Gd,reverse:pr,reverse1d:Hd,reverse2d:qd,reverse3d:jd,reverse4d:Kd,maxPool:Le,avgPool:dr,pool:Xd,maxPool3d:$d,avgPool3d:Yd,slice:Tt,slice1d:Jd,slice2d:Qd,slice3d:Wu,slice4d:Zd,abs:Ap,acos:Tp,acosh:Np,asin:Fp,asinh:Pp,atan:Mp,atanh:Op,ceil:Bp,clipByValue:Pa,cos:Lp,cosh:Wp,erf:Up,exp:ha,expm1:Vp,floor:zp,log:Gp,log1p:Hp,logSigmoid:qp,neg:Xr,reciprocal:jp,round:Kp,rsqrt:xu,sigmoid:bu,sign:Xp,isNaN:$p,isInf:Yp,isFinite:Jp,sin:Qp,sinh:Zp,softplus:ed,sqrt:td,step:nd,tan:rd,tanh:od,all:ev,any:tv,argMax:nv,argMin:rv,logSumExp:ov,max:co,mean:av,min:iv,moments:sv,sum:Vu,prod:uv,equal:Du,equalStrict:kd,greater:Sd,greaterEqual:Au,greaterEqualStrict:Dd,greaterStrict:Ad,less:Td,lessEqual:Nd,lessEqualStrict:Fd,lessStrict:Pd,notEqual:Md,notEqualStrict:Od,add:ue,addN:dd,addStrict:vd,atan2:md,div:dt,divNoNan:gd,divStrict:yd,floorDiv:ku,maximum:Ma,maximumStrict:xd,minimum:Su,minimumStrict:bd,mod:wd,modStrict:Cd,mul:Xe,mulStrict:_d,pow:$r,powStrict:Ed,squaredDifferenceStrict:Id,sub:Oe,subStrict:Rd,elu:zu,leakyRelu:cv,prelu:Gu,relu:Ie,relu6:Hu,selu:lv,logicalAnd:io,logicalNot:fd,logicalOr:Iu,logicalXor:pd,where:vn,whereAsync:Ru,buffer:oe,print:ah,batchToSpaceND:Vs,broadcastTo:ih,cast:sh,clone:uh,cumsum:ch,depthToSpace:lh,expandDims:lt,eye:zs,multinomial:hh,oneHot:sa,pad:xn,pad1d:fh,pad2d:ph,pad3d:dh,pad4d:vh,rand:mh,randomNormal:gh,randomGamma:yh,randomUniform:Gs,reshape:vt,spaceToBatchND:Hs,squeeze:qs,stack:ct,tile:Mn,truncatedNormal:xh,unstack:Pe,setdiff1dAsync:bh,fill:At,linspace:jl,ones:Kn,range:Ur,scalar:q,tensor:Ge,tensor1d:Te,tensor2d:Zt,tensor3d:_a,tensor4d:Je,tensor5d:Gl,tensor6d:Hl,variable:ql,zeros:we,onesLike:Us,zerosLike:ve,transpose:nn,softmax:Gt,logSoftmax:kh,localResponseNormalization:hv,norm:qu,gather:Oa,unsortedSegmentSum:Tu,basicLSTMCell:fv,multiRNNCell:pv,movingAverage:dv,stridedSlice:vv,to
vendor: 55,902 bytes, lines 3755-3814
3755pk:mv,scatterND:gv,fft:Wa,ifft:Yr,rfft:Ua,irfft:ju,sparseToDense:xv,gatherND:bv,diag:wv,dropout:Cv,hannWindow:Va,hammingWindow:Xu,frame:za,stft:$u,inTopKAsync:Ev});function z(r,t){Array.isArray(r)||(r=[r]),r.forEach(function(e){e!=null&&E(e.dtype!=="complex64",function(){return t+" does not support complex64 tensors."})})}function Uo(r,t,e,n){if(e==="linear")return r.linear(t);if(e==="relu")return r.relu(t);if(e==="elu")return r.elu(t);if(e==="relu6")return r.relu6(t);if(e==="prelu")return r.prelu(t,n);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}var Yv=function(r){function t(){var e=r.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new Qs(e,T),e}return gt(t,r),t.prototype.write=function(e,n,o){this.firstUse&&(this.firstUse=!1,M().get("IS_NODE")&&Lr(`
3756============================
3757Hi 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.
3758============================`));var a={};return this.data.set(a,{values:e,dtype:o}),a},t.prototype.move=function(e,n,o,a){this.data.set(e,{values:n,dtype:a})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){return[2,this.readSync(e)]})})},t.prototype.readSync=function(e){var n=this.data.get(e),o=n.dtype,a=n.complexTensors;return o==="complex64"?la(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var n=this.readSync(e.dataId),o=n;if(e.dtype==="string")try{o=n.map(function(a){return Mr(a)})}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return oe(e.shape,e.dtype,o)},t.prototype.makeOutput=function(e,n,o){var a=this.write(e,n,o);return T.makeTensorFromDataId(a,n,o,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var n=this.data.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return X(this,void 0,void 0,function(){var n;return $(this,function(o){return n=Et(),e(),[2,{kernelMs:Et()-n}]})})},t.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."]}},t.prototype.complex=function(e,n){var o=this.makeOutput(null,e.shape,"complex64");return this.data.get(o.dataId).complexTensors={real:T.keep(e.clone()),imag:T.keep(n.clone())},o},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,n,o){if(z(e,"slice"),Ys(e.shape,n,o)){var a=Js(n,e.strides),i=Y(o);return Ge(this.readSync(e.dataId).subarray(a,a+i),o,e.dtype)}for(var s=oe(o,e.dtype),u=this.bufferSync(e),c=0;c<s.size;++c){var l=s.indexToLoc(c).map(function(h,f){return h+n[f]});s.values[c]=u.get.apply(u,l)}return s.toTensor()},t.prototype.stridedSlice=function(e,n,o,a){z(e,"stridedSlice");var i=Ra(n,o,a);if(i.some(function(p){return p===0}))return Ge([],i);for(var s=oe(i,e.dtype),u=this.bufferSync(e),c=0;c<s.size;c++){for(var l=s.indexToLoc(c),h=new Array(l.length),f=0;f<h.length;f++)h[f]=l[f]*a[f]+n[f];s.set.apply(s,[u.get.apply(u,h)].concat(l))}return s.toTensor()},t.prototype.diag=function(e){for(var n=this.readSync(e.dataId),o=oe([e.size,e.size],e.dtype),a=o.values,i=0;i<n.length;i++)a[i*e.size+i]=n[i];return o.toTensor()},t.prototype.unstack=function(e,n){for(var o=e.shape[n],a=new Array(e.rank-1),i=0,s=0;s<e.rank;s++)s!==n&&(a[i++]=e.shape[s]);var u=new Array(e.rank).fill(0),c=e.shape.slice();c[n]=1;var l=new Array(o);for(s=0;s<l.length;s++)u[n]=s,l[s]=this.slice(e,u,c).reshape(a);return l},t.prototype.reverse=function(e,n){z(e,"reverse");for(var o=oe(e.shape,e.dtype),a=this.bufferSync(e),i=function(u){var c=o.indexToLoc(u),l=c.slice();n.forEach(function(h){return l[h]=e.shape[h]-1-l[h]}),o.set.apply(o,[a.get.apply(a,l)].concat(c))},s=0;s<o.size;s++)i(s);return o.toTensor()},t.prototype.concat=function(e,n){var o=this;if(e[0].dtype==="complex64"){var a=e.map(function(p){return ht(p)}),i=e.map(function(p){return Rt(p)});return Ve(this.concat(a,n),this.concat(i,n))}var s=e.map(function(p){var d=Y(p.shape.slice(n));return p.as2D(-1,d)}),u=Hn(s.map(function(p){return p.shape}),1),c=oe(u,e[0].dtype).values;if(s[0].shape[0]===1){var l=0;s.forEach(function(p){c.set(o.readSync(p.dataId),l),l+=p.size})}else{var h=0;s.forEach(function(p){for(var d=o.readSync(p.dataId),g=0,v=0;v<p.shape[0];++v)for(var m=v*u[1]+h,x=0;x<p.shape[1];++x)c[m+x]=d[g++];h+=p.shape[1]})}var f=Hn(e.map(function(p){return p.shape}),n);return Ge(c,f,e[0].dtype)},t.prototype.neg=function(e){return z(e,"neg"),this.multiply(q(-1),e)},t.prototype.add=function(e,n){return e.dtype==="complex64"||n.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),n.cast("complex64"),function(o,a,i,s){return{real:o+i,imag:a+s}}):this.broadcastedBinaryOp(e,n,ze(e.dtype,n.dtype),function(o,a){return o+a})},t.prototype.addN=function(e){var n=this;z(e,"addN");for(var o=e.map(function(l){return n.readSync(l.dataId)}),a=oe(e[0].shape,e[0].dtype),i=a.values,s=0;s<e.length;s++)for(var u=o[s],c=0;c<i.length;c++)i[c]+=u[c];return a.toTensor()},t.prototype.softmax=function(e,n){var o=Be([n],e.shape),a=this.max(e,o),i=et(a.shape,o),s=this.subtract(e,a.reshape(i)),u=this.exp(s),c=this.sum(u,o).reshape(i);return this.realDivide(u,c)},t.prototype.subtract=function(e,n){return e.dtype==="complex64"||n.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),n.cast("complex64"),function(o,a,i,s){return{real:o-i,imag:a-s}}):this.broadcastedBinaryOp(e,n,ze(e.dtype,n.dtype),function(o,a){return o-a})},t.prototype.pow=function(e,n){return z([e,n],"pow"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){return Math.pow(o,a)})},t.prototype.batchMatMul=function(e,n,o,a){z([e,n],"matMul");for(var i=o?e.shape[1]:e.shape[2],s=o?e.shape[2]:e.shape[1],u=a?n.shape[1]:n.shape[2],c=e.shape[0],l=this.readSync(e.dataId),h=this.readSync(n.dataId),f=o?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],p=f[0],d=f[1],g=f[2],v=a?[1,n.strides[1],n.strides[0]]:[n.strides[1],1,n.strides[0]],m=v[0],x=v[1],b=v[2],y=s*u,w=oe([c,s,u],e.dtype),C=w.values,S=this.blockSize,k=0;k<c;k++)for(var I=0;I<s;I+=S)for(var R=0;R<u;R+=S)for(var N=0;N<i;N+=S)for(var A=Math.min(I+S,s),L=Math.min(R+S,u),O=Math.min(N+S,i),B=I;B<A;B++)for(var V=R;V<L;V++){for(var U=0,W=N;W<O;W++)U+=l[k*p+B*d+W*g]*h[W*m+V*x+k*b];C[k*y+(B*u+V)]+=U}return w.toTensor()},t.prototype.fusedBatchMatMul=function(e){var n=e.a,o=e.b,a=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=this.batchMatMul(n,o,a,i);return s&&(l=this.add(l,s)),u&&(l=Uo(this,l,u,c)),l},t.prototype.multiply=function(e,n){return e.dtype==="complex64"||n.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),n.cast("complex64"),function(o,a,i,s){return{real:o*i-a*s,imag:o*s+a*i}}):this.broadcastedBinaryOp(e,n,ze(e.dtype,n.dtype),function(o,a){return o*a})},t.prototype.realDivide=function(e,n){return z([e,n],"realDivide"),this.broadcastedBinaryOp(e,n,"float32",function(o,a){return o/a})},t.prototype.floorDiv=function(e,n){return z([e,n],"floorDiv"),this.broadcastedBinaryOp(e,n,"int32",function(o,a){return Math.floor(o/a)})},t.prototype.sum=function(e,n){z(e,"sum"),ot("sum",n,e.rank);for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,ze(e.dtype,"int32")),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=0,d=0;d<u;++d)p+=l[f+d];c[h]=p}return s},t.prototype.prod=function(e,n){z(e,"sum");for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,ze(e.dtype,"int32")),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=1,d=0;d<u;++d)p*=l[f+d];c[h]=p}return s},t.prototype.unsortedSegmentSum=function(e,n,o){z(e,"unsortedSegmentSum");for(var a=[],i=e.rank-n.rank,s=0;s<i;++s)n=n.expandDims(s+1);for(s=0;s<o;++s){var u=q(s,"int32"),c=Du(u,n).asType("float32").mul(e).sum(0);a.push(c)}return ct(a)},t.prototype.argMin=function(e,n){z(e,"argMin");var o=[n];ot("argMin",o,e.rank);for(var a=He(e.shape,o),i=a[0],s=a[1],u=we(i,"int32"),c=Y(s),l=this.readSync(u.dataId),h=this.readSync(e.dataId),f=0;f<l.length;++f){for(var p=f*c,d=h[p],g=0,v=0;v<c;++v){var m=h[p+v];m<d&&(d=m,g=v)}l[f]=g}return u},t.prototype.argMax=function(e,n){z(e,"argMax");var o=[n];ot("argMax",o,e.rank);for(var a=He(e.shape,o),i=a[0],s=a[1],u=we(i,"int32"),c=Y(s),l=this.readSync(u.dataId),h=this.readSync(e.dataId),f=0;f<l.length;++f){for(var p=f*c,d=h[p],g=0,v=0;v<c;++v){var m=h[p+v];m>d&&(d=m,g=v)}l[f]=g}return u},t.prototype.cumsum=function(e,n,o,a){if(z(e,"cumsum"),n!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+n);for(var i=ze(e.dtype,"int32"),s=we(e.shape,i),u=this.readSync(s.dataId),c=this.readSync(e.dataId),l=e.shape[e.rank-1],h=a?function(v,m){return v+l-m-1}:function(v,m){return v+m},f=0;f<c.length;f+=l)for(var p=0;p<l;p++){var d=h(f,p);if(p===0)u[d]=o?0:c[d];else{var g=h(f,p-1);u[d]=o?c[g]+u[g]:c[d]+u[g]}}return s},t.prototype.equal=function(e,n){return z([e,n],"equal"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o===a?1:0})},t.prototype.notEqual=function(e,n){return z([e,n],"notEqual"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o!==a?1:0})},t.prototype.less=function(e,n){return z([e,n],"less"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o<a?1:0})},t.prototype.lessEqual=function(e,n){return z([e,n],"lessEqual"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o<=a?1:0})},t.prototype.greater=function(e,n){return z([e,n],"greater"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o>a?1:0})},t.prototype.greaterEqual=function(e,n){return z([e,n],"greaterEqual"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o>=a?1:0})},t.prototype.logicalNot=function(e){z(e,"logicalNot");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a<n.length;++a)o[a]=n[a]?0:1;return this.makeOutput(o,e.shape,"bool")},t.prototype.logicalAnd=function(e,n){return z([e,n],"logicalAnd"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o&&a})},t.prototype.logicalOr=function(e,n){return z([e,n],"logicalOr"),this.broadcastedBinaryOp(e,n,"bool",function(o,a){return o||a})},t.prototype.select=function(e,n,o){z([e,n,o],"select");for(var a=this.readSync(e.dataId),i=this.readSync(n.dataId),s=this.readSync(o.dataId),u=we(n.shape,ze(n.dtype,o.dtype)),c=this.readSync(u.dataId),l=0,h=e.rank===0||e.rank>1||n.rank===1?1:Y(n.shape.slice(1)),f=0;f<a.length;f++)for(var p=0;p<h;p++)a[f]===1?c[l++]=i[f]:c[l++]=s[f];return u},t.prototype.where=function(e){z([e],"where");var n=this.readSync(e.dataId);return Aa(e.shape,n)},t.prototype.topk=function(e,n,o){return z(e,"topk"),iu(this.readSync(e.dataId),e.shape,e.dtype,n)},t.prototype.min=function(e,n){z(e,"min"),ot("min",n,e.rank);for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,e.dtype),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=l[f],d=0;d<u;++d){var g=l[f+d];g<p&&(p=g)}c[h]=p}return s},t.prototype.minimum=function(e,n){return z([e,n],"minimum"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){return Math.min(o,a)})},t.prototype.mod=function(e,n){return z([e,n],"mod"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){var i=o%a;return o<0&&a<0||o>=0&&a>=0?i:(i+a)%a})},t.prototype.max=function(e,n){z(e,"max"),ot("max",n,e.rank);for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,e.dtype),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=l[f],d=0;d<u;++d){var g=l[f+d];g>p&&(p=g)}c[h]=p}return s},t.prototype.maximum=function(e,n){return z([e,n],"maximum"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){return Math.max(o,a)})},t.prototype.all=function(e,n){z(e,"all"),ot("all",n,e.rank);for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,e.dtype),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=l[f],d=0;d<u;++d){var g=l[f+d];p=p&&g}c[h]=p}return s},t.prototype.any=function(e,n){z(e,"any"),ot("any",n,e.rank);for(var o=He(e.shape,n),a=o[0],i=o[1],s=we(a,e.dtype),u=Y(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h<c.length;++h){for(var f=h*u,p=l[f],d=0;d<u;++d){var g=l[f+d];p=p||g}c[h]=p}return s},t.prototype.squaredDifference=function(e,n){return z([e,n],"squaredDifference"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){var i=o-a;return i*i})},t.prototype.ceil=function(e){z(e,"ceil");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)o[a]=Math.ceil(n[a]);return this.makeOutput(o,e.shape,"float32")},t.prototype.floor=function(e){z(e,"floor");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)o[a]=Math.floor(n[a]);return this.makeOutput(o,e.shape,"float32")},t.prototype.sign=function(e){z(e,"x");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)n[a]<0?o[a]=-1:n[a]>0?o[a]=1:o[a]=0;return this.makeOutput(o,e.shape,"float32")},t.prototype.isNaN=function(e){z(e,"x");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a<n.length;++a)Number.isNaN(n[a])&&(o[a]=1);return this.makeOutput(o,e.shape,"bool")},t.prototype.isInf=function(e){z(e,"x");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a<n.length;++a)Math.abs(n[a])===1/0&&(o[a]=1);return this.makeOutput(o,e.shape,"bool")},t.prototype.isFinite=function(e){z(e,"x");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a<n.length;++a)Number.isFinite(n[a])&&(o[a]=1);return this.makeOutput(o,e.shape,"bool")},t.prototype.round=function(e){z(e,"round");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a){var i=Math.floor(n[a]);n[a]-i<.5?o[a]=Math.floor(n[a]):n[a]-i>.5?o[a]=Math.ceil(n[a]):o[a]=i%2==0?i:i+1}return this.makeOutput(o,e.shape,"float32")},t.prototype.exp=function(e){z(e,"exp");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)o[a]=Math.exp(n[a]);return this.makeOutput(o,e.shape,"float32")},t.prototype.expm1=function(e){z(e,"expm1");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)o[a]=Math.expm1(n[a]);return this.makeOutput(o,e.shape,"float32")},t.prototype.log=function(e){z(e,"log");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a){var i=n[a];o[a]=Math.log(i)}return this.makeOutput(o,e.shape,"float32")},t.prototype.log1p=function(e){z(e,"log1p");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a){var i=n[a];o[a]=Math.log1p(i)}return this.makeOutput(o,e.shape,"float32")},t.prototype.sqrt=function(e){z(e,"sqrt");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a){var i=n[a];o[a]=Math.sqrt(i)}return this.makeOutput(o,e.shape,"float32")},t.prototype.rsqrt=function(e){z(e,"rsqrt");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a){var i=n[a];o[a]=1/Math.sqrt(i)}return this.makeOutput(o,e.shape,"float32")},t.prototype.reciprocal=function(e){z(e,"reciprocal");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a<n.length;++a)o[a]=1/n[a];return this.makeOutput(o,e.shape,"float32")},t.prototype.linear=function(e){return e},t.prototype.relu=function(e){z(e,"relu");for(var n=we(e.shape,e.dtype),o=this.readSync(n.dataId),a=this.readSync(e.dataId),i=0;i<a.length;++i)o[i]=Math.max(0,a[i]);return n},t.prototype.relu6=function(e){z(e,"relu");for(var n=we(e.shape,e.dtype),o=this.readSync(n.dataId),a=this.readSync(e.dataId),i=0;i<a.length;++i)o[i]=Math.min(Math.max(0,a[i]),6);return n},t.prototype.prelu=function(e,n){return z([e,n],"prelu"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){return o<0?a*o:o})},t.prototype.elu=function(e){z(e,"elu");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a){var i=o[a];n[a]=i>=0?i:Math.exp(i)-1}return this.makeOutput(n,e.shape,"float32")},t.prototype.eluDer=function(e,n){z([e,n],"eluDer");for(var o=new Float32Array(n.size),a=this.readSync(n.dataId),i=this.readSync(e.dataId),s=0;s<a.length;++s){var u=a[s];o[s]=u>=1?i[s]:i[s]*(u+1)}return this.makeOutput(o,n.shape,"float32")},t.prototype.selu=function(e){z(e,"selu");for(var n=Na,o=Fa,a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s<i.length;++s){var u=i[s];a[s]=u>=0?o*u:n*(Math.exp(u)-1)}return this.makeOutput(a,e.shape,"float32")},t.prototype.clip=function(e,n,o){z(e,"clip");for(var a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s<i.length;++s){var u=i[s];a[s]=u>o?o:u<n?n:u}return this.makeOutput(a,e.shape,"float32")},t.prototype.abs=function(e){for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.abs(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.complexAbs=function(e){for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<e.size;++a){var i=o[2*a],s=o[2*a+1];n[a]=Math.hypot(i,s)}return this.makeOutput(n,e.shape,"float32")},t.prototype.int=function(e){z(e,"int");for(var n=new Int32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=o[a];return this.makeOutput(n,e.shape,"int32")},t.prototype.sigmoid=function(e){z(e,"sigmoid");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=1/(1+Math.exp(-o[a]));return this.makeOutput(n,e.shape,"float32")},t.prototype.softplus=function(e){z(e,"softplus");for(var n=Math.log(11920928955078125e-23)+2,o=new Float32Array(e.size),a=this.readSync(e.dataId),i=0;i<a.length;++i){var s=a[i]>-n,u=a[i]<n,c=Math.exp(a[i]),l=void 0;l=u?c:s?a[i]:Math.log(1+c),o[i]=l}return this.makeOutput(o,e.shape,"float32")},t.prototype.sin=function(e){z(e,"sin");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.sin(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.cos=function(e){z(e,"cos");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.cos(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.tan=function(e){z(e,"tan");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.tan(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.asin=function(e){z(e,"asin");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.asin(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.acos=function(e){z(e,"acos");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.acos(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.atan=function(e){z(e,"atan");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.atan(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.atan2=function(e,n){return z([e,n],"atan2"),this.broadcastedBinaryOp(e,n,e.dtype,function(o,a){return Math.atan2(o,a)})},t.prototype.sinh=function(e){z(e,"sinh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.sinh(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.cosh=function(e){z(e,"cosh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.cosh(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.tanh=function(e){z(e,"tanh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Yc(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.asinh=function(e){z(e,"asinh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.asinh(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.acosh=function(e){z(e,"acosh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.acosh(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.atanh=function(e){z(e,"atanh");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a)n[a]=Math.atanh(o[a]);return this.makeOutput(n,e.shape,"float32")},t.prototype.erf=function(e){z(e,"erf");for(var n=new Float32Array(e.size),o=this.readSync(e.dataId),a=0;a<o.length;++a){var i=Math.sign(o[a]),s=Math.abs(o[a]),u=1/(1+.3275911*s);n[a]=i*(1-((((1.061405429*u-1.453152027)*u+1.421413741)*u-.284496736)*u+.254829592)*u*Math.exp(-s*s))}return this.makeOutput(n,e.shape,"float32")},t.prototype.step=function(e,n){n===void 0&&(n=0),z(e,"step");for(var o=new Float32Array(e.size),a=this.readSync(e.dataId),i=0;i<a.length;++i){var s=a[i];isNaN(s)?o[i]=NaN:o[i]=s>0?1:n}return this.makeOutput(o,e.shape,"float32")},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.conv2d(n,o,a);return i&&(c=this.add(c,i)),s&&(c=Uo(this,c,s,u)),c},t.prototype.conv2d=function(e,n,o){z([e,n],"conv2d");for(var a=o.filterHeight,i=o.filterWidth,s=o.dilationHeight,u=o.dilationWidth,c=o.padInfo.left,l=o.padInfo.top,h=o.dataFormat==="channelsLast",f=oe(o.outShape,e.dtype),p=e.strides[0],d=h?e.strides[1]:e.strides[2],g=h?e.strides[2]:1,v=h?1:e.strides[1],m=f.strides[0],x=h?f.strides[1]:f.strides[2],b=h?f.strides[2]:1,y=h?1:f.strides[1],w=this.readSync(e.dataId),C=this.readSync(n.dataId),S=f.values,k=0;k<o.batchSize;++k)for(var I=k*p,R=k*m,N=0;N<o.outHeight;++N)for(var A=R+N*x,L=N*o.strideHeight-l,O=0;O<a;O++){var B=L+O*s;if(!(B<0||B>=o.inHeight))for(var V=O*n.strides[0],U=I+B*d,W=0;W<o.outWidth;++W)for(var G=A+W*b,H=W*o.strideWidth-c,j=0;j<i;j++){var ee=H+j*u;if(!(ee<0||ee>=o.inWidth))for(var te=U+ee*g,ie=V+j*n.strides[1],se=0;se<o.inChannels;++se){for(var ce=w[te+se*v],pe=0;pe<o.outChannels;++pe)S[G+pe*y]+=ce*C[ie+pe];ie+=o.outChannels}}}return f.toTensor()},t.prototype.conv3d=function(e,n,o){for(var a=o.filterDepth,i=o.filterHeight,s=o.filterWidth,u=o.dilationDepth,c=o.dilationHeight,l=o.dilationWidth,h=o.padInfo.front,f=o.padInfo.left,p=o.padInfo.top,d=oe(o.outShape,e.dtype),g=this.readSync(e.dataId),v=this.readSync(n.dataId),m=d.values,x=0;x<o.batchSize;++x)for(var b=x*e.strides[0],y=x*d.strides[0],w=0;w<o.outDepth;++w)for(var C=y+w*d.strides[1],S=w*o.strideDepth-h,k=0;k<a;k++){var I=S+k*u;if(!(I<0||I>=o.inDepth))for(var R=k*n.strides[0],N=b+I*e.strides[1],A=0;A<o.outHeight;++A)for(var L=C+A*d.strides[2],O=A*o.strideHeight-p,B=0;B<i;B++){var V=O+B*c;if(!(V<0||V>=o.inHeight))for(var U=R+B*n.strides[1],W=N+V*e.strides[2],G=0;G<o.outWidth;++G)for(var H=L+G*o.outChannels,j=G*o.strideWidth-f,ee=0;ee<s;ee++){var te=j+ee*l;if(!(te<0||te>=o.inWidth))for(var ie=U+ee*n.strides[2],se=W+te*o.inChannels,ce=ie,pe=0;pe<o.inChannels;++pe){for(var he=g[se+pe],de=0;de<o.outChannels;++de)m[H+de]+=he*v[ce+de];ce+=o.outChannels}}}}return d.toTensor()},t.prototype.conv2dDerInput=function(e,n,o){z([e,n],"conv2dDerInput");for(var a=oe(o.inShape,"float32"),i=a.values,s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=n.strides,l=c[0],h=c[1],f=c[2],p=o.batchSize,d=o.filterHeight,g=o.filterWidth,v=o.inChannels,m=o.inHeight,x=o.inWidth,b=o.outChannels,y=o.outHeight,w=o.outWidth,C=o.strideHeight,S=o.strideWidth,k=o.dataFormat,I=d-1-o.padInfo.top,R=g-1-o.padInfo.left,N=k==="channelsLast",A=a.strides[0],L=N?a.strides[1]:a.strides[2],O=N?a.strides[2]:1,B=N?1:a.strides[1],V=e.strides[0],U=N?e.strides[1]:e.strides[2],W=N?e.strides[2]:1,G=N?1:e.strides[1],H=0;H<p;++H)for(var j=0;j<v;++j)for(var ee=0;ee<m;++ee)for(var te=ee-I,ie=Math.max(0,Math.ceil(te/C)),se=Math.min(y,(d+te)/C),ce=0;ce<x;++ce){for(var pe=ce-R,he=Math.max(0,Math.ceil(pe/S)),de=Math.min(w,(g+pe)/S),De=0,fe=ie;fe<se;++fe)for(var xe=fe*C-te,me=he;me<de;++me)for(var ke=V*H+U*fe+W*me,Ce=l*(d-1-xe)+h*(g-1-(me*S-pe))+f*j,_e=0;_e<b;++_e)De+=s[ke+G*_e]*u[Ce+_e];i[A*H+L*ee+O*ce+B*j]=De}return a.toTensor()},t.prototype.conv3dDerInput=function(e,n,o){for(var a=oe(o.inShape,"float32"),i=a.values,s=a.strides,u=s[0],c=s[1],l=s[2],h=s[3],f=this.readSync(e.dataId),p=e.strides,d=p[0],g=p[1],v=p[2],m=p[3],x=this.readSync(n.dataId),b=n.strides,y=b[0],w=b[1],C=b[2],S=b[3],k=o.batchSize,I=o.filterDepth,R=o.filterHeight,N=o.filterWidth,A=o.inChannels,L=o.inDepth,O=o.inHeight,B=o.inWidth,V=o.outChannels,U=o.outDepth,W=o.outHeight,G=o.outWidth,H=o.strideDepth,j=o.strideHeight,ee=o.strideWidth,te=I-1-o.padInfo.front,ie=R-1-o.padInfo.top,se=N-1-o.padInfo.left,ce=0;ce<k;++ce)for(var pe=0;pe<A;++pe)for(var he=0;he<L;++he)for(var de=he-te,De=Math.max(0,Math.ceil(de/H)),fe=Math.min(U,(I+de)/H),xe=0;xe<O;++xe)for(var me=xe-ie,ke=Math.max(0,Math.ceil(me/j)),Ce=Math.min(W,(R+me)/j),_e=0;_e<B;++_e){for(var xt=_e-se,bt=Math.max(0,Math.ceil(xt/ee)),nt=Math.min(G,(N+xt)/ee),_n=0,Ot=De;Ot<fe;++Ot)for(var Xt=Ot*H-de,Bt=ke;Bt<Ce;++Bt)for(var En=Bt*j-me,Lt=bt;Lt<nt;++Lt)for(var yo=d*ce+g*Ot+v*Bt+m*Lt,In=y*(I-1-Xt)+w*(R-1-En)+C*(N-1-(Lt*ee-xt))+S*pe,wt=0;wt<V;++wt)_n+=f[yo+wt]*x[In+wt];i[u*ce+c*he+l*xe+h*_e+pe]=_n}return a.toTensor()},t.prototype.conv2dDerFilter=function(e,n,o){z([e,n],"conv2dDerFilter");for(var a=o.strideHeight,i=o.strideWidth,s=o.filterHeight,u=o.filterWidth,c=o.dataFormat==="channelsLast",l=oe(o.filterShape,"float32"),h=o.padInfo.left,f=o.padInfo.top,p=this.bufferSync(e),d=this.bufferSync(n),g=0;g<s;++g)for(var v=Math.max(0,Math.ceil((f-g)/a)),m=Math.min(o.outHeight,(o.inHeight+f-g)/a),x=0;x<u;++x)for(var b=Math.max(0,Math.ceil((h-x)/i)),y=Math.min(o.outWidth,(o.inWidth+h-x)/i),w=0;w<o.inChannels;++w)for(var C=0;C<o.outChannels;++C){for(var S=0,k=0;k<o.batchSize;++k)for(var I=v;I<m;++I)for(var R=g+I*a-f,N=b;N<y;++N){var A=x+N*i-h;S+=c?p.get(k,R,A,w)*d.get(k,I,N,C):p.get(k,w,R,A)*d.get(k,C,I,N)}l.set(S,g,x,w,C)}return l.toTensor()},t.prototype.conv3dDerFilter=function(e,n,o){for(var a=o.strideDepth,i=o.strideHeight,s=o.strideWidth,u=o.filterDepth,c=o.filterHeight,l=o.filterWidth,h=oe(o.filterShape,"float32"),f=h.values,p=h.strides,d=p[0],g=p[1],v=p[2],m=p[3],x=this.readSync(n.dataId),b=n.strides,y=b[0],w=b[1],C=b[2],S=b[3],k=this.readSync(e.dataId),I=e.strides,R=I[0],N=I[1],A=I[2],L=I[3],O=o.padInfo.front,B=o.padInfo.left,V=o.padInfo.top,U=0;U<u;++U)for(var W=Math.max(0,Math.ceil((O-U)/a)),G=Math.min(o.outDepth,(o.inDepth+O-U)/a),H=U*d,j=0;j<c;++j)for(var ee=Math.max(0,Math.ceil((V-j)/i)),te=Math.min(o.outHeight,(o.inHeight+V-j)/i),ie=j*g+H,se=0;se<l;++se)for(var ce=Math.max(0,Math.ceil((B-se)/s)),pe=Math.min(o.outWidth,(o.inWidth+B-se)/s),he=se*v+ie,de=0;de<o.inChannels;++de)for(var De=de*m+he,fe=0;fe<o.outChannels;++fe){for(var xe=0,me=0;me<o.batchSize;++me)for(var ke=me*R,Ce=me*y,_e=W;_e<G;++_e)for(var xt=(U+_e*a-O)*N+ke,bt=_e*w+Ce,nt=ee;nt<te;++nt)for(var _n=(j+nt*i-V)*A+xt,Ot=nt*C+bt,Xt=ce;Xt<pe;++Xt){var Bt=Xt*S+Ot;xe+=k[(se+Xt*s-B)*L+_n+de]*x[Bt+fe]}f[De+fe]=xe}return h.toTensor()},t.prototype.fusedDepthwiseConv2D=function(e){var n=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.depthwiseConv2D(n,o,a);return i&&(c=this.add(c,i)),s&&(c=Uo(this,c,s,u)),c},t.prototype.depthwiseConv2D=function(e,n,o){z([e,n],"depthwiseConv2D");for(var a=o.filterHeight,i=o.filterWidth,s=o.dilationHeight,u=o.dilationWidth,c=o.padInfo.left,l=o.padInfo.top,h=o.outChannels/o.inChannels,f=oe(o.outShape,e.dtype),p=this.readSync(e.dataId),d=this.readSync(n.dataId),g=f.values,v=0;v<o.batchSize;++v)for(var m=v*e.strides[0],x=v*f.strides[0],b=0;b<o.outHeight;++b)for(var y=x+b*f.strides[1],w=b*o.strideHeight-c,C=0;C<a;++C){var S=w+C*s;if(!(S<0||S>=o.inHeight))for(var k=C*n.strides[0],I=m+S*e.strides[1],R=0;R<o.outWidth;++R)for(var N=y+R*f.strides[2],A=R*o.strideWidth-l,L=0;L<i;++L){var O=A+L*u;if(!(O<0||O>=o.inWidth))for(var B=k+L*n.strides[1],V=I+O*o.inChannels,U=N,W=B,G=0;G<o.inChannels;++G){for(var H=p[V+G],j=0;j<h;++j)g[U+j]+=H*d[W+j];U+=h,W+=h}}}return f.toTensor()},t.prototype.depthwiseConv2DDerInput=function(e,n,o){z([e,n],"depthwiseConv2DDerInput");for(var a=oe(o.inShape,"float32"),i=a.values,s=a.strides,u=s[0],c=s[1],l=s[2],h=this.readSync(e.dataId),f=e.strides,p=f[0],d=f[1],g=f[2],v=this.readSync(n.dataId),m=n.strides,x=m[0],b=m[1],y=m[2],w=o.batchSize,C=o.filterHeight,S=o.filterWidth,k=o.inChannels,I=o.inHeight,R=o.inWidth,N=o.outChannels,A=o.outHeight,L=o.outWidth,O=o.strideHeight,B=o.strideWidth,V=C-1-o.padInfo.top,U=S-1-o.padInfo.left,W=N/k,G=0;G<w;++G)for(var H=0;H<k;++H)for(var j=0;j<I;++j)for(var ee=j-V,te=Math.max(0,Math.ceil(ee/O)),ie=Math.min(A,(C+ee)/O),se=0;se<R;++se){for(var ce=se-U,pe=Math.max(0,Math.ceil(ce/B)),he=Math.min(L,(S+ce)/B),de=0,De=te;De<ie;++De)for(var fe=De*O-ee,xe=pe;xe<he;++xe)for(var me=p*G+d*De+g*xe,ke=x*(C-1-fe)+b*(S-1-(xe*B-ce))+y*H,Ce=0;Ce<W;++Ce)de+=h[me+(H*W+Ce)]*v[ke+Ce];i[u*G+c*j+l*se+H]=de}return a.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(e,n,o){z([e,n],"depthwiseConv2DDerFilter");for(var a=o.strideHeight,i=o.strideWidth,s=o.filterHeight,u=o.filterWidth,c=oe(o.filterShape,"float32"),l=o.padInfo.left,h=o.padInfo.top,f=o.outChannels/o.inChannels,p=this.bufferSync(e),d=this.bufferSync(n),g=0;g<s;++g)for(var v=Math.max(0,Math.ceil((h-g)/a)),m=Math.min(o.outHeight,(o.inHeight+h-g)/a),x=0;x<u;++x)for(var b=Math.max(0,Math.ceil((l-x)/i)),y=Math.min(o.outWidth,(o.inWidth+l-x)/i),w=0;w<o.outChannels;++w){for(var C=Math.trunc(w/f),S=w%f,k=0,I=0;I<o.batchSize;++I)for(var R=v;R<m;++R)for(var N=g+R*a-h,A=b;A<y;++A){var L=x+A*i-l;k+=p.get(I,N,L,C)*d.get(I,R,A,w)}c.set(k,g,x,C,S)}return c.toTensor()},t.prototype.tile=function(e,n){return z(e,"tile"),au(this.bufferSync(e),n)},t.prototype.pad=function(e,n,o){z(e,"pad");var a=n.map(function(f,p){return f[0]+e.shape[p]+f[1]}),i=n.map(function(f){return f[0]}),s=this.bufferSync(e),u=oe(a,e.dtype);o!==0&&u.values.fill(o);for(var c=0;c<e.size;c++){var l=s.indexToLoc(c),h=l.map(function(f,p){return f+i[p]});u.set.apply(u,[s.get.apply(s,l)].concat(h))}return u.toTensor()},t.prototype.transpose=function(e,n){z(e,"transpose");for(var o=new Array(e.rank),a=0;a<o.length;a++)o[a]=e.shape[n[a]];var i=this.readSync(e.dataId),s=oe(o,e.dtype),u=this.bufferSync(e);for(a=0;a<e.size;++a){for(var c=u.indexToLoc(a),l=new Array(c.length),h=0;h<l.length;h++)l[h]=c[n[h]];var f=s.locToIndex(l);s.values[f]=i[a]}return s.toTensor()},t.prototype.gather=function(e,n,o){z([e,n],"gather");var a=e.shape.slice(),i=this.readSync(n.dataId);a[o]=i.length;for(var s=oe(a,e.dtype),u=this.bufferSync(e),c=0;c<s.size;++c){var l=s.indexToLoc(c),h=l.slice();h[o]=i[l[o]];var f=u.locToIndex(h);s.values[c]=u.values[f]}return s.toTensor()},t.prototype.batchToSpaceND=function(e,n,o){z([e],"batchToSpaceND");var a=n.reduce(function(h,f){return h*f}),i=Vr(e.shape,n,a),s=zr(i.length,n.length),u=Gr(e.shape,n,a),c=js(o,n.length),l=Ks(u,o,n.length);return e.reshape(i).transpose(s).reshape(u).slice(c,l)},t.prototype.spaceToBatchND=function(e,n,o){z([e],"spaceToBatchND");var a=n.reduce(function(f,p){return f*p}),i=[[0,0]];i.push.apply(i,o);for(var s=1+n.length;s<e.shape.length;++s)i.push([0,0]);var u=e.pad(i),c=Vr(u.shape,n,a,!1),l=zr(c.length,n.length,!1),h=Gr(u.shape,n,a,!1);return u.reshape(c).transpose(l).reshape(h)},t.prototype.pool=function(e,n,o){z(e,"pool");for(var a=n.strideHeight,i=n.strideWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=n.padInfo.top,f=n.padInfo.left,p=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,d=this.readSync(e.dataId),g=oe(n.outShape,e.dtype),v=g.values,m=n.outShape[1]*n.outShape[2]*n.outShape[3],x=n.outShape[2]*n.outShape[3],b=n.outShape[3],y=0;y<n.batchSize;++y)for(var w=y*m,C=y*e.strides[0],S=0;S<n.inChannels;++S)for(var k=0;k<n.outHeight;++k)for(var I=k*a-h,R=Math.max(0,I),N=Math.min(n.inHeight,c+I),A=w+k*x,L=0;L<n.outWidth;++L){for(var O=L*i-f,B=Math.max(0,O),V=Math.min(n.inWidth,l+O),U=p,W=0,G=0,H=R;H<N;H+=s){for(var j=C+H*e.strides[1],ee=B;ee<V;ee+=u){var te=d[j+ee*e.strides[2]+S];o==="max"&&te>U?U=te:o==="avg"&&(W+=te,G++)}if(isNaN(U))break}v[A+L*b+S]=o==="avg"?W/G:U}return g.toTensor()},t.prototype.maxPool=function(e,n){return this.pool(e,n,"max")},t.prototype.maxPoolPositions=function(e,n){for(var o=oe(n.outShape,"int32"),a=n.strideHeight,i=n.strideWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=n.padInfo.top,f=n.padInfo.left,p=this.bufferSync(e),d=0;d<n.batchSize;++d)for(var g=0;g<n.inChannels;++g)for(var v=0;v<n.outHeight;++v){for(var m=v*a-h,x=m;x<0;)x+=s;for(var b=Math.min(n.inHeight,c+m),y=0;y<n.outWidth;++y){for(var w=y*i-f,C=w;C<0;)C+=u;for(var S=Math.min(n.inWidth,l+w),k=Number.NEGATIVE_INFINITY,I=-1,R=x;R<b;R+=s)for(var N=R-m,A=C;A<S;A+=u){var L=A-w,O=p.get(d,R,A,g);O>k&&(k=O,I=N*l+L)}o.set(I,d,v,y,g)}}return o.toTensor()},t.prototype.maxPoolBackprop=function(e,n,o,a){z([n,o],"maxPoolBackprop");for(var i=this.maxPoolPositions(n,a),s=a.strideHeight,u=a.strideWidth,c=a.dilationHeight,l=a.dilationWidth,h=a.effectiveFilterHeight,f=a.effectiveFilterWidth,p=f-1-a.padInfo.left,d=h-1-a.padInfo.top,g=oe(n.shape,"float32"),v=this.bufferSync(i),m=this.bufferSync(e),x=0;x<a.batchSize;++x)for(var b=0;b<a.inChannels;++b)for(var y=0;y<a.inHeight;++y)for(var w=0;w<a.inWidth;++w){for(var C=y-d,S=w-p,k=0,I=0;I<h;I+=c){var R=(C+I)/s;if(!(R<0||R>=a.outHeight||Math.floor(R)!==R))for(var N=0;N<f;N+=l){var A=(S+N)/u;if(!(A<0||A>=a.outWidth||Math.floor(A)!==A)){var L=h*f-1-v.get(x,R,A,b)===I*f+N?1:0;L!==0&&(k+=m.get(x,R,A,b)*L)}}}g.set(k,x,y,w,b)}return g.toTensor()},t.prototype.avgPoolBackprop=function(e,n,o){z([e,n],"avgPoolBackprop");for(var a=o.strideHeight,i=o.strideWidth,s=o.filterHeight,u=o.filterWidth,c=o.dilationHeight,l=o.dilationWidth,h=o.effectiveFilterHeight,f=o.effectiveFilterWidth,p=f-1-o.padInfo.left,d=h-1-o.padInfo.top,g=oe(n.shape,"float32"),v=1/(s*u),m=this.bufferSync(e),x=0;x<o.batchSize;++x)for(var b=0;b<o.inChannels;++b)for(var y=0;y<o.inHeight;++y)for(var w=0;w<o.inWidth;++w){for(var C=y-d,S=w-p,k=0,I=0;I<h;I+=c){var R=(C+I)/a;if(!(R<0||R>=o.outHeight||Math.floor(R)!==R))for(var N=0;N<f;N+=l){var A=(S+N)/i;A<0||A>=o.outWidth||Math.floor(A)!==A||(k+=m.get(x,R,A,b))}}g.set(k*v,x,y,w,b)}return g.toTensor()},t.prototype.pool3d=function(e,n,o){z(e,"pool3d");for(var a=n.strideDepth,i=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,p=n.effectiveFilterWidth,d=n.padInfo.front,g=n.padInfo.top,v=n.padInfo.left,m=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=this.readSync(e.dataId),b=oe(n.outShape,e.dtype),y=b.values,w=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],C=n.outShape[2]*n.outShape[3]*n.outShape[4],S=n.outShape[3]*n.outShape[4],k=n.outShape[4],I=0;I<n.batchSize;++I)for(var R=I*w,N=I*e.strides[0],A=0;A<n.inChannels;++A)for(var L=0;L<n.outDepth;++L){for(var O=L*a-d,B=O;B<0;)B+=u;for(var V=Math.min(n.inDepth,h+O),U=R+L*C,W=0;W<n.outHeight;++W){for(var G=W*i-g,H=G;H<0;)H+=c;for(var j=Math.min(n.inHeight,f+G),ee=U+W*S,te=0;te<n.outWidth;++te){for(var ie=te*s-v,se=ie;se<0;)se+=l;for(var ce=Math.min(n.inWidth,p+ie),pe=ee+te*k,he=m,de=0,De=0,fe=B;fe<V;fe+=u){for(var xe=N+fe*e.strides[1],me=H;me<j;me+=c){for(var ke=xe+me*e.strides[2],Ce=se;Ce<ce;Ce+=l){var _e=x[ke+Ce*e.strides[3]+A];if(o==="max"&&_e>he?he=_e:o==="avg"&&(de+=_e,De++),isNaN(he))break}if(isNaN(he))break}if(isNaN(he))break}y[pe+A]=o==="avg"?de/De:he}}}return b.toTensor()},t.prototype.avgPool3d=function(e,n){return z(e,"avgPool3d"),this.pool3d(e,n,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,n,o){z([e,n],"avgPool3dBackprop");for(var a=o.strideDepth,i=o.strideHeight,s=o.strideWidth,u=o.filterDepth,c=o.filterHeight,l=o.filterWidth,h=o.dilationDepth,f=o.dilationHeight,p=o.dilationWidth,d=o.effectiveFilterDepth,g=o.effectiveFilterHeight,v=o.effectiveFilterWidth,m=d-1-o.padInfo.front,x=v-1-o.padInfo.left,b=g-1-o.padInfo.top,y=oe(n.shape,"float32"),w=1/(u*c*l),C=this.bufferSync(e),S=0;S<o.batchSize;++S)for(var k=0;k<o.inChannels;++k)for(var I=0;I<o.inDepth;++I)for(var R=0;R<o.inHeight;++R)for(var N=0;N<o.inWidth;++N){for(var A=I-m,L=R-b,O=N-x,B=0,V=0;V<d;V+=h){var U=(A+V)/a;if(!(U<0||U>=o.outDepth||Math.floor(U)!==U))for(var W=0;W<g;W+=f){var G=(L+W)/i;if(!(G<0||G>=o.outHeight||Math.floor(G)!==G))for(var H=0;H<v;H+=p){var j=(O+H)/s;j<0||j>=o.outWidth||Math.floor(j)!==j||(B+=C.get(S,U,G,j,k))}}}y.set(B*w,S,I,R,N,k)}return y.toTensor()},t.prototype.maxPool3d=function(e,n){return z(e,"maxPool3d"),this.pool3d(e,n,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,n){for(var o=oe(n.outShape,"int32"),a=n.strideDepth,i=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,p=n.effectiveFilterWidth,d=n.padInfo.front,g=n.padInfo.top,v=n.padInfo.left,m=this.bufferSync(e),x=0;x<n.batchSize;++x)for(var b=0;b<n.inChannels;++b)for(var y=0;y<n.outDepth;++y){for(var w=y*a-d,C=w;C<0;)C+=u;for(var S=Math.min(n.inDepth,h+w),k=0;k<n.outHeight;++k){for(var I=k*i-g,R=I;R<0;)R+=c;for(var N=Math.min(n.inHeight,f+I),A=0;A<n.outWidth;++A){for(var L=A*s-v,O=L;O<0;)O+=l;for(var B=Math.min(n.inWidth,p+L),V=Number.NEGATIVE_INFINITY,U=-1,W=C;W<S;W+=u)for(var G=W-w,H=R;H<N;H+=c)for(var j=H-I,ee=O;ee<B;ee+=l){var te=ee-L,ie=m.get(x,W,H,ee,b);ie>=V&&(V=ie,U=G*f*p+j*f+te)}o.set(U,x,y,k,A,b)}}}return o.toTensor()},t.prototype.maxPool3dBackprop=function(e,n,o,a){z([n,o],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(n,a),s=a.strideDepth,u=a.strideHeight,c=a.strideWidth,l=a.dilationDepth,h=a.dilationHeight,f=a.dilationWidth,p=a.effectiveFilterDepth,d=a.effectiveFilterHeight,g=a.effectiveFilterWidth,v=p-1-a.padInfo.front,m=g-1-a.padInfo.left,x=d-1-a.padInfo.top,b=oe(n.shape,"float32"),y=this.bufferSync(i),w=this.bufferSync(e),C=0;C<a.batchSize;++C)for(var S=0;S<a.inChannels;++S)for(var k=0;k<a.inDepth;++k)for(var I=0;I<a.inHeight;++I)for(var R=0;R<a.inWidth;++R){for(var N=k-v,A=I-x,L=R-m,O=0,B=0;B<p;B+=l){var V=(N+B)/s;if(!(V<0||V>=a.outDepth||Math.floor(V)!==V))for(var U=0;U<d;U+=h){var W=(A+U)/u;if(!(W<0||W>=a.outHeight||Math.floor(W)!==W))for(var G=0;G<g;G+=f){var H=(L+G)/c;if(!(H<0||H>=a.outWidth||Math.floor(H)!==H)){var j=p*d*g-1-y.get(C,V,W,H,S)===B*d*g+U*g+G?1:0;j!==0&&(O+=w.get(C,V,W,H,S)*j)}}}}b.set(O,C,k,I,R,S)}return b.toTensor()},t.prototype.cast=function(e,n){return tu(e,n,this)},t.prototype.reshape=function(e,n){return ca(e,n)},t.prototype.avgPool=function(e,n){return z(e,"avgPool"),this.pool(e,n,"avg").toFloat()},t.prototype.resizeBilinear=function(e,n,o,a){z(e,"resizeBilinear");for(var i=e.shape,s=i[0],u=i[1],c=i[2],l=i[3],h=this.readSync(e.dataId),f=new Float32Array(Y([s,n,o,l])),p=[a&&n>1?u-1:u,a&&o>1?c-1:c],d=[a&&n>1?n-1:n,a&&o>1?o-1:o],g=0,v=p[0]/d[0],m=p[1]/d[1],x=0;x<s;x++)for(var b=0;b<n;b++)for(var y=v*b,w=Math.floor(y),C=y-w,S=Math.min(u-1,Math.ceil(y)),k=x*e.strides[0]+w*e.strides[1],I=x*e.strides[0]+S*e.strides[1],R=0;R<o;R++)for(var N=m*R,A=Math.floor(N),L=N-A,O=Math.min(c-1,Math.ceil(N)),B=k+A*e.strides[2],V=I+A*e.strides[2],U=k+O*e.strides[2],W=I+O*e.strides[2],G=0;G<l;G++){var H=h[B+G],j=h[V+G],ee=H+(h[U+G]-H)*L,te=ee+(j+(h[W+G]-j)*L-ee)*C;f[g++]=te}return Ge(f,[s,n,o,l])},t.prototype.resizeBilinearBackprop=function(e,n,o){z([e,n],"resizeBilinearBackprop");for(var a=n.shape,i=a[0],s=a[1],u=a[2],c=a[3],l=e.shape,h=l[1],f=l[2],p=new Float32Array(i*s*u*c),d=[o&&h>1?s-1:s,o&&f>1?u-1:u],g=[o&&h>1?h-1:h,o&&f>1?f-1:f],v=d[0]/g[0],m=d[1]/g[1],x=this.readSync(e.dataId),b=0,y=0;y<i;y++)for(var w=y*n.strides[0],C=0;C<h;C++)for(var S=C*v,k=Math.floor(S),I=Math.min(Math.ceil(S),s-1),R=w+k*n.strides[1],N=w+I*n.strides[1],A=S-k,L=1-A,O=0;O<f;O++)for(var B=O*m,V=Math.floor(B),U=Math.min(Math.ceil(B),u-1),W=B-V,G=1-W,H=R+V*n.strides[2],j=R+U*n.strides[2],ee=N+V*n.strides[2],te=N+U*n.strides[2],ie=L*G,se=L*W,ce=A*G,pe=A*W,he=0;he<c;he++){var de=x[b++];p[H+he]+=de*ie,p[j+he]+=de*se,p[ee+he]+=de*ce,p[te+he]+=de*pe}return Je(p,[i,u,s,c],n.dtype)},t.prototype.resizeNearestNeighbor=function(e,n,o,a){z(e,"resizeNearestNeighbor");for(var i=e.shape,s=i[0],u=i[1],c=i[2],l=i[3],h=this.readSync(e.dataId),f=new Float32Array(s*n*o*l),p=[a&&n>1?u-1:u,a&&o>1?c-1:c],d=[a&&n>1?n-1:n,a&&o>1?o-1:o],g=p[0]/d[0],v=p[1]/d[1],m=0,x=0;x<s;x++)for(var b=x*e.strides[0],y=0;y<n;y++)for(var w=g*y,C=b+Math.min(u-1,a?Math.round(w):Math.floor(w))*e.strides[1],S=0;S<o;S++)for(var k=v*S,I=C+Math.min(c-1,a?Math.round(k):Math.floor(k))*e.strides[2],R=0;R<l;R++){var N=h[I+R];f[m++]=N}return Ge(f,[s,n,o,l],e.dtype)},t.prototype.resizeNearestNeighborBackprop=function(e,n,o){z([e,n],"resizeNearestNeighborBackprop");for(var a=n.shape,i=a[0],s=a[1],u=a[2],c=a[3],l=e.shape,h=l[1],f=l[2],p=new Float32Array(i*s*u*c),d=this.readSync(e.dataId),g=[o&&h>1?s-1:s,o&&f>1?u-1:u],v=[o&&h>1?h-1:h,o&&f>1?f-1:f],m=g[0]/v[0],x=g[1]/v[1],b=1/m,y=1/x,w=2*Math.ceil(b)+2,C=2*Math.ceil(y)+2,S=0;S<i;S++)for(var k=S*n.strides[0],I=0;I<s;I++)for(var R=k+I*n.strides[1],N=Math.floor(I*b),A=Math.floor(N-w/2),L=0;L<u;L++)for(var O=R+L*n.strides[2],B=Math.floor(L*y),V=Math.floor(B-C/2),U=0;U<c;U++){for(var W=0,G=0;G<w;G++){var H=G+A;if(!(H<0||H>=h)){var j=k+H*e.strides[1],ee=H*m;if(I===Math.min(s-1,o?Math.round(ee):Math.floor(ee)))for(var te=0;te<C;te++){var ie=te+V;if(!(ie<0||ie>=f)){var se=j+ie*e.strides[2],ce=ie*x;L===Math.min(u-1,o?Math.round(ce):Math.floor(ce))&&(W+=d[se+U])}}}}p[O+U]=W}return Je(p,n.shape,n.dtype)},t.prototype.batchNormalization=function(e,n,o,a,i,s){z([e,n,o,i,s],"batchNorm");for(var u=this.readSync(e.dataId),c=this.readSync(n.dataId),l=this.readSync(o.dataId),h=i?this.readSync(i.dataId):new Float32Array([1]),f=s?this.readSync(s.dataId):new Float32Array([0]),p=new Float32Array(u.length),d=f.length,g=h.length,v=l.length,m=c.length,x=0,b=0,y=0,w=0,C=0;C<u.length;++C)p[C]=f[x++]+(u[C]-c[b++])*h[y++]/Math.sqrt(l[w++]+a),x>=d&&(x=0),b>=m&&(b=0),y>=g&&(y=0),w>=v&&(w=0);return Je(p,e.shape)},t.prototype.localResponseNormalization4D=function(e,n,o,a,i){z(e,"localResponseNormalization4D");var s=e.shape[3],u=s-1,c=this.readSync(e.dataId),l=e.size,h=new Float32Array(l);function f(v){for(var m=v%s,x=v-m+Math.max(0,m-n),b=v-m+Math.min(m+n,u),y=0;x<=b;x++){var w=c[x];y+=w*w}return y}for(var p=0;p<l;p++){var d=f(p),g=c[p]*Math.pow(o+a*d,-i);h[p]=g}return Je(h,e.shape)},t.prototype.LRNGrad=function(e,n,o,a,i,s,u){z(e,"LRNGrad");for(var c=e.shape[3],l=this.readSync(e.dataId),h=this.readSync(n.dataId),f=this.readSync(o.dataId),p=new Float32Array(e.size),d=e.size,g=0;g<d;g++){for(var v=g%c,m=g-v+Math.max(0,v-a),x=g-v+Math.min(c,v+a+1),b=0,y=m;y<x;y++)b+=Math.pow(h[y],2);for(b=s*b+i,y=m;y<x;y++){var w=-2*s*u*h[y]*f[g]/b;g===y&&(w+=Math.pow(b,-u)),w*=l[g],p[y]+=w}}return Je(p,e.shape)},t.prototype.multinomial=function(e,n,o,a){z(e,"multinomial");for(var i=n?e:Gt(e),s=i.shape[0],u=i.shape[1],c=we([s,o],"int32"),l=this.readSync(c.dataId),h=this.readSync(i.dataId),f=0;f<s;++f){var p=f*u,d=new Float32Array(u-1);d[0]=h[p];for(var g=1;g<d.length;++g)d[g]=d[g-1]+h[p+g];for(var v=ro(a.toString()),m=f*o,x=0;x<o;++x){var b=v();l[m+x]=d.length;for(var y=0;y<d.length;y++)if(b<d[y]){l[m+x]=y;break}}}return c},t.prototype.oneHot=function(e,n,o,a){z(e,"oneHot");var i=new Float32Array(e.size*n);i.fill(a);for(var s=this.readSync(e.dataId),u=0;u<e.size;++u)s[u]>=0&&s[u]<n&&(i[u*n+s[u]]=o);return Zt(i,[e.size,n],"int32")},t.prototype.nonMaxSuppression=function(e,n,o,a,i){return z(e,"nonMaxSuppression"),Sa(this.readSync(e.dataId),this.readSync(n.dataId),o,a,i)},t.prototype.fft=function(e){return this.fftBatch(e,!1)},t.prototype.ifft=function(e){return this.fftBatch(e,!0)},t.prototype.fftBatch=function(e,n){for(var o=e.shape[0],a=e.shape[1],i=oe(e.shape,"float32"),s=oe(e.shape,"float32"),u=ht(e).as2D(o,a),c=Rt(e).as2D(o,a),l=0;l<o;l++)for(var h=u.slice([l,0],[1,a]),f=c.slice([l,0],[1,a]),p=Ve(h,f),d=this.readSync(this.fftImpl(p,n).dataId),g=0;g<a;g++){var v=Mi(d,g);i.values[l*a+g]=v.real,s.values[l*a+g]=v.imag}return Ve(i.toTensor(),s.toTensor()).as2D(o,a)},t.prototype.fftImpl=function(e,n){var o=e.as1D(),a=o.size;if(this.isExponentOf2(a)){var i=this.fftRadix2(o,a,n).as2D(e.shape[0],e.shape[1]);return n&&(i=Ve(ht(i).div(q(a)),Rt(i).div(q(a)))),i}var s=this.readSync(e.dataId),u=function(c){for(var l=new Float32Array(c.length/2),h=new Float32Array(c.length/2),f=0;f<c.length;f+=2)l[f/2]=c[f],h[f/2]=c[f+1];return{real:l,imag:h}}(this.fourierTransformByMatmul(s,a,n));return Ve(u.real,u.imag).as2D(e.shape[0],e.shape[1])},t.prototype.isExponentOf2=function(e){return(e&e-1)==0},t.prototype.fftRadix2=function(e,n,o){if(n===1)return e;var a=this.readSync(e.dataId),i=n/2,s=function(m){for(var x=Math.ceil(m.length/4),b=new Float32Array(x),y=new Float32Array(x),w=0;w<m.length;w+=4)b[Math.floor(w/4)]=m[w],y[Math.floor(w/4)]=m[w+1];return{real:b,imag:y}}(a),u=Ve(s.real,s.imag).as1D(),c=function(m){for(var x=Math.floor(m.length/4),b=new Float32Array(x),y=new Float32Array(x),w=2;w<m.length;w+=4)b[Math.floor(w/4)]=m[w],y[Math.floor(w/4)]=m[w+1];return{real:b,imag:y}}(a),l=Ve(c.real,c.imag).as1D();u=this.fftRadix2(u,i,o),l=this.fftRadix2(l,i,o);var h=function(m,x){for(var b=new Float32Array(m/2),y=new Float32Array(m/2),w=0;w<Math.ceil(m/2);w++){var C=(x?2:-2)*Math.PI*(w/m);b[w]=Math.cos(C),y[w]=Math.sin(C)}return{real:b,imag:y}}(n,o),f=Ve(h.real,h.imag).mul(l),p=u.add(f),d=u.sub(f),g=ht(p).concat(ht(d)),v=Rt(p).concat(Rt(d));return Ve(g,v).as1D()},t.prototype.fourierTransformByMatmul=function(e,n,o){for(var a=new Float32Array(2*n),i=0;i<n;i++){for(var s=0,u=0,c=0;c<n;c++){var l=Dh(i*c,n,o),h=Mi(e,c);s+=h.real*l.real-h.imag*l.imag,u+=h.real*l.imag+h.imag*l.real}o&&(s/=n,u/=n),Sh(a,s,u,i)}return a},t.prototype.depthToSpace=function(e,n,o){E(o==="NHWC",function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+o}),E(n>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+n});for(var a=e.shape[0],i=e.shape[1],s=e.shape[2],u=e.shape[3],c=i*n,l=s*n,h=u/(n*n),f=this.readSync(e.dataId),p=new Float32Array(a*c*l*h),d=0,g=0;g<a;++g)for(var v=0;v<c;++v)for(var m=Math.floor(v/n),x=v%n,b=0;b<l;++b)for(var y=Math.floor(b/n),w=(x*n+b%n)*h,C=0;C<h;++C){var S=C+w+u*(y+s*(m+i*g));p[d++]=f[S]}return Je(p,[a,c,l,h])},t.prototype.broadcastedBinaryOp=function(e,n,o,a){var i=le(e.shape,n.shape),s=oe(i,o),u=this.readSync(e.dataId),c=this.readSync(n.dataId),l=Jt(e.shape,i),h=Jt(n.shape,i),f=s.values;if(l.length+h.length===0)for(var p=0;p<f.length;++p)f[p]=a(u[p%u.length],c[p%c.length]);else{var d=this.bufferSync(e),g=this.bufferSync(n),v=function(m){var x=s.indexToLoc(m),b=x.slice(-e.rank);l.forEach(function(S){return b[S]=0});var y=d.locToIndex(b),w=x.slice(-n.rank);h.forEach(function(S){return w[S]=0});var C=g.locToIndex(w);f[m]=a(u[y],c[C])};for(p=0;p<f.length;++p)v(p)}return s.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(e,n,o){var a=le(e.shape,n.shape),i=oe(a,"float32"),s=oe(a,"float32"),u=this.readSync(e.dataId),c=this.readSync(n.dataId),l=Jt(e.shape,a),h=Jt(n.shape,a),f=i.values,p=s.values;if(l.length+h.length===0)for(var d=0;d<f.length;d++){var g=d%u.length,v=d%c.length,m=o(u[2*g],u[2*g+1],c[2*v],c[2*v+1]);f[d]=m.real,p[d]=m.imag}else{var x=this.bufferSync(this.data.get(e.dataId).complexTensors.real),b=this.bufferSync(this.data.get(n.dataId).complexTensors.real),y=function(w){var C=i.indexToLoc(w),S=C.slice(-e.rank);l.forEach(function(A){return S[A]=0});var k=x.locToIndex(S),I=C.slice(-n.rank);h.forEach(function(A){return I[A]=0});var R=b.locToIndex(I),N=o(u[2*k],u[2*k+1],c[2*R],c[2*R+1]);f[w]=N.real,p[w]=N.imag};for(d=0;d<f.length;d++)y(d)}return this.complex(i.toTensor(),s.toTensor())},t.prototype.split=function(e,n,o){return ou(e,n,o)},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32},t.prototype.epsilon=function(){return 1e-7},t.prototype.cropAndResize=function(e,n,o,a,i,s){for(var u=e.shape,c=u[0],l=u[1],h=u[2],f=u[3],p=n.shape[0],d=a[0],g=a[1],v=oe([p,d,g,f],"float32"),m=this.readSync(n.dataId),x=this.readSync(o.dataId),b=this.readSync(e.dataId),y=e.strides,w=v.strides,C=0;C<p;C++){var S=4*C,k=m[S],I=m[S+1],R=m[S+2],N=m[S+3],A=x[C];if(!(A>=c))for(var L=d>1?(R-k)*(l-1)/(d-1):0,O=g>1?(N-I)*(h-1)/(g-1):0,B=0;B<d;B++){var V=d>1?k*(l-1)+B*L:.5*(k+R)*(l-1);if(V<0||V>l-1)for(var U=0;U<g;U++)for(var W=0;W<f;W++){var G=W+U*w[2]+B*w[1]+C*w[0];v.values[G]=s}else if(i==="bilinear"){var H=Math.floor(V),j=Math.ceil(V),ee=V-H;for(U=0;U<g;U++)if((fe=g>1?I*(h-1)+U*O:.5*(I+N)*(h-1))<0||fe>h-1)for(W=0;W<f;W++)G=W+U*w[2]+B*w[1]+C*w[0],v.values[G]=s;else{var te=Math.floor(fe),ie=Math.ceil(fe),se=fe-te;for(W=0;W<f;W++){var ce=b[G=W+te*y[2]+H*y[1]+A*y[0]],pe=b[G=W+ie*y[2]+H*y[1]+A*y[0]],he=b[G=W+te*y[2]+j*y[1]+A*y[0]],de=ce+(pe-ce)*se,De=he+(b[G=W+ie*y[2]+j*y[1]+A*y[0]]-he)*se;G=W+U*w[2]+B*w[1]+C*w[0],v.values[G]=de+(De-de)*ee}}}else for(U=0;U<g;++U){var fe;if((fe=g>1?I*(h-1)+U*O:.5*(I+N)*(h-1))<0||fe>h-1)for(W=0;W<f;W++)G=W+U*w[2]+B*w[1]+C*w[0],v.values[G]=s;else{var xe=Math.round(fe),me=Math.round(V);for(W=0;W<f;W++){var ke=W+xe*y[2]+me*y[1]+A*y[0],Ce=W+U*w[2]+B*w[1]+C*w[0];v.values[Ce]=b[ke]}}}}}return v.toTensor()},t.prototype.sparseToDense=function(e,n,o,a){var i=Hr(0,e,o),s=i.sliceRank,u=i.numUpdates,c=i.sliceSize,l=i.strides,h=i.outputSize;return this.scatter(e,n,o,h,c,u,s,l,a,!1)},t.prototype.gatherND=function(e,n){var o=n.shape,a=o[o.length-1],i=Xs(e,n),s=i[0],u=i[1],c=i[2],l=i[3];if(u===0)return Ge([],s,e.dtype);for(var h=new nr([u,c],e.dtype),f=this.readSync(n.dataId),p=this.readSync(e.dataId),d=0;d<u;d++){for(var g=[],v=0,m=0;m<a;m++){var x=f[d*a+m];v+=x*l[m],g.push(x)}if(v<0||v>=e.size/c)throw new Error("Invalid indices: "+g+" does not index into "+e.shape);for(var b=0;b<c;b++)h.values[d*c+b]=p[v*c+b]}return h.toTensor().reshape(s)},t.prototype.scatterND=function(e,n,o){var a=Hr(0,e,o),i=a.sliceRank,s=a.numUpdates,u=a.sliceSize,c=a.strides,l=a.outputSize,h=q(0);return this.scatter(e,n,o,l,u,s,i,c,h,!0)},t.prototype.fill=function(e,n,o){var a=Pr(o=o||ur(n),Y(e));return a.fill(n),T.makeTensor(a,e,o,this)},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){var n=Pr(e.dtype,Y(e.shape));return this.makeOutput(n,e.shape,e.dtype)},t.prototype.linspace=function(e,n,o){return nu(e,n,o)},t.prototype.scatter=function(e,n,o,a,i,s,u,c,l,h){var f=[a/i,i],p=this.readSync(e.dataId),d=this.readSync(n.dataId);if(a===0)return Ge([],o,n.dtype);var g=new nr(f,n.dtype);g.values.fill(this.readSync(l.dataId)[0]);for(var v=0;v<s;v++){for(var m=[],x=0,b=0;b<u;b++){var y=p[v*u+b];m.push(y),x+=y*c[b]}if(x<0||x>=a/i)throw new Error("Invalid indices: "+m+" does not index into "+o);for(var w=0;w<i;w++)h?g.values[x*i+w]+=d[v*i+w]:g.values[x*i+w]=n.rank===0?d[0]:d[v*i+w]}return g.toTensor().reshape(o)},t}(Zs);T.registerBackend("cpu",function(){return new Yv},1);for(var Vo=0,rs=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=r.attrs,o=t,a=o.boxes,i=o.scores,s=n,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=e;z(a,"NonMaxSuppressionWithScore");var p=Da(f.data.get(a.dataId).values,f.data.get(i.dataId).values,u,c,l,h);return[p.selectedIndices,p.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=t.x,o=e;z(n,"square");for(var a=o.data.get(n.dataId).values,i=new Float32Array(a.length),s=0;s<a.length;++s){var u=a[s];i[s]=u*u}return{dataId:o.write(i,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},{kernelName:ar,backendName:"cpu",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=t,o=n.a,a=n.b,i=e;z([o,a],ar);var s=i.data.get(o.dataId).values,u=i.data.get(a.dataId).values,c=function(f,p,d,g,v,m){var x=le(f,p),b=x.length,y=Dt(x),w=tr(v,Y(x)),C=f.length,S=p.length,k=Dt(f),I=Dt(p),R=Jt(f,x),N=Jt(p,x);if(R.length+N.length===0)for(var A=0;A<w.length;++A)w[A]=m(d[A%d.length],g[A%g.length]);else{var L=function(O){var B=al(O,b,y),V=B.slice(-C);R.forEach(function(H){return V[H]=0});var U=Ri(V,C,k),W=B.slice(-S);N.forEach(function(H){return W[H]=0});var G=Ri(W,S,I);w[O]=m(d[U],g[G])};for(A=0;A<w.length;++A)L(A)}return[w,x]}(o.shape,a.shape,s,u,o.dtype,function(f,p){var d=f-p;return d*d}),l=c[0],h=c[1];return{dataId:i.write(l,h,o.dtype),shape:h,dtype:o.dtype}}}];Vo<rs.length;Vo++)ks(rs[Vo]);var kn,Jv=function(r){this.variableNames=["A"];var t=je(),e=r[0],n=r[1];this.outputShape=r,this.userCode=`
3759      void main() {
3760        ivec3 coords = getOutputCoords();
3761        int texR = coords[0];
3762        int texC = coords[1];
3763        int depth = coords[2];
3764        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+n+".0, "+e+`.0);
3765
3766        vec4 values = `+t.texture2D+`(A, uv);
3767        float value;
3768        if (depth == 0) {
3769          value = values.r;
3770        } else if (depth == 1) {
3771          value = values.g;
3772        } else if (depth == 2) {
3773          value = values.b;
3774        } else if (depth == 3) {
3775          value = values.a;
3776        }
3777
3778        setOutput(floor(value * 255.0 + 0.5));
3779      }
3780    `},Qv=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var t=je(),e=r[0],n=r[1];this.outputShape=r,this.userCode=`
3781      void main() {
3782        ivec3 coords = getOutputCoords();
3783        int texR = coords[0];
3784        int texC = coords[1];
3785        int depth = coords[2];
3786
3787        vec4 result = vec4(0.);
3788
3789        for(int row=0; row<=1; row++) {
3790          for(int col=0; col<=1; col++) {
3791            texC = coords[1] + row;
3792            depth = coords[2] + col;
3793
3794            vec2 uv = (vec2(texC, texR) + halfCR) /
3795                       vec2(`+n+".0, "+e+`.0);
3796            vec4 values = `+t.texture2D+`(A, uv);
3797            float value;
3798            if (depth == 0) {
3799              value = values.r;
3800            } else if (depth == 1) {
3801              value = values.g;
3802            } else if (depth == 2) {
3803              value = values.b;
3804            } else if (depth == 3) {
3805              value = values.a;
3806            }
3807
3808            result[row * 2 + col] = floor(value * 255.0 + 0.5);
3809          }
3810        }
3811
3812        `+t.output+` = result;
3813      }
3814    `};for(var zo=0,os=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=r.attrs,o=t.pixels,a=n.numChannels,i=typeof HTMLVideoElement<"u"&&o instanceof HTMLVideoElement,s=typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement,u=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],c=u[0],l=u[1],h=[l,c],f=[l,c,a];(s||i)&&(kn==null&&(kn=document.createElement("canvas").getContext("2d")),kn.canvas.width=c,kn.canvas.height=l,kn.drawImage(o,0,0,c,l),o=kn.canvas);var p=e.makeTensorInfo(h,"int32");e.texData.get(p.dataId).usage=it.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),o);var d=M().getBool("WEBGL_PACK")?new Qv(f):new Jv(f),g=e.runWebGLProgram(d,[p],"int32");return e.disposeData(p.dataId),g}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=r.attrs;Lr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var o=t,a=o.boxes,i=o.scores,s=n,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=e,p=Da(f.readSync(a.dataId),f.readSync(i.dataId),u,c,l,h);return[p.selectedIndices,p.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=t.x,o=e,a=new ae(n.shape,"return x * x;");return o.runWebGLProgram(a,[n],n.dtype)}},{kernelName:ar,backendName:"webgl",kernelFunc:function(r){var t=r.inputs,e=r.backend,n=t,o=n.a,a=n.b,i=e,s=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ut("return (a 
3814- b) * (a - b);",o.shape,a.shape):new Se("return (a - b) * (a - b);",o.shape,a.shape);return i.compileAndRun(s,[o,a])}}];zo<os.length;zo++)ks(os[zo]);for(var Go=0,as=[{kernelName:"Square",gradFunc:function(r,t){var e=t[0];return{x:function(){return r.mul(e.toFloat().mul(2))}}}},{kernelName:ar,gradFunc:function(r,t){var e=t[0],n=t[1],o=q(2);return{a:function(){return Xe(r,Xe(o,Oe(e,n)))},b:function(){return Xe(r,Xe(o,Oe(n,e)))}}}}];Go<as.length;Go++)Xc(as[Go]);var Zv=function(){function r(){}return r.prototype.fetch=function(t,e){return fetch(t,e)},r.prototype.now=function(){return performance.now()},r.prototype.encode=function(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error("Browser's encoder only supports utf-8, but got "+e);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},r.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},r}();M().get("IS_BROWSER")&&M().setPlatform("browser",new Zv);var Ho,em=function(){return require("node-fetch")},tm=function(){function r(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return r.prototype.fetch=function(t,e){return M().global.fetch!=null?M().global.fetch(t,e):(Ho==null&&(Ho=em()),Ho(t,e))},r.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},r.prototype.encode=function(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},r.prototype.decode=function(t,e){return t.length===0?"":new this.util.TextDecoder(e).decode(t)},r}();M().get("IS_NODE")&&M().setPlatform("node",new tm);var fa={float32:4,int32:4,uint16:2,uint8:1,bool:1},Jr=4;function Yu(r,t){for(var e={},n=0,o=function(s){var u=s.name,c=s.dtype,l=s.shape,h=Y(l),f=void 0;if("quantization"in s){var p=s.quantization;if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error("Weight "+s.name+" has unknown quantization dtype "+p.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var d=fa[p.dtype],g=r.slice(n,n+h*d),v=p.dtype==="uint8"?new Uint8Array(g):new Uint16Array(g);if(c==="float32")f=Float32Array.from(v,function(C){return C*p.scale+p.min});else{if(c!=="int32")throw new Error("Unsupported dtype in weight '"+u+"': "+c);f=Int32Array.from(v,function(C){return Math.round(C*p.scale+p.min)})}n+=h*d}else if(c==="string"){var m=Y(s.shape);f=[];for(var x=0;x<m;x++){var b=new Uint32Array(r.slice(n,n+Jr))[0];n+=Jr;var y=new Uint8Array(r.slice(n,n+b));f.push(y),n+=b}}else{var w=fa[c];if(g=r.slice(n,n+h*w),c==="float32")f=new Float32Array(g);else if(c==="int32")f=new Int32Array(g);else{if(c!=="bool")throw new Error("Unsupported dtype in weight '"+u+"': "+c);f=new Uint8Array(g)}n+=h*w}e[u]=Ge(f,l,c)},a=0,i=t;a<i.length;a++)o(i[a]);return e}function nm(r){if(r===null)throw new Error("Invalid input value: "+JSON.stringify(r));var t=0,e=[];r.forEach(function(a){if(t+=a.byteLength,e.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+a.constructor.name)});var n=new Uint8Array(t),o=0;return e.forEach(function(a){n.set(new Uint8Array(a.buffer),o),o+=a.byteLength}),n.buffer}var pa=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function is(r){return pa?Buffer.byteLength(r):new Blob([r]).size}function Xa(r){var t=0;r.forEach(function(o){t+=o.byteLength});var e=new Uint8Array(t),n=0;return r.forEach(function(o){e.set(new Uint8Array(o),n),n+=o.byteLength}),e.buffer}function ss(r){for(r=r.trim();r.endsWith("/");)r=r.slice(0,r.length-1);var t=r.split("/");return t[t.length-1]}function vr(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:is(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:is(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}var st=function(){function r(){this.saveRouters=[],this.loadRouters=[]}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerSaveRouter=function(t){r.getInstance().saveRouters.push(t)},r.registerLoadRouter=function(t){r.getInstance().loadRouters.push(t)}
vendor: 21,183 bytes, lines 3814-3815
3814,r.getSaveHandlers=function(t){return r.getHandlers(t,"save")},r.getLoadHandlers=function(t,e){return r.getHandlers(t,"load",e)},r.getHandlers=function(t,e,n){var o=[];return(e==="load"?r.getInstance().loadRouters:r.getInstance().saveRouters).forEach(function(a){var i=a(t,n);i!==null&&o.push(i)}),o},r}(),Bn="://",en=function(){function r(){this.managers={}}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerManager=function(t,e){E(t!=null,function(){return"scheme must not be undefined or null."}),t.endsWith(Bn)&&(t=t.slice(0,t.indexOf(Bn))),E(t.length>0,function(){return"scheme must not be an empty string."});var n=r.getInstance();E(n.managers[t]==null,function(){return"A model store manager is already registered for scheme '"+t+"'."}),n.managers[t]=e},r.getManager=function(t){var e=this.getInstance().managers[t];if(e==null)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},r.getSchemes=function(){return Object.keys(this.getInstance().managers)},r}();function Nr(r){if(r.indexOf(Bn)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+en.getSchemes().join(","));return{scheme:r.split(Bn)[0],path:r.split(Bn)[1]}}function us(r,t,e){return e===void 0&&(e=!1),X(this,void 0,void 0,function(){var n,o,a,i,s,u,c,l,h;return $(this,function(f){switch(f.label){case 0:return E(r!==t,function(){return"Old path and new path are the same: '"+r+"'"}),E((n=st.getLoadHandlers(r)).length>0,function(){return"Copying failed because no load handler is found for source URL "+r+"."}),E(n.length<2,function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+r+"."}),o=n[0],E((a=st.getSaveHandlers(t)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+t+"."}),E(a.length<2,function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."}),i=a[0],s=Nr(r).scheme,u=Nr(r).path,c=s===Nr(r).scheme,[4,o.load()];case 1:return l=f.sent(),e&&c?[4,en.getManager(s).removeModel(u)]:[3,3];case 2:f.sent(),f.label=3;case 3:return[4,i.save(l)];case 4:return h=f.sent(),!e||c?[3,6]:[4,en.getManager(s).removeModel(u)];case 5:f.sent(),f.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var pn="models_store",Qt="model_info_store";function Ju(){if(!M().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var r=window||self,t=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function da(r){var t=r.result;t.createObjectStore(pn,{keyPath:"modelPath"}),t.createObjectStore(Qt,{keyPath:"modelPath"})}var Ln=function(){function r(t){if(this.indexedDB=Ju(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return r.prototype.save=function(t){return X(this,void 0,void 0,function(){return $(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)]})})},r.prototype.load=function(){return X(this,void 0,void 0,function(){return $(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},r.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(o,a){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return da(i)},i.onsuccess=function(){var s=i.result;if(e==null){var u=s.transaction(pn,"readonly"),c=u.objectStore(pn).get(n.modelPath);c.onsuccess=function(){if(c.result==null)return s.close(),a(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));o(c.result.modelArtifacts)},c.onerror=function(g){return s.close(),a(c.error)},u.oncomplete=function(){return s.close()}}else{var l,h=vr(e),f=s.transaction(Qt,"readwrite"),p=f.objectStore(Qt),d=p.put({modelPath:n.modelPath,modelArtifactsInfo:h});d.onsuccess=function(){var g=(l=s.transaction(pn,"readwrite")).objectStore(pn).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:h});g.onsuccess=function(){return o({modelArtifactsInfo:h})},g.onerror=function(v){var m=(p=f.objectStore(Qt)).delete(n.modelPath);m.onsuccess=function(){return s.close(),a(g.error)},m.onerror=function(x){return s.close(),a(g.error)}}},d.onerror=function(g){return s.close(),a(d.error)},f.oncomplete=function(){l==null?s.close():l.oncomplete=function(){return s.close()}}}},i.onerror=function(s){return a(i.error)}})},r.URL_SCHEME="indexeddb://",r}(),cs=function(r){return M().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Ln.URL_SCHEME)?(t=r.slice(Ln.URL_SCHEME.length),new Ln(t)):null;var t};st.registerSaveRouter(cs),st.registerLoadRouter(cs);var rm=function(){function r(){this.indexedDB=Ju()}return r.prototype.listModels=function(){return X(this,void 0,void 0,function(){var t=this;return $(this,function(e){return[2,new Promise(function(n,o){var a=t.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return da(a)},a.onsuccess=function(){var i=a.result,s=i.transaction(Qt,"readonly"),u=s.objectStore(Qt).getAll();u.onsuccess=function(){for(var c={},l=0,h=u.result;l<h.length;l++){var f=h[l];c[f.modelPath]=f.modelArtifactsInfo}n(c)},u.onerror=function(c){return i.close(),o(u.error)},s.oncomplete=function(){return i.close()}},a.onerror=function(i){return o(a.error)}})]})})},r.prototype.removeModel=function(t){return X(this,void 0,void 0,function(){var e=this;return $(this,function(n){var o;return t=(o=t).startsWith(Ln.URL_SCHEME)?o.slice(Ln.URL_SCHEME.length):o,[2,new Promise(function(a,i){var s=e.indexedDB.open("tensorflowjs",1);s.onupgradeneeded=function(){return da(s)},s.onsuccess=function(){var u,c=s.result,l=c.transaction(Qt,"readwrite"),h=l.objectStore(Qt),f=h.get(t);f.onsuccess=function(){if(f.result==null)return c.close(),i(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var p=h.delete(t),d=function(){var g=(u=c.transaction(pn,"readwrite")).objectStore(pn).delete(t);g.onsuccess=function(){return a(f.result.modelArtifactsInfo)},g.onerror=function(v){return i(f.error)}};p.onsuccess=d,p.onerror=function(g){return d(),c.close(),i(f.error)}},f.onerror=function(p){return c.close(),i(f.error)},l.oncomplete=function(){u==null?c.close():u.oncomplete=function(){return c.close()}}},s.onerror=function(u){return i(s.error)}})]})})},r}();if(M().getBool("IS_BROWSER"))try{en.registerManager(Ln.URL_SCHEME,new rm)}catch{}var Vt="/",Fn="tensorflowjs_models",Qu="info",om="model_topology",am="weight_specs",im="weight_data",sm="model_metadata";function Zu(r){return{info:[Fn,r,Qu].join(Vt),topology:[Fn,r,om].join(Vt),weightSpecs:[Fn,r,am].join(Vt),weightData:[Fn,r,im].join(Vt),modelMetadata:[Fn,r,sm].join(Vt)}}function um(r){var t=r.split(Vt);if(t.length<3)throw new Error("Invalid key format: "+r);return t.slice(1,t.length-1).join(Vt)}var Wn=function(){function r(t){if(!M().getBool("IS_BROWSER")||typeof window>"u"||window.localStorage===void 0)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=Zu(this.modelPath)}return r.prototype.save=function(t){return X(this,void 0,void 0,function(){var e,n,o;return $(this,function(a){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),o=vr(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(i){if(pa)return Buffer.from(i).toString("base64");for(var s=new Uint8Array(i),u="",c=0,l=s.length;c<l;c++)u+=String.fromCharCode(s[c]);return btoa(u)}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[2,{modelArtifactsInfo:o}]}catch{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="+o.modelTopologyBytes+", weightSpecsBytes="+o.weightSpecsBytes+", weightDataBytes="+o.weightDataBytes+".")}return[2]})})},r.prototype.load=function(){return X(this,void 0,void 0,function(){var t,e,n,o,a,i,s;return $(this,function(u){if((t=JSON.parse(this.LS.getItem(this.keys.info)))==null)throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if(t.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},(n=JSON.parse(this.LS.getItem(this.keys.topology)))==null)throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,(o=JSON.parse(this.LS.getItem(this.keys.weightSpecs)))==null)throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=o,(a=this.LS.getItem(this.keys.modelMetadata))!=null&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),(s=this.LS.getItem(this.keys.weightData))==null)throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(c){if(pa){var l=Buffer.from(c,"base64");return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}for(var h=atob(c),f=new Uint8Array(h.length),p=0;p<h.length;++p)f.set([h.charCodeAt(p)],p);return f.buffer}(s),[2,e]})})},r.URL_SCHEME="localstorage://",r}(),ls=function(r){return M().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Wn.URL_SCHEME)?(t=r.slice(Wn.URL_SCHEME.length),new Wn(t)):null;var t};st.registerSaveRouter(ls),st.registerLoadRouter(ls);var cm=function(){function r(){E(M().getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),E(typeof window>"u"||window.localStorage!==void 0,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return r.prototype.listModels=function(){return X(this,void 0,void 0,function(){var t,e,n,o,a,i;return $(this,function(s){for(t={},e=Fn+Vt,n=Vt+Qu,o=0;o<this.LS.length;++o)(a=this.LS.key(o)).startsWith(e)&&a.endsWith(n)&&(i=um(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]})})},r.prototype.removeModel=function(t){return X(this,void 0,void 0,function(){var e,n;return $(this,function(o){var a;if(t=(a=t).startsWith(Wn.URL_SCHEME)?a.slice(Wn.URL_SCHEME.length):a,e=Zu(t),this.LS.getItem(e.info)==null)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]})})},r}();if(M().getBool("IS_BROWSER"))try{en.registerManager(Wn.URL_SCHEME,new cm)}catch{}var lm="model",hm=".json",fm=".weights.bin";function hs(r){return new Promise(function(t){return setTimeout(t)}).then(r)}var qo=function(){function r(t){if(!M().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(r.URL_SCHEME)&&(t=t.slice(r.URL_SCHEME.length)),t!=null&&t.length!==0||(t=lm),this.modelTopologyFileName=t+hm,this.weightDataFileName=t+fm}return r.prototype.save=function(t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s;return $(this,function(u){switch(u.label){case 0:if(typeof document>"u")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}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),(i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,hs(function(){return i.dispatchEvent(new MouseEvent("click"))})];case 2:return u.sent(),t.weightData==null?[3,4]:((s=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,hs(function(){return s.dispatchEvent(new MouseEvent("click"))})]);case 3:u.sent(),u.label=4;case 4:return[2,{modelArtifactsInfo:vr(t)}]}})})},r.URL_SCHEME="downloads://",r}(),pm=function(){function r(t){if(t==null||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return r.prototype.load=function(){return X(this,void 0,void 0,function(){var t,e,n=this;return $(this,function(o){return t=this.files[0],e=this.files.slice(1),[2,new Promise(function(a,i){var s=new FileReader;s.onload=function(u){var c=JSON.parse(u.target.result),l=c.modelTopology;if(l!=null){e.length===0&&a({modelTopology:l});var h=c.weightsManifest;if(h!=null){var f;try{f=n.checkManifestAndWeightFiles(h,e)}catch(v){return void i(v)}var p=[],d=[],g=[];h.forEach(function(v){v.paths.forEach(function(m){d.push(m),g.push(null)}),p.push.apply(p,v.weights)}),h.forEach(function(v){v.paths.forEach(function(m){var x=new FileReader;x.onload=function(b){var y=b.target.result,w=d.indexOf(m);g[w]=y,g.indexOf(null)===-1&&a({modelTopology:l,weightSpecs:p,weightData:Xa(g),format:c.format,generatedBy:c.generatedBy,convertedBy:c.convertedBy,userDefinedMetadata:c.userDefinedMetadata})},x.onerror=function(b){return i("Failed to weights data from file of path '"+m+"'.")},x.readAsArrayBuffer(f[m])})})}else i(new Error("weightManifest field is missing from file "+t.name))}else i(new Error("modelTopology field is missing from file "+t.name))},s.onerror=function(u){return i("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},s.readAsText(t)})]})})},r.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],o=e.map(function(u){return ss(u.name)}),a={},i=0,s=t;i<s.length;i++)s[i].paths.forEach(function(u){var c=ss(u);if(n.indexOf(c)!==-1)throw new Error("Duplicate file basename found in weights manifest: '"+c+"'");if(n.push(c),o.indexOf(c)===-1)throw new Error("Weight file with basename '"+c+"' is not provided.");a[u]=e[o.indexOf(c)]});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 a},r}();function fs(r,t,e,n){(function(a){E(a!=null&&Array.isArray(a)&&a.length>0,function(){return"promises must be a none empty array"})})(r),function(a,i){E(a>=0&&a<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+a}),E(i>=0&&i<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+i}),E(i>=a,function(){return"startFraction must be no more than endFraction, but got startFraction "+a+" and endFraction "+i})}(e=e??0,n=n??1);var o=0;return Promise.all(r.map(function(a){return a.then(function(i){var s=e+ ++o/r.length*(n-e);return t(s),i}),a}))}function ec(r,t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s,u,c,l;return $(this,function(h){switch(h.label){case 0:return t==null&&(t={}),e=t.fetchFunc==null?M().platform.fetch:t.fetchFunc,n=r.map(function(f){return e(f,t.requestInit,{isBinary:!0})}),o=0,a=.5,t.onProgress!=null?[3,2]:[4,Promise.all(n)];case 1:return i=h.sent(),[3,4];case 2:return[4,fs(n,t.onProgress,o,a)];case 3:i=h.sent(),h.label=4;case 4:return s=i.map(function(f){return f.arrayBuffer()}),u=.5,c=1,t.onProgress!=null?[3,6]:[4,Promise.all(s)];case 5:return l=h.sent(),[3,8];case 6:return[4,fs(s,t.onProgress,u,c)];case 7:l=h.sent(),h.label=8;case 8:return[2,l]}})})}function ps(r){var t=this;return function(e,n,o){return n===void 0&&(n=""),X(t,void 0,void 0,function(){var a,i,s,u,c,l,h,f,p,d;return $(this,function(g){switch(g.label){case 0:if(a=e.map(function(){return!1}),i={},s=o!=null?o.map(function(){return!1}):[],u=[],e.forEach(function(v,m){var x=0;v.weights.forEach(function(b){var y="quantization"in b?b.quantization.dtype:b.dtype,w=fa[y]*Y(b.shape),C=function(){a[m]=!0,i[m]==null&&(i[m]=[]),i[m].push({manifestEntry:b,groupOffset:x,sizeBytes:w})};o!=null?o.forEach(function(S,k){S===b.name&&(C(),s[k]=!0)}):C(),u.push(b.name),x+=w})}),!s.every(function(v){return v}))throw c=o.filter(function(v,m){return!s[m]}),new Error("Could not find weights in manifest with names: "+c.join(", ")+`. 
3815Manifest JSON has weights with names: `+u.join(", ")+".");return l=a.reduce(function(v,m,x){return m&&v.push(x),v},[]),h=[],l.forEach(function(v){e[v].paths.forEach(function(m){var x=n+(n.endsWith("/")?"":"/")+m;h.push(x)})}),[4,r(h)];case 1:return f=g.sent(),p={},d=0,l.forEach(function(v){for(var m=e[v].paths.length,x=0,b=0;b<m;b++)x+=f[d+b].byteLength;for(var y=new ArrayBuffer(x),w=new Uint8Array(y),C=0,S=0;S<m;S++){var k=new Uint8Array(f[d+S]);w.set(k,C),C+=k.byteLength}i[v].forEach(function(I){var R=Yu(y.slice(I.groupOffset,I.groupOffset+I.sizeBytes),[I.manifestEntry]);for(var N in R)p[N]=R[N]}),d+=m}),[2,p]}})})}}st.registerSaveRouter(function(r){return M().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(qo.URL_SCHEME)?function(t){return t===void 0&&(t="model"),new qo(t)}(r.slice(qo.URL_SCHEME.length)):null});var tc=function(){function r(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,e.fetchFunc!=null?(E(typeof e.fetchFunc=="function",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=M().platform.fetch,E(t!=null&&t.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&E(t.length===2,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return r.prototype.save=function(t){return X(this,void 0,void 0,function(){var e,n,o,a;return $(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}],o={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(o)],{type:"application/json"}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:vr(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},r.prototype.load=function(){return X(this,void 0,void 0,function(){var t,e,n,o,a,i,s,u,c,l,h,f;return $(this,function(p){switch(p.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=p.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.");p.label=2;case 2:return p.trys.push([2,4,,5]),[4,t.json()];case 3:return e=p.sent(),[3,5];case 4:throw p.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(o=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,o==null&&a==null)throw new Error("The JSON from HTTP path "+this.path+" contains 
3815neither model topology or manifest for weights.");return a==null?[3,7]:[4,this.loadWeights(a)];case 6:f=p.sent(),l=f[0],h=f[1],p.label=7;case 7:return[2,{modelTopology:o,weightSpecs:l,weightData:h,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}})})},r.prototype.loadWeights=function(t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s,u,c,l,h,f;return $(this,function(p){switch(p.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(d){var g=d.lastIndexOf("/"),v=d.lastIndexOf("?"),m=d.substring(0,g),x=v>g?d.substring(v):"";return[m+"/",x]}(e),o=n[0],a=n[1],i=this.weightPathPrefix||o,s=[],u=0,c=t;u<c.length;u++)l=c[u],s.push.apply(s,l.weights);return h=[],t.forEach(function(d){d.paths.forEach(function(g){h.push(i+g+a)})}),[4,ec(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=p.sent(),[2,[s,Xa(f)]]}})})},r.URL_SCHEME_REGEX=/^https?:\/\//,r}();function va(r){return r.match(tc.URL_SCHEME_REGEX)!=null}var ds=function(r,t){return typeof fetch>"u"?null:(Array.isArray(r)?r.every(function(e){return va(e)}):va(r))?ma(r,{onProgress:t}):null};function ma(r,t){return new tc(r,t)}st.registerSaveRouter(ds),st.registerLoadRouter(ds);var jo=function(){function r(t){this.modelArtifacts=t}return r.prototype.load=function(){return X(this,void 0,void 0,function(){return $(this,function(t){return[2,this.modelArtifacts]})})},r}(),dm=function(){function r(t){this.saveHandler=t}return r.prototype.save=function(t){return X(this,void 0,void 0,function(){return $(this,function(e){return[2,this.saveHandler(t)]})})},r}(),nc=Object.freeze({browserFiles:function(r){return new pm(r)},browserHTTPRequest:function(r,t){return ma(r,t)},concatenateArrayBuffers:Xa,decodeWeights:Yu,encodeWeights:function(r,t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s=this;return $(this,function(u){switch(u.label){case 0:for(e=[],n=[],o=Array.isArray(r)?r.map(function(c){return c.name}):Object.keys(r),a=function(c){var l=o[c],h=Array.isArray(r)?r[c].tensor:r[l];if(h.dtype!=="float32"&&h.dtype!=="int32"&&h.dtype!=="bool"&&h.dtype!=="string")throw new Error("Unsupported dtype in weight '"+l+"': "+h.dtype);var f={name:l,shape:h.shape,dtype:h.dtype};if(h.dtype==="string"){var p=new Promise(function(d){return X(s,void 0,void 0,function(){var g,v,m,x,b,y,w;return $(this,function(C){switch(C.label){case 0:return[4,h.bytes()];case 1:for(g=C.sent(),v=g.reduce(function(S,k){return S+k.length},0)+Jr*g.length,m=new Uint8Array(v),x=0,b=0;b<g.length;b++)y=g[b],w=new Uint8Array(new Uint32Array([y.length]).buffer),m.set(w,x),x+=Jr,m.set(y,x),x+=y.length;return d(m),[2]}})})});n.push(p)}else n.push(h.data());t!=null&&(f.group=t),e.push(f)},i=0;i<o.length;++i)a(i);return[4,Promise.all(n)];case 1:return[2,{data:nm(u.sent()),specs:e}]}})})},fromMemory:function(r,t,e,n){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new jo(r):(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 jo({modelTopology:r})):(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 jo({modelTopology:r,weightSpecs:t,weightData:e,trainingConfig:n}))},getLoadHandlers:function(r,t){return st.getLoadHandlers(r,t)},getModelArtifactsInfoForJSON:vr,getSaveHandlers:function(r){return st.getSaveHandlers(r)},http:ma,isHTTPScheme:va,loadWeights:function(r,t,e,n){return t===void 0&&(t=""),X(this,void 0,void 0,function(){return $(this,function(o){return[2,ps(function(a){return ec(a,{requestInit:n})})(r,t,e)]})})},registerLoadRouter:function(r){return st.registerLoadRouter(r)},registerSaveRouter:function(r){return st.registerSaveRouter(r)},weightsLoaderFactory:ps,withSaveHandler:function(r){return new dm(r)},copyModel:function(r,t){return X(this,void 0,void 0,function(){return $(this,function(e){return[2,us(r,t,!1)]})})},listModels:function(){return X(this,void 0,void 0,function(){var r,t,e,n,o,a,i;return $(this,function(s){switch(s.label){case 0:r=en.getSchemes(),t={},e=0,n=r,s.label=1;case 1:return e<n.length?(o=n[e],[4,en.getManager(o).listModels()]):[3,4];case 2:for(i in a=s.sent())t[o+Bn+i]=a[i];s.label=3;case 3:return e++,[3,1];case 4:return[2,t]}})})},moveModel:function(r,t){return X(this,void 0,void 0,function(){return $(this,function(e){return[2,us(r,t,!0)]})})},removeModel:function(r){return X(this,void 0,void 0,function(){var t;return $(this,function(e){return t=Nr(r),[2,en.getManager(t.scheme).removeModel(t.path)]})})}}),Sn;D({confusionMatrix_:function(r,t,e){var n=_(r,"labels","confusionMatrix"),o=_(t,"predictions","confusionMatrix");
vendor: 129,847 bytes, lines 3815-3828
3815E(e==null||e>0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, but got "+e}),E(n.rank===1,function(){return"Expected the rank of labels to be 1, but got "+n.rank}),E(o.rank===1,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),E(n.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+n.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),E(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+e});var a=sa(n.asType("int32"),e),i=sa(o.asType("int32"),e);return a.transpose().matMul(i).asType("int32")}});var vm=D({fromPixels_:function(r,t){if(t===void 0&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,n=!1,o=!1,a=!1,i=!1;if(r.data instanceof Uint8Array)e=!0;else if(typeof ImageData<"u"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)a=!0;else{if(r.getContext==null)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 "+r.constructor.name);i=!0}if(o&&o&&r.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(Rs("FromPixels",T.backendName)!=null)return T.runKernel("FromPixels",{pixels:r},{numChannels:t});var s,u,c=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],l=c[0],h=c[1];if(i?s=r.getContext("2d").getImageData(0,0,l,h).data:n||e?s=r.data:(a||o)&&(Sn==null&&(Sn=document.createElement("canvas").getContext("2d")),Sn.canvas.width=l,Sn.canvas.height=h,Sn.drawImage(r,0,0,l,h),s=Sn.getImageData(0,0,l,h).data),t===4)u=new Int32Array(s);else{var f=l*h;u=new Int32Array(f*t);for(var p=0;p<f;p++)for(var d=0;d<t;++d)u[p*t+d]=s[4*p+d]}return _a(u,[h,l,t],"int32")}}),$a=Object.freeze({toPixels:function(r,t){return X(this,void 0,void 0,function(){var e,n,o,a,i,s,u,c,l,h,f,p,d,g,v,m,x,b,y,w,C,S,k;return $(this,function(I){switch(I.label){case 0:if(e=_(r,"img","toPixels"),r instanceof Ee||(e=e.toInt()),e.rank!==2&&e.rank!==3)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+e.rank+".");if(n=e.shape.slice(0,2),o=n[0],a=n[1],(i=e.rank===2?1:e.shape[2])>4||i===2)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return[4,e.data()];case 1:return s=I.sent(),u=e.min(),c=e.max(),[4,Promise.all([u.data(),c.data()])];case 2:if(l=I.sent(),h=l[0],f=l[1],p=h[0],d=f[0],u.dispose(),c.dispose(),e.dtype==="float32"){if(p<0||d>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+p+" - "+d+"].")}else{if(e.dtype!=="int32")throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");if(p<0||d>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+p+" - "+d+"].")}for(g=e.dtype==="float32"?255:1,v=new Uint8ClampedArray(a*o*4),m=0;m<o*a;++m)x=void 0,b=void 0,y=void 0,w=void 0,i===1?(x=s[m]*g,b=s[m]*g,y=s[m]*g,w=255):i===3?(x=s[3*m]*g,b=s[3*m+1]*g,y=s[3*m+2]*g,w=255):i===4&&(x=s[4*m]*g,b=s[4*m+1]*g,y=s[4*m+2]*g,w=s[4*m+3]*g),v[(C=4*m)+0]=Math.round(x),v[C+1]=Math.round(b),v[C+2]=Math.round(y),v[C+3]=Math.round(w);return t!=null&&(t.width=a,t.height=o,S=t.getContext("2d"),k=new ImageData(v,a,o),S.putImageData(k,0,0)),e!==r&&e.dispose(),[2,v]}})})},fromPixels:vm}),mm=function(){function r(){}return r.prototype.getClassName=function(){return this.constructor.className},r.fromConfig=function(t,e){return new t(e)},r}(),gm=function(){function r(){this.classNameMap={}}return r.getMap=function(){return r.instance==null&&(r.instance=new r),r.instance},r.register=function(t){r.getMap().classNameMap[t.className]=[t,t.fromConfig]},r}();function wn(r){E(r.className!=null,function(){return"Class being registered does not have the static className property defined."}),E(typeof r.className=="string",function(){return"className is required to be a string, but got type "+typeof r.className}),E(r.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),gm.register(r)}var Cn=function(r){function t(){return r!==null&&r.apply(this,arguments)||this}return gt(t,r),t.prototype.minimize=function(e,n,o){n===void 0&&(n=!1);var a=this.computeGradients(e,o),i=a.value,s=a.grads;if(o!=null){var u=o.map(function(c){return{name:c.name,tensor:s[c.name]}});this.applyGradients(u)}else this.applyGradients(s);return Ze(s),n?i:(i.dispose(),null)},Object.defineProperty(t.prototype,"iterations",{get:function(){return this.iterations_==null&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,n){return Rh(e,n)},t.prototype.dispose=function(){this.iterations_!=null&&Ze(this.iterations_)},t.prototype.saveIterations=function(){return X(this,void 0,void 0,function(){return $(this,function(e){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:q(this.iterations_,"int32")}]})})},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){return $(this,function(e){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},t.prototype.extractIterations=function(e){return X(this,void 0,void 0,function(){var n;return $(this,function(o){switch(o.label){case 0:return n=this,[4,e[0].tensor.data()];case 1:return n.iterations_=o.sent()[0],[2,e.slice(1)]}})})},t}(mm);Object.defineProperty(Cn,Symbol.hasInstance,{value:function(r){return r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null}});var ym=function(r){function t(e,n,o){o===void 0&&(o=null);var a=r.call(this)||this;return a.learningRate=e,a.rho=n,a.epsilon=o,a.accumulatedGrads=[],a.accumulatedUpdates=[],o==null&&(a.epsilon=T.backend.epsilon()),a}return gt(t,r),t.prototype.applyGradients=function(e){var n=this;(Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e)).forEach(function(o,a){var i=T.registeredVariables[o];n.accumulatedGrads[a]==null&&(n.accumulatedGrads[a]={originalName:o+"/accum_grad",variable:K(function(){return ve(i).variable(!1)})}),n.accumulatedUpdates[a]==null&&(n.accumulatedUpdates[a]={originalName:o+"/accum_var",variable:K(function(){return ve(i).variable(!1)})});var s=Array.isArray(e)?e[a].tensor:e[o];if(s!=null){var u=n.accumulatedGrads[a].variable,c=n.accumulatedUpdates[a].variable;K(function(){var l=u.mul(n.rho).add(s.square().mul(1-n.rho)),h=c.add(n.epsilon).sqrt().div(u.add(n.epsilon).sqrt()).mul(s),f=c.mul(n.rho).add(h.square().mul(1-n.rho));u.assign(l),c.assign(f);var p=h.mul(-n.learningRate).add(i);i.assign(p)})}}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Ze(this.accumulatedGrads.map(function(e){return e.variable})),Ze(this.accumulatedUpdates.map(function(e){return e.variable})))},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[n.sent()].concat(e.map(function(o){return{name:o.originalName,tensor:o.variable}}))]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){var n;return $(this,function(o){switch(o.label){case 0:return[4,this.extractIterations(e)];case 1:return e=o.sent(),n=e.length/2,this.accumulatedGrads=e.slice(0,n).map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),this.accumulatedUpdates=e.slice(n,2*n).map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,n){return new e(n.learningRate,n.rho,n.epsilon)},t.className="Adadelta",t}(Cn);wn(ym);var xm=function(r){function t(e,n){n===void 0&&(n=.1);var o=r.call(this)||this;return o.learningRate=e,o.initialAccumulatorValue=n,o.accumulatedGrads=[],o}return gt(t,r),t.prototype.applyGradients=function(e){var n=this;(Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e)).forEach(function(o,a){var i=T.registeredVariables[o];n.accumulatedGrads[a]==null&&(n.accumulatedGrads[a]={originalName:o+"/accumulator",variable:K(function(){return At(i.shape,n.initialAccumulatorValue).variable(!1)})});var s=Array.isArray(e)?e[a].tensor:e[o];if(s!=null){var u=n.accumulatedGrads[a].variable;K(function(){var c=u.add(s.square());u.assign(c);var l=s.div(c.add(T.backend.epsilon()).sqrt()).mul(-n.learningRate).add(i);i.assign(l)})}}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedGrads!=null&&Ze(this.accumulatedGrads.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){return $(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map(function(n){return{name:n.originalName,tensor:n.variable}}))]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),this.accumulatedGrads=e.map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,n){return new e(n.learningRate,n.initialAccumulatorValue)},t.className="Adagrad",t}(Cn);wn(xm);var bm=function(r){function t(e,n,o,a){a===void 0&&(a=null);var i=r.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=o,i.epsilon=a,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],K(function(){i.accBeta1=q(n).variable(),i.accBeta2=q(o).variable()}),a==null&&(i.epsilon=T.backend.epsilon()),i}return gt(t,r),t.prototype.applyGradients=function(e){var n=this,o=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);K(function(){var a=Oe(1,n.accBeta1),i=Oe(1,n.accBeta2);o.forEach(function(s,u){var c=T.registeredVariables[s];n.accumulatedFirstMoment[u]==null&&(n.accumulatedFirstMoment[u]={originalName:s+"/m",variable:K(function(){return ve(c).variable(!1)})}),n.accumulatedSecondMoment[u]==null&&(n.accumulatedSecondMoment[u]={originalName:s+"/v",variable:K(function(){return ve(c).variable(!1)})});var l=Array.isArray(e)?e[u].tensor:e[s];if(l!=null){var h=n.accumulatedFirstMoment[u].variable,f=n.accumulatedSecondMoment[u].variable,p=h.mul(n.beta1).add(l.mul(1-n.beta1)),d=f.mul(n.beta2).add(l.square().mul(1-n.beta2)),g=p.div(a),v=d.div(i);h.assign(p),f.assign(d);var m=g.div(v.sqrt().add(n.epsilon)).mul(-n.learningRate).add(c);c.assign(m)}}),n.accBeta1.assign(n.accBeta1.mul(n.beta1)),n.accBeta2.assign(n.accBeta2.mul(n.beta2))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ze(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedSecondMoment!=null&&Ze(this.accumulatedSecondMoment.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[n.sent()].concat(e.map(function(o){return{name:o.originalName,tensor:o.variable}}))]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){var n,o=this;return $(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),K(function(){o.accBeta1.assign($r(o.beta1,o.iterations_+1)),o.accBeta2.assign($r(o.beta2,o.iterations_+1))}),n=e.length/2,this.accumulatedFirstMoment=e.slice(0,n).map(function(i){return{originalName:i.name,variable:i.tensor.variable(!1)}}),this.accumulatedSecondMoment=e.slice(n,2*n).map(function(i){return{originalName:i.name,variable:i.tensor.variable(!1)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,n){return new e(n.learningRate,n.beta1,n.beta2,n.epsilon)},t.className="Adam",t}(Cn);wn(bm);var wm=function(r){function t(e,n,o,a,i){a===void 0&&(a=null),i===void 0&&(i=0);var s=r.call(this)||this;return s.learningRate=e,s.beta1=n,s.beta2=o,s.epsilon=a,s.decay=i,s.accumulatedFirstMoment=[],s.accumulatedWeightedInfNorm=[],K(function(){s.iteration=q(0).variable(),s.accBeta1=q(n).variable()}),a==null&&(s.epsilon=T.backend.epsilon()),s}return gt(t,r),t.prototype.applyGradients=function(e){var n=this,o=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);K(function(){var a=Oe(1,n.accBeta1),i=dt(-n.learningRate,n.iteration.mul(n.decay).add(1));o.forEach(function(s,u){var c=T.registeredVariables[s];n.accumulatedFirstMoment[u]==null&&(n.accumulatedFirstMoment[u]={originalName:s+"/m",variable:ve(c).variable(!1)}),n.accumulatedWeightedInfNorm[u]==null&&(n.accumulatedWeightedInfNorm[u]={originalName:s+"/v",variable:ve(c).variable(!1)});var l=Array.isArray(e)?e[u].tensor:e[s];if(l!=null){var h=n.accumulatedFirstMoment[u].variable,f=n.accumulatedWeightedInfNorm[u].variable,p=h.mul(n.beta1).add(l.mul(1-n.beta1)),d=f.mul(n.beta2),g=l.abs(),v=d.maximum(g);h.assign(p),f.assign(v);var m=i.div(a).mul(p.div(v.add(n.epsilon))).add(c);c.assign(m)}}),n.iteration.assign(n.iteration.add(1)),n.accBeta1.assign(n.accBeta1.mul(n.beta1))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ze(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedWeightedInfNorm!=null&&Ze(this.accumulatedWeightedInfNorm.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){return $(this,function(e){throw new Error("getWeights() is not implemented for Adamax yet.")})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){throw new Error("setWeights() is not implemented for Adamax yet.")})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,n){return new e(n.learningRate,n.beta1,n.beta2,n.epsilon,n.decay)},t.className="Adamax",t}(Cn);wn(wm);var rc=function(r){function t(e){var n=r.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return gt(t,r),t.prototype.applyGradients=function(e){var n=this;(Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e)).forEach(function(o,a){var i=Array.isArray(e)?e[a].tensor:e[o];if(i!=null){var s=T.registeredVariables[o];K(function(){var u=n.c.mul(i).add(s);s.assign(u)})}}),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Ul(q(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){return $(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:if((e=n.sent()).length!==0)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,n){return new e(n.learningRate)},t.className="SGD",t}(Cn);wn(rc);var Cm=function(r){function t(e,n,o){o===void 0&&(o=!1);var a=r.call(this,e)||this;return a.learningRate=e,a.momentum=n,a.useNesterov=o,a.accumulations=[],a.m=q(a.momentum),a}return gt(t,r),t.prototype.applyGradients=function(e){var n=this;(Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e)).forEach(function(o,a){var i=T.registeredVariables[o];n.accumulations[a]==null&&(n.accumulations[a]={originalName:o+"/momentum",variable:K(function(){return ve(i).variable(!1)})});var s=n.accumulations[a].variable,u=Array.isArray(e)?e[a].tensor:e[o];u!=null&&K(function(){var c,l=n.m.mul(s).add(u);c=n.useNesterov?n.c.mul(u.add(l.mul(n.m))).add(i):n.c.mul(l).add(i),s.assign(l),i.assign(c)})}),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&Ze(this.accumulations.map(function(e){return e.variable}))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){return $(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map(function(n){return{name:n.originalName,tensor:n.variable}}))]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){return $(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),this.accumulations=e.map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,n){return new e(n.learningRate,n.momentum,n.useNesterov)},t.className="Momentum",t}(rc);wn(Cm);var _m=function(r){function t(e,n,o,a,i){n===void 0&&(n=.9),o===void 0&&(o=0),a===void 0&&(a=null),i===void 0&&(i=!1);var s=r.call(this)||this;if(s.learningRate=e,s.decay=n,s.momentum=o,s.epsilon=a,s.accumulatedMeanSquares=[],s.accumulatedMoments=[],s.accumulatedMeanGrads=[],s.centered=i,a==null&&(s.epsilon=T.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.");return s}return gt(t,r),t.prototype.applyGradients=function(e){var n=this;(Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e)).forEach(function(o,a){var i=T.registeredVariables[o];n.accumulatedMeanSquares[a]==null&&(n.accumulatedMeanSquares[a]={originalName:o+"/rms",variable:K(function(){return ve(i).variable(!1)})}),n.accumulatedMoments[a]==null&&(n.accumulatedMoments[a]={originalName:o+"/momentum",variable:K(function(){return ve(i).variable(!1)})}),n.accumulatedMeanGrads[a]==null&&n.centered&&(n.accumulatedMeanGrads[a]={originalName:o+"/mg",variable:K(function(){return ve(i).variable(!1)})});var s=Array.isArray(e)?e[a].tensor:e[o];if(s!=null){var u=n.accumulatedMeanSquares[a].variable,c=n.accumulatedMoments[a].variable;K(function(){var l=u.mul(n.decay).add(s.square().mul(1-n.decay));if(n.centered){var h=n.accumulatedMeanGrads[a].variable,f=h.mul(n.decay).add(s.mul(1-n.decay)),p=c.mul(n.momentum).add(s.mul(n.learningRate).div(l.sub(f.square().add(n.epsilon)).sqrt()));u.assign(l),h.assign(f),c.assign(p);var d=i.sub(p);i.assign(d)}else{var g=u.mul(n.decay).add(s.square().mul(1-n.decay));p=c.mul(n.momentum).add(s.mul(n.learningRate).div(g.add(n.epsilon).sqrt())),u.assign(g),c.assign(p),d=i.sub(p),i.assign(d)}})}}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Ze(this.accumulatedMeanSquares.map(function(e){return e.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Ze(this.accumulatedMeanGrads.map(function(e){return e.variable})),this.accumulatedMoments!=null&&Ze(this.accumulatedMoments.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return X(this,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[n.sent()].concat(e.map(function(o){return{name:o.originalName,tensor:o.variable}}))]}})})},t.prototype.setWeights=function(e){return X(this,void 0,void 0,function(){var n;return $(this,function(o){switch(o.label){case 0:return[4,this.extractIterations(e)];case 1:return e=o.sent(),n=this.centered?e.length/3:e.length/2,this.accumulatedMeanSquares=e.slice(0,n).map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),this.accumulatedMoments=e.slice(n,2*n).map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=e.slice(2*n,3*n).map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}})),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,n){return new e(n.learningRate,n.decay,n.momentum,n.epsilon,n.centered)},t.className="RMSProp",t}(Cn);wn(_m);Ee.prototype.squaredDifference=function(r){return yu(this,r)},P=$v;/*! *****************************************************************************
3816Copyright (c) Microsoft Corporation.
3817
3818Permission to use, copy, modify, and/or distribute this software for any
3819purpose with or without fee is hereby granted.
3820
3821THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
3822REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
3823AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
3824INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
3825LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3826OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3827PERFORMANCE OF THIS SOFTWARE.
3828***************************************************************************** */var ga=function(r,t){return ga=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var o in n)n.hasOwnProperty(o)&&(e[o]=n[o])},ga(r,t)};function re(r,t){ga(r,t);function e(){this.constructor=r}r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}var qe=function(){return qe=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a])}return t},qe.apply(this,arguments)};function Q(r,t,e,n){function o(a){return a instanceof e?a:new e(function(i){i(a)})}return new(e||(e=Promise))(function(a,i){function s(l){try{c(n.next(l))}catch(h){i(h)}}function u(l){try{c(n.throw(l))}catch(h){i(h)}}function c(l){l.done?a(l.value):o(l.value).then(s,u)}c((n=n.apply(r,[])).next())})}function Z(r,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,o,a,i;return i={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(c){return function(l){return u([c,l])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;e;)try{if(n=1,o&&(a=c[0]&2?o.return:c[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,c[1])).done)return a;switch(o=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return e.label++,{value:c[1],done:!1};case 5:e.label++,o=c[1],c=[0];continue;case 7:c=e.ops.pop(),e.trys.pop();continue;default:if(a=e.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){e=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){e.label=c[1];break}if(c[0]===6&&e.label<a[1]){e.label=a[1],a=c;break}if(a&&e.label<a[2]){e.label=a[2],e.ops.push(c);break}a[2]&&e.ops.pop(),e.trys.pop();continue}c=t.call(r,e)}catch(l){c=[6,l],o=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function er(){for(var r=0,t=0,e=arguments.length;t<e;t++)r+=arguments[t].length;for(var n=Array(r),o=0,t=0;t<e;t++)for(var a=arguments[t],i=0,s=a.length;i<s;i++,o++)n[o]=a[i];return n}var Un=function(){function r(t,e){if(!dn(t)||!dn(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(r.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),r.prototype.reverse=function(){return new r(1/this.width,1/this.height)},r}();function ho(r,t){return r instanceof Ee&&r.shape.length===t}function Em(r){return ho(r,2)}function fo(r){return ho(r,3)}function tn(r){return ho(r,4)}function Im(r){return r%1!==0}function vs(r){return r%2===0}function Rm(r,t){t===void 0&&(t=2);var e=Math.pow(10,t);return Math.floor(r*e)/e}function ms(r){return r&&r.width&&r.height}function km(r,t){var e=r.width,n=r.height,o=t/Math.max(n,e);return new Un(Math.round(e*o),Math.round(n*o))}function Ya(r){return r.reduce(function(t,e){return t.add(e)},new ge(0,0)).div(new ge(r.length,r.length))}function ir(r,t,e){return Array(r).fill(0).map(function(n,o){return t+o*e})}function dn(r){return!!r&&r!==1/0&&r!==-1/0&&!isNaN(r)||r===0}function gs(r){return dn(r)&&0<=r&&r<=1}var ge=function(){function r(t,e){this._x=t,this._y=e}return Object.defineProperty(r.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.sub=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.mul=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.div=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.abs=function(){return new r(Math.abs(this.x),Math.abs(this.y))},r.prototype.magnitude=function(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))},r.prototype.floor=function(){return new r(Math.floor(this.x),Math.floor(this.y))},r}(),rn=function(){function r(t,e){e===void 0&&(e=!0);var n=t||{},o=[n.left,n.top,n.right,n.bottom].every(dn),a=[n.x,n.y,n.width,n.height].every(dn);if(!a&&!o)throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have "+JSON.stringify(n));var i=a?[n.x,n.y,n.width,n.height]:[n.left,n.top,n.right-n.left,n.bottom-n.top],s=i[0],u=i[1],c=i[2],l=i[3];r.assertIsValidBox({x:s,y:u,width:c,height:l},"Box.constructor",e),this._x=s,this._y=u,this._width=c,this._height=l}return r.isRect=function(t){return!!t&&[t.x,t.y,t.width,t.height].every(dn)},r.assertIsValidBox=function(t,e,n){if(n===void 0&&(n=!1),!r.isRect(t))throw new Error(e+" - invalid box: "+JSON.stringify(t)+", expected object with properties x, y, width, height");if(!n&&(t.width<0||t.height<0))throw new Error(e+" - width ("+t.width+") and height ("+t.height+") must be positive numbers")},Object.defineProperty(r.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"left",{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"top",{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"right",{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bottom",{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"area",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"topLeft",{get:function(){return new ge(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"topRight",{get:function(){return new ge(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bottomLeft",{get:function(){return new ge(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bottomRight",{get:function(){return new ge(this.right,this.bottom)},enumerable:!0,configurable:!0}),r.prototype.round=function(){var t=[this.x,this.y,this.width,this.height].map(function(i){return Math.round(i)}),e=t[0],n=t[1],o=t[2],a=t[3];return new r({x:e,y:n,width:o,height:a})},r.prototype.floor=function(){var t=[this.x,this.y,this.width,this.height].map(function(i){return Math.floor(i)}),e=t[0],n=t[1],o=t[2],a=t[3];return new r({x:e,y:n,width:o,height:a})},r.prototype.toSquare=function(){var t=this,e=t.x,n=t.y,o=t.width,a=t.height,i=Math.abs(o-a);return o<a&&(e-=i/2,o+=i),a<o&&(n-=i/2,a+=i),new r({x:e,y:n,width:o,height:a})},r.prototype.rescale=function(t){var e=ms(t)?t.width:t,n=ms(t)?t.height:t;return new r({x:this.x*e,y:this.y*n,width:this.width*e,height:this.height*n})},r.prototype.pad=function(t,e){var n=[this.x-t/2,this.y-e/2,this.width+t,this.height+e],o=n[0],a=n[1],i=n[2],s=n[3];return new r({x:o,y:a,width:i,height:s})},r.prototype.clipAtImageBorders=function(t,e){var n=this,o=n.x,a=n.y,i=n.right,s=n.bottom,u=Math.max(o,0),c=Math.max(a,0),l=i-u,h=s-c,f=Math.min(l,t-u),p=Math.min(h,e-c);return new r({x:u,y:c,width:f,height:p}).floor()},r.prototype.shift=function(t,e){var n=this,o=n.width,a=n.height,i=this.x+t,s=this.y+e;return new r({x:i,y:s,width:o,height:a})},r.prototype.padAtBorders=function(t,e){var n=this.width+1,o=this.height+1,a=1,i=1,s=n,u=o,c=this.left,l=this.top,h=this.right,f=this.bottom;return h>e&&(s=-h+e+n,h=e),f>t&&(u=-f+t+o,f=t),c<1&&(u=2-c,c=1),l<1&&(u=2-l,l=1),{dy:i,edy:u,dx:a,edx:s,y:l,ey:f,x:c,ex:h,w:n,h:o}},r.prototype.calibrate=function(t){return new r({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()},r}(),po=function(r){re(t,r);function t(e,n,o,a,i){return i===void 0&&(i=!1),r.call(this,{left:e,top:n,right:o,bottom:a},i)||this}return t}(rn),oc=function(){function r(t,e,n,o,a){this._imageDims=new Un(a.width,a.height),this._score=t,this._classScore=e,this._className=n,this._box=new rn(o).rescale(this._imageDims)}return Object.defineProperty(r.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"box",{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"imageDims",{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"imageWidth",{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"imageHeight",{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"relativeBox",{get:function(){return new rn(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),r.prototype.forSize=function(t,e){return new r(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:e})},r}(),Mt=function(r){re(t,r);function t(e,n,o){return r.call(this,e,e,"",n,o)||this}return t.prototype.forSize=function(e,n){var o=r.prototype.forSize.call(this,e,n),a=o.score,i=o.relativeBox,s=o.imageDims;return new t(a,i,s)},t}(oc);function Sm(r,t,e){e===void 0&&(e=!0);var n=Math.max(0,Math.min(r.right,t.right)-Math.max(r.left,t.left)),o=Math.max(0,Math.min(r.bottom,t.bottom)-Math.max(r.top,t.top)),a=n*o;return e?a/(r.area+t.area-a):a/Math.min(r.area,t.area)}function Dm(r){var t=r.map(function(s){return s.x}),e=r.map(function(s){return s.y}),n=t.reduce(function(s,u){return u<s?u:s},1/0),o=e.reduce(function(s,u){return u<s?u:s},1/0),a=t.reduce(function(s,u){return s<u?u:s},0),i=e.reduce(function(s,u){return s<u?u:s},0);return new po(n,o,a,i)}function sr(r,t,e,n){n===void 0&&(n=!0);for(var o=t.map(function(s,u){return{score:s,boxIndex:u}}).sort(function(s,u){return s.score-u.score}).map(function(s){return s.boxIndex}),a=[],i=function(){var s=o.pop();a.push(s);for(var u=o,c=[],l=0;l<u.length;l++){var h=u[l],f=r[s],p=r[h];c.push(Sm(f,p,n))}o=o.filter(function(d,g){return c[g]<=e})};o.length>0;)i();return a}function mr(r,t){return K(function(){var e=t[0],n=t[1],o=t[2],a=At(er(r.shape.slice(0,3),[1]),e),i=At(er(r.shape.slice(0,3),[1]),n),s=At(er(r.shape.slice(0,3),[1]),o),u=Fe([a,i,s],3);return Oe(r,u)})}function Am(r,t){return t===void 0&&(t=!1),K(function(){var e=r.shape.slice(1),n=e[0],o=e[1];if(n===o)return r;var a=Math.abs(n-o),i=Math.round(a*(t?.5:1)),s=n>o?2:1,u=function(p){var d=r.shape.slice();return d[s]=p,At(d,0)},c=u(i),l=a-c.shape[s],h=t&&l?u(l):null,f=[h,r,c].filter(function(p){return!!p}).map(function(p){return p.toFloat()});return Fe(f,s)})}function Ko(r){return 1/(1+Math.exp(-r))}var Ja=function(r){re(t,r);function t(e,n,o,a,i){return i===void 0&&(i=!1),r.call(this,{x:e,y:n,width:o,height:a},i)||this}return t}(rn),Tm=.5,Nm=.43,Fm=.45,Qr=function(){function r(t,e,n){n===void 0&&(n=new ge(0,0));var o=e.width,a=e.height;this._imgDims=new Un(o,a),this._shift=n,this._positions=t.map(function(i){return i.mul(new ge(o,a)).add(n)})}return Object.defineProperty(r.prototype,"shift",{get:function(){return new ge(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"imageWidth",{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"imageHeight",{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"positions",{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"relativePositions",{get:function(){var t=this;return this._positions.map(function(e){return e.sub(t._shift).div(new ge(t.imageWidth,t.imageHeight))})},enumerable:!0,configurable:!0}),r.prototype.forSize=function(t,e){return new this.constructor(this.relativePositions,{width:t,height:e})},r.prototype.shiftBy=function(t,e){return new this.constructor(this.relativePositions,this._imgDims,new ge(t,e))},r.prototype.shiftByPoint=function(t){return this.shiftBy(t.x,t.y)},r.prototype.align=function(t,e){if(e===void 0&&(e={}),t){var n=t instanceof Mt?t.box.floor():new rn(t);return this.shiftBy(n.x,n.y).align(null,e)}var o=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},e),a=o.useDlibAlignment,i=o.minBoxPadding;return a?this.alignDlib():this.alignMinBbox(i)},r.prototype.alignDlib=function(){var t=this.getRefPointsForAlignment(),e=t[0],n=t[1],o=t[2],a=function(h){return o.sub(h).magnitude()},i=(a(e)+a(n))/2,s=Math.floor(i/Fm),u=Ya(t),c=Math.floor(Math.max(0,u.x-Tm*s)),l=Math.floor(Math.max(0,u.y-Nm*s));return new Ja(c,l,Math.min(s,this.imageWidth+c),Math.min(s,this.imageHeight+l))},r.prototype.alignMinBbox=function(t){var e=Dm(this.positions);return e.pad(e.width*t,e.height*t)},r.prototype.getRefPointsForAlignment=function(){throw new Error("getRefPointsForAlignment not implemented by base class")},r}(),Pm=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.getRefPointsForAlignment=function(){var e=this.positions;return[e[0],e[1],Ya([e[3],e[4]])]},t}(Qr),Mm=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.getJawOutline=function(){return this.positions.slice(0,17)},t.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},t.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},t.prototype.getNose=function(){return this.positions.slice(27,36)},t.prototype.getLeftEye=function(){return this.positions.slice(36,42)},t.prototype.getRightEye=function(){return this.positions.slice(42,48)},t.prototype.getMouth=function(){return this.positions.slice(48,68)},t.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Ya)},t}(Qr),ys=function(){function r(t,e){this._label=t,this._distance=e}return Object.defineProperty(r.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"distance",{get:function(){return this._distance},enumerable:!0,configurable:!0}),r.prototype.toString=function(t){return t===void 0&&(t=!0),""+this.label+(t?" ("+Rm(this.distance)+")":"")},r}(),xs=function(r){re(t,r);function t(e,n){var o=r.call(this,e)||this;return o._label=n,o}return t.assertIsValidLabeledBox=function(e,n){if(rn.assertIsValidBox(e,n),!dn(e.label))throw new Error(n+" - expected property label ("+e.label+") to be a number")},Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),t}(rn),kr=function(){function r(t,e){if(typeof t!="string")throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(e)||e.some(function(n){return!(n instanceof Float32Array)}))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=e}return Object.defineProperty(r.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"descriptors",{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),r.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map(function(t){return Array.from(t)})}},r.fromJSON=function(t){var e=t.descriptors.map(function(n){return new Float32Array(n)});return new r(t.label,e)},r}();(function(r){re(t,r);function t(e,n,o,a){var i=r.call(this,e,n)||this;return i._score=o,i._classScore=a,i}return t.assertIsValidPredictedBox=function(e,n){if(xs.assertIsValidLabeledBox(e,n),!gs(e.score)||!gs(e.classScore))throw new Error(n+" - expected properties score ("+e.score+") and ("+e.classScore+") to be a number between [0, 1]")},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}),t})(xs);function Om(r){return r.detection instanceof Mt}function Qa(r,t){var e={detection:t};return Object.assign({},r,e)}function ac(){var r=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},t=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement("canvas")},createImageElement:function(){return document.createElement("img")},fetch:r,readFile:t}}function ic(r){var t="";if(!r)try{r=require("fs")}catch(n){t=n.toString()}var e=r?function(n){return new Promise(function(o,a){r.readFile(n,function(i,s){return i?a(i):o(s)})})}:function(){throw new Error("readFile - failed to require fs in nodejs environment with error: "+t)};return{readFile:e}}function sc(){var r=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,e=function(){if(r)return new r;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},n=function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},o=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},a=ic();return qe({Canvas:r||function(){function i(){}return i}(),CanvasRenderingContext2D:global.CanvasRenderingContext2D||function(){function i(){}return i}(),Image:t||function(){function i(){}return i}(),ImageData:global.ImageData||function(){function i(){}return i}(),Video:global.HTMLVideoElement||function(){function i(){}return i}(),createCanvasElement:e,createImageElement:n,fetch:o},a)}function uc(){return typeof window=="object"&&typeof document<"u"&&typeof HTMLImageElement<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLVideoElement<"u"&&typeof ImageData<"u"&&typeof CanvasRenderingContext2D<"u"}function cc(){return typeof global=="object"&&typeof require=="function"&&typeof module<"u"&&typeof process<"u"&&!!process.version}var Ne;function Bm(){if(!Ne)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Ne}function ya(r){Ne=r}function Za(){uc()&&ya(ac()),cc()&&ya(sc())}function Lm(r){if(Ne||Za(),!Ne)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");var t=r.Canvas,e=t===void 0?Ne.Canvas:t,n=r.Image,o=n===void 0?Ne.Image:n;Ne.Canvas=e,Ne.Image=o,Ne.createCanvasElement=r.createCanvasElement||function(){return new e},Ne.createImageElement=r.createImageElement||function(){return new o},Ne.ImageData=r.ImageData||Ne.ImageData,Ne.Video=r.Video||Ne.Video,Ne.fetch=r.fetch||Ne.fetch,Ne.readFile=r.readFile||Ne.readFile}var $e={getEnv:Bm,setEnv:ya,initialize:Za,createBrowserEnv:ac,createFileSystem:ic,createNodejsEnv:sc,monkeyPatch:Lm,isBrowser:uc,isNodejs:cc};Za();function lc(r){return!$e.isNodejs()&&typeof r=="string"?document.getElementById(r):r}function mn(r){var t=$e.getEnv(),e=t.Canvas,n=t.CanvasRenderingContext2D;if(r instanceof n)return r;var o=lc(r);if(!(o instanceof e))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");var a=o.getContext("2d");if(!a)throw new Error("resolveContext2d - canvas 2d context is null");return a}var bs;(function(r){r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT"})(bs||(bs={}));function hc(r){var t=$e.getEnv(),e=t.Image,n=t.Video;return r instanceof e&&r.complete||r instanceof n&&r.readyState>=3}function Wm(r){return new Promise(function(t,e){if(r instanceof $e.getEnv().Canvas||hc(r))return t();function n(a){a.currentTarget&&(a.currentTarget.removeEventListener("load",n),a.currentTarget.removeEventListener("error",o),t(a))}function o(a){a.currentTarget&&(a.currentTarget.removeEventListener("load",n),a.currentTarget.removeEventListener("error",o),e(a))}r.addEventListener("load",n),r.addEventListener("error",o)})}function fc(r){var t=$e.getEnv(),e=t.Image,n=t.Video;return r instanceof e?new Un(r.naturalWidth,r.naturalHeight):r instanceof n?new Un(r.videoWidth,r.videoHeight):new Un(r.width,r.height)}function vo(r){var t=r.width,e=r.height,n=$e.getEnv().createCanvasElement,o=n();return o.width=t,o.height=e,o}function ei(r,t){var e=$e.getEnv().ImageData;if(!(r instanceof e)&&!hc(r))throw new Error("createCanvasFromMedia - media has not finished loading yet");var n=fc(r),o=n.width,a=n.height,i=vo({width:o,height:a});return r instanceof e?mn(i).putImageData(r,0,0):mn(i).drawImage(r,0,0,o,a),i}function Um(r,t){return Q(this,void 0,void 0,function(){var e,n,o,a,i,s;return Z(this,function(u){switch(u.label){case 0:return e=$e.getEnv().createCanvasElement(),n=r.shape.slice(tn(r)?1:0),o=n[0],a=n[1],i=n[2],s=K(function(){return r.as3D(o,a,i).toInt()}),[4,$a.toPixels(s,e)];case 1:return u.sent(),s.dispose(),[2,e]}})})}function ws(r){var t=$e.getEnv(),e=t.Image,n=t.Canvas,o=t.Video;return r instanceof e||r instanceof n||r instanceof o}function Vm(r,t,e){e===void 0&&(e=!1);var n=$e.getEnv(),o=n.Image,a=n.Canvas;if(!(r instanceof o||r instanceof a))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");var i=fc(r),s=t/Math.max(i.height,i.width),u=s*i.width,c=s*i.height,l=vo({width:t,height:t}),h=r instanceof a?r:ei(r),f=Math.abs(u-c)/2,p=e&&u<c?f:0,d=e&&c<u?f:0;return mn(l).drawImage(h,p,d,u,c),l}var Zr=function(){function r(t,e){var n=this;if(e===void 0&&(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(o,a){if(fo(o)){n._imageTensors[a]=o,n._inputDimensions[a]=o.shape;return}if(tn(o)){var i=o.shape[0];if(i!==1)throw new Error("NetInput - tf.Tensor4D with batchSize "+i+" passed, but not supported in input array");n._imageTensors[a]=o,n._inputDimensions[a]=o.shape.slice(1);return}var s=o instanceof $e.getEnv().Canvas?o:ei(o);n._canvases[a]=s,n._inputDimensions[a]=[s.height,s.width,3]})}return Object.defineProperty(r.prototype,"imageTensors",{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"canvases",{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"isBatchInput",{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"batchSize",{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"inputDimensions",{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"reshapedInputDimensions",{get:function(){var t=this;return ir(this.batchSize,0,1).map(function(e,n){return t.getReshapedInputDimensions(n)})},enumerable:!0,configurable:!0}),r.prototype.getInput=function(t){return this.canvases[t]||this.imageTensors[t]},r.prototype.getInputDimensions=function(t){return this._inputDimensions[t]},r.prototype.getInputHeight=function(t){return this._inputDimensions[t][0]},r.prototype.getInputWidth=function(t){return this._inputDimensions[t][1]},r.prototype.getReshapedInputDimensions=function(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");var e=this.getInputWidth(t),n=this.getInputHeight(t);return km({width:e,height:n},this.inputSize)},r.prototype.toBatchTensor=function(t,e){var n=this;return e===void 0&&(e=!0),this._inputSize=t,K(function(){var o=ir(n.batchSize,0,1).map(function(i){var s=n.getInput(i);if(s instanceof Ee){var u=tn(s)?s:s.expandDims();return u=Am(u,e),(u.shape[1]!==t||u.shape[2]!==t)&&(u=Ga.resizeBilinear(u,[t,t])),u.as3D(t,t,3)}if(s instanceof $e.getEnv().Canvas)return $a.fromPixels(Vm(s,t,e));throw new Error("toBatchTensor - at batchIdx "+i+", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have "+s)}),a=ct(o.map(function(i){return i.toFloat()})).as4D(n.batchSize,t,t,3);return a})},r}();function Ue(r){return Q(this,void 0,void 0,function(){var t,e,n;return Z(this,function(o){switch(o.label){case 0:if(r instanceof Zr)return[2,r];if(t=Array.isArray(r)?r:[r],!t.length)throw new Error("toNetInput - empty array passed as input");return e=function(a){return Array.isArray(r)?" at input index "+a+":":""},n=t.map(lc),n.forEach(function(a,i){if(!ws(a)&&!fo(a)&&!tn(a))throw typeof t[i]=="string"?new Error("toNetInput -"+e(i)+" string passed, but could not resolve HTMLElement for element id "+t[i]):new Error("toNetInput -"+e(i)+" expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id");if(tn(a)){var s=a.shape[0];if(s!==1)throw new Error("toNetInput -"+e(i)+" tf.Tensor4D with batchSize "+s+" passed, but not supported in input array")}}),[4,Promise.all(n.map(function(a){return ws(a)&&Wm(a)}))];case 1:return o.sent(),[2,new Zr(n,Array.isArray(r))]}})})}function ti(r,t){return Q(this,void 0,void 0,function(){var e,n,o,a,i,s,u;return Z(this,function(c){switch(c.label){case 0:return e=$e.getEnv().Canvas,n=r,r instanceof e?[3,5]:[4,Ue(r)];case 1:if(o=c.sent(),o.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");return a=o.getInput(0),a instanceof e?(i=a,[3,4]):[3,2];case 2:return[4,Um(a)];case 3:i=c.sent(),c.label=4;case 4:n=i,c.label=5;case 5:return s=mn(n),u=t.map(function(l){return l instanceof Mt?l.forSize(n.width,n.height).box.floor():l}).map(function(l){return l.clipAtImageBorders(n.width,n.height)}),[2,u.map(function(l){var h=l.x,f=l.y,p=l.width,d=l.height,g=vo({width:p,height:d});return mn(g).putImageData(s.getImageData(h,f,p,d),0,0),g})]}})})}function ni(r,t){return Q(this,void 0,void 0,function(){return Z(this,function(e){if(!fo(r)&&!tn(r))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(tn(r)&&r.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return[2,K(function(){var n=r.shape.slice(tn(r)?1:0),o=n[0],a=n[1],i=n[2],s=t.map(function(c){return c instanceof Mt?c.forSize(a,o).box:c}).map(function(c){return c.clipAtImageBorders(a,o)}),u=s.map(function(c){var l=c.x,h=c.y,f=c.width,p=c.height;return Wu(r.as3D(o,a,i),[h,l,0],[p,f,i])});return u})]})})}function zm(r,t){return Q(this,void 0,void 0,function(){var e,n;return Z(this,function(o){switch(o.label){case 0:return e=$e.getEnv().fetch,[4,e(r,t)];case 1:if(n=o.sent(),!(n.status<400))throw new Error("failed to fetch: ("+n.status+") "+n.statusText+", from url: "+n.url);return[2,n]}})})}function Gm(r){return Q(this,void 0,void 0,function(){return Z(this,function(t){switch(t.label){case 0:return[4,zm(r)];case 1:return[2,t.sent().json()]}})})}function pc(r,t){var e=t+"-weights_manifest.json";if(!r)return{modelBaseUri:"",manifestUri:e};if(r==="/")return{modelBaseUri:"/",manifestUri:"/"+e};var n=r.startsWith("http://")?"http://":r.startsWith("https://")?"https://":"";r=r.replace(n,"");var o=r.split("/").filter(function(s){return s}),a=r.endsWith(".json")?o[o.length-1]:e,i=n+(r.endsWith(".json")?o.slice(0,o.length-1):o).join("/");return i=r.startsWith("/")?"/"+i:i,{modelBaseUri:i,manifestUri:i==="/"?"/"+a:i+"/"+a}}function Hm(r,t){return Q(this,void 0,void 0,function(){var e,n,o,a;return Z(this,function(i){switch(i.label){case 0:return e=pc(r,t),n=e.manifestUri,o=e.modelBaseUri,[4,Gm(n)];case 1:return a=i.sent(),[2,nc.loadWeights(a,o)]}})})}var qt=function(){function r(t){this._name=t,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(r.prototype,"params",{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"paramMappings",{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"isLoaded",{get:function(){return!!this.params},enumerable:!0,configurable:!0}),r.prototype.getParamFromPath=function(t){var e=this.traversePropertyPath(t),n=e.obj,o=e.objProp;return n[o]},r.prototype.reassignParamFromPath=function(t,e){var n=this.traversePropertyPath(t),o=n.obj,a=n.objProp;o[a].dispose(),o[a]=e},r.prototype.getParamList=function(){var t=this;return this._paramMappings.map(function(e){var n=e.paramPath;return{path:n,tensor:t.getParamFromPath(n)}})},r.prototype.getTrainableParams=function(){return this.getParamList().filter(function(t){return t.tensor instanceof Gn})},r.prototype.getFrozenParams=function(){return this.getParamList().filter(function(t){return!(t.tensor instanceof Gn)})},r.prototype.variable=function(){var t=this;this.getFrozenParams().forEach(function(e){var n=e.path,o=e.tensor;t.reassignParamFromPath(n,o.variable())})},r.prototype.freeze=function(){var t=this;this.getTrainableParams().forEach(function(e){var n=e.path,o=e.tensor,a=Ge(o.dataSync());o.dispose(),t.reassignParamFromPath(n,a)})},r.prototype.dispose=function(t){t===void 0&&(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},r.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)}))},r.prototype.load=function(t){return Q(this,void 0,void 0,function(){return Z(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]}})})},r.prototype.loadFromUri=function(t){return Q(this,void 0,void 0,function(){var e;return Z(this,function(n){switch(n.label){case 0:if(t&&typeof t!="string")throw new Error(this._name+".loadFromUri - expected model uri");return[4,Hm(t,this.getDefaultModelName())];case 1:return e=n.sent(),this.loadFromWeightMap(e),[2]}})})},r.prototype.loadFromDisk=function(t){return Q(this,void 0,void 0,function(){var e,n,o,a,i,s,u,c,l,h;return Z(this,function(f){switch(f.label){case 0:if(t&&typeof t!="string")throw new Error(this._name+".loadFromDisk - expected model file path");return e=$e.getEnv().readFile,n=pc(t,this.getDefaultModelName()),o=n.manifestUri,a=n.modelBaseUri,i=function(p){return Promise.all(p.map(function(d){return e(d).then(function(g){return g.buffer})}))},s=nc.weightsLoaderFactory(i),l=(c=JSON).parse,[4,e(o)];case 1:return u=l.apply(c,[f.sent().toString()]),[4,s(u,a)];case 2:return h=f.sent(),this.loadFromWeightMap(h),[2]}})})},r.prototype.loadFromWeightMap=function(t){var e=this.extractParamsFromWeigthMap(t),n=e.paramMappings,o=e.params;this._paramMappings=n,this._params=o},r.prototype.extractWeights=function(t){var e=this.extractParams(t),n=e.paramMappings,o=e.params;this._paramMappings=n,this._params=o},r.prototype.traversePropertyPath=function(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");var e=t.split("/").reduce(function(a,i){if(!a.nextObj.hasOwnProperty(i))throw new Error("traversePropertyPath - object does not have property "+i+", for path "+t);return{obj:a.nextObj,objProp:i,nextObj:a.nextObj[i]}},{nextObj:this.params}),n=e.obj,o=e.objProp;if(!n||!o||!(n[o]instanceof Ee))throw new Error("traversePropertyPath - parameter is not a tensor, for path "+t);return{obj:n,objProp:o}},r}();function ut(r,t,e){return K(function(){var n=La(r,t.depthwise_filter,t.pointwise_filter,e,"same");return n=ue(n,t.bias),n})}function Xo(r,t,e){return e===void 0&&(e=!1),K(function(){var n=Ie(e?ue(pt(r,t.conv0.filters,[2,2],"same"),t.conv0.bias):ut(r,t.conv0,[2,2])),o=ut(n,t.conv1,[1,1]),a=Ie(ue(n,o)),i=ut(a,t.conv2,[1,1]);return Ie(ue(n,ue(o,i)))})}function Sr(r,t,e,n){return e===void 0&&(e=!1),n===void 0&&(n=!0),K(function(){var o=Ie(e?ue(pt(r,t.conv0.filters,n?[2,2]:[1,1],"same"),t.conv0.bias):ut(r,t.conv0,n?[2,2]:[1,1])),a=ut(o,t.conv1,[1,1]),i=Ie(ue(o,a)),s=ut(i,t.conv2,[1,1]),u=Ie(ue(o,ue(a,s))),c=ut(u,t.conv3,[1,1]);return Ie(ue(o,ue(a,ue(s,c))))})}function mt(r,t,e,n){return e===void 0&&(e="same"),n===void 0&&(n=!1),K(function(){var o=ue(pt(r,t.filters,[1,1],e),t.bias);return n?Ie(o):o})}function jt(r,t){Object.keys(r).forEach(function(e){t.some(function(n){return n.originalPath===e})||r[e].dispose()})}function mo(r,t){return function(e,n,o,a){var i=Je(r(e*n*o*o),[o,o,e,n]),s=Te(r(n));return t.push({paramPath:a+"/filters"},{paramPath:a+"/bias"}),{filters:i,bias:s}}}function ri(r,t){return function(e,n,o){var a=Zt(r(e*n),[e,n]),i=Te(r(n));return t.push({paramPath:o+"/weights"},{paramPath:o+"/bias"}),{weights:a,bias:i}}}var dc=function(){function r(t,e,n){this.depthwise_filter=t,this.pointwise_filter=e,this.bias=n}return r}();function oi(r,t){return function(e,n,o){var a=Je(r(9*e),[3,3,e,1]),i=Je(r(e*n),[1,1,e,n]),s=Te(r(n));return t.push({paramPath:o+"/depthwise_filter"},{paramPath:o+"/pointwise_filter"},{paramPath:o+"/bias"}),new dc(a,i,s)}}function ai(r){return function(t){var e=r(t+"/depthwise_filter",4),n=r(t+"/pointwise_filter",4),o=r(t+"/bias",1);return new dc(e,n,o)}}function sn(r,t){return function(e,n,o){var a=r[e];if(!ho(a,n))throw new Error("expected weightMap["+e+"] to be a Tensor"+n+"D, instead have "+a);return t.push({originalPath:e,paramPath:o||e}),a}}function Kt(r){var t=r;function e(o){var a=t.slice(0,o);return t=t.slice(o),a}function n(){return t}return{extractWeights:e,getRemainingWeights:n}}function vc(r,t){var e=mo(r,t),n=oi(r,t);function o(i,s,u,c){c===void 0&&(c=!1);var l=c?e(i,s,3,u+"/conv0"):n(i,s,u+"/conv0"),h=n(s,s,u+"/conv1"),f=n(s,s,u+"/conv2");return{conv0:l,conv1:h,conv2:f}}function a(i,s,u,c){c===void 0&&(c=!1);var l=o(i,s,u,c),h=l.conv0,f=l.conv1,p=l.conv2,d=n(s,s,u+"/conv3");return{conv0:h,conv1:f,conv2:p,conv3:d}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:a}}function qm(r){var t=[],e=Kt(r),n=e.extractWeights,o=e.getRemainingWeights,a=vc(n,t).extractDenseBlock4Params,i=a(3,32,"dense0",!0),s=a(32,64,"dense1"),u=a(64,128,"dense2"),c=a(128,256,"dense3");if(o().length!==0)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:t,params:{dense0:i,dense1:s,dense2:u,dense3:c}}}function mc(r){return function(t){var e=r(t+"/filters",4),n=r(t+"/bias",1);return{filters:e,bias:n}}}function gc(r,t){var e=sn(r,t),n=mc(e),o=ai(e);function a(s,u){u===void 0&&(u=!1);var c=u?n(s+"/conv0"):o(s+"/conv0"),l=o(s+"/conv1"),h=o(s+"/conv2");return{conv0:c,conv1:l,conv2:h}}function i(s,u){u===void 0&&(u=!1);var c=u?n(s+"/conv0"):o(s+"/conv0"),l=o(s+"/conv1"),h=o(s+"/conv2"),f=o(s+"/conv3");return{conv0:c,conv1:l,conv2:h,conv3:f}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:i}}function jm(r){var t=[],e=gc(r,t).extractDenseBlock4Params,n={dense0:e("dense0",!0),dense1:e("dense1"),dense2:e("dense2"),dense3:e("dense3")};return jt(r,t),{params:n,paramMappings:t}}var yc=function(r){re(t,r);function t(){return r.call(this,"FaceFeatureExtractor")||this}return t.prototype.forwardInput=function(e){var n=this.params;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return K(function(){var o=e.toBatchTensor(112,!0),a=[122.782,117.001,104.298],i=mr(o,a).div(q(255)),s=Sr(i,n.dense0,!0);return s=Sr(s,n.dense1),s=Sr(s,n.dense2),s=Sr(s,n.dense3),s=dr(s,[7,7],[2,2],"valid"),s})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.getDefaultModelName=function(){return"face_feature_extractor_model"},t.prototype.extractParamsFromWeigthMap=function(e){return jm(e)},t.prototype.extractParams=function(e){return qm(e)},t}(qt);function kt(r,t){return K(function(){return ue(uo(r,t.weights),t.bias)})}function Km(r,t,e){var n=[],o=Kt(r),a=o.extractWeights,i=o.getRemainingWeights,s=ri(a,n),u=s(t,e,"fc");if(i().length!==0)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:n,params:{fc:u}}}function Xm(r){var t=[],e=sn(r,t);function n(a){var i=e(a+"/weights",2),s=e(a+"/bias",1);return{weights:i,bias:s}}var o={fc:n("fc")};return jt(r,t),{params:o,paramMappings:t}}function xc(r){var t={},e={};return Object.keys(r).forEach(function(n){var o=n.startsWith("fc")?e:t;o[n]=r[n]}),{featureExtractorMap:t,classifierMap:e}}var bc=function(r){re(t,r);function t(e,n){var o=r.call(this,e)||this;return o._faceFeatureExtractor=n,o}return Object.defineProperty(t.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var n=this,o=this.params;if(!o)throw new Error(this._name+" - load model before inference");return K(function(){var a=e instanceof Zr?n.faceFeatureExtractor.forwardInput(e):e;return kt(a.as2D(a.shape[0],-1),o.fc)})},t.prototype.dispose=function(e){e===void 0&&(e=!0),this.faceFeatureExtractor.dispose(e),r.prototype.dispose.call(this,e)},t.prototype.loadClassifierParams=function(e){var n=this.extractClassifierParams(e),o=n.params,a=n.paramMappings;this._params=o,this._paramMappings=a},t.prototype.extractClassifierParams=function(e){return Km(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},t.prototype.extractParamsFromWeigthMap=function(e){var n=xc(e),o=n.featureExtractorMap,a=n.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(o),Xm(a)},t.prototype.extractParams=function(e){var n=this.getClassifierChannelsIn(),o=this.getClassifierChannelsOut(),a=o*n+o,i=e.slice(0,e.length-a),s=e.slice(e.length-a);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(s)},t}(qt),Cs=["neutral","happy","sad","angry","fearful","disgusted","surprised"],$m=function(){function r(t){var e=this;if(t.length!==7)throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: "+t.length);Cs.forEach(function(n,o){e[n]=t[o]})}return r.prototype.asSortedArray=function(){var t=this;return Cs.map(function(e){return{expression:e,probability:t[e]}}).sort(function(e,n){return n.probability-e.probability})},r}(),Ym=function(r){re(t,r);function t(e){return e===void 0&&(e=new yc),r.call(this,"FaceExpressionNet",e)||this}return t.prototype.forwardInput=function(e){var n=this;return K(function(){return Gt(n.runNet(e))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.predictExpressions=function(e){return Q(this,void 0,void 0,function(){var n,o,a,i,s=this;return Z(this,function(u){switch(u.label){case 0:return[4,Ue(e)];case 1:return n=u.sent(),[4,this.forwardInput(n)];case 2:return o=u.sent(),[4,Promise.all(Pe(o).map(function(c){return Q(s,void 0,void 0,function(){var l;return Z(this,function(h){switch(h.label){case 0:return[4,c.data()];case 1:return l=h.sent(),c.dispose(),[2,l]}})})}))];case 3:return a=u.sent(),o.dispose(),i=a.map(function(c){return new $m(c)}),[2,n.isBatchInput?i:i[0]]}})})},t.prototype.getDefaultModelName=function(){return"face_expression_model"},t.prototype.getClassifierChannelsIn=function(){return 256},t.prototype.getClassifierChannelsOut=function(){return 7},t}(bc);function wc(r,t){var e={expressions:t};return Object.assign({},r,e)}function Jm(r){return Om(r)&&r.landmarks instanceof Qr&&r.unshiftedLandmarks instanceof Qr&&r.alignedRect instanceof Mt}function ii(r,t){var e=r.detection.box,n=t.shiftBy(e.x,e.y),o=n.align(),a=r.detection.imageDims,i=new Mt(r.detection.score,o.rescale(a.reverse()),a),s={landmarks:n,unshiftedLandmarks:t,alignedRect:i};return Object.assign({},r,s)}function Qm(r,t){var e=mo(r,t),n=oi(r,t);function o(i,s,u){var c=n(i,s,u+"/separable_conv0"),l=n(s,s,u+"/separable_conv1"),h=e(i,s,1,u+"/expansion_conv");return{separable_conv0:c,separable_conv1:l,expansion_conv:h}}function a(i,s){var u=n(i,i,s+"/separable_conv0"),c=n(i,i,s+"/separable_conv1"),l=n(i,i,s+"/separable_conv2");return{separable_conv0:u,separable_conv1:c,separable_conv2:l}}return{extractConvParams:e,extractSeparableConvParams:n,extractReductionBlockParams:o,extractMainBlockParams:a}}function Zm(r,t){var e=[],n=Kt(r),o=n.extractWeights,a=n.getRemainingWeights,i=Qm(o,e),s=i.extractConvParams,u=i.extractSeparableConvParams,c=i.extractReductionBlockParams,l=i.extractMainBlockParams,h=s(3,32,3,"entry_flow/conv_in"),f=c(32,64,"entry_flow/reduction_block_0"),p=c(64,128,"entry_flow/reduction_block_1"),d={conv_in:h,reduction_block_0:f,reduction_block_1:p},g={};ir(t,0,1).forEach(function(b){g["main_block_"+b]=l(128,"middle_flow/main_block_"+b)});var v=c(128,256,"exit_flow/reduction_block"),m=u(256,512,"exit_flow/separable_conv"),x={reduction_block:v,separable_conv:m};if(a().length!==0)throw new Error("weights remaing after extract: "+a().length);return{paramMappings:e,params:{entry_flow:d,middle_flow:g,exit_flow:x}}}function eg(r,t){var e=sn(r,t),n=mc(e),o=ai(e);function a(s){var u=o(s+"/separable_conv0"),c=o(s+"/separable_conv1"),l=n(s+"/expansion_conv");return{separable_conv0:u,separable_conv1:c,expansion_conv:l}}function i(s){var u=o(s+"/separable_conv0"),c=o(s+"/separable_conv1"),l=o(s+"/separable_conv2");return{separable_conv0:u,separable_conv1:c,separable_conv2:l}}return{extractConvParams:n,extractSeparableConvParams:o,extractReductionBlockParams:a,extractMainBlockParams:i}}function tg(r,t){var e=[],n=eg(r,e),o=n.extractConvParams,a=n.extractSeparableConvParams,i=n.extractReductionBlockParams,s=n.extractMainBlockParams,u=o("entry_flow/conv_in"),c=i("entry_flow/reduction_block_0"),l=i("entry_flow/reduction_block_1"),h={conv_in:u,reduction_block_0:c,reduction_block_1:l},f={};ir(t,0,1).forEach(function(v){f["main_block_"+v]=s("middle_flow/main_block_"+v)});var p=i("exit_flow/reduction_block"),d=a("exit_flow/separable_conv"),g={reduction_block:p,separable_conv:d};return jt(r,e),{params:{entry_flow:h,middle_flow:f,exit_flow:g},paramMappings:e}}function Cc(r,t,e){return ue(pt(r,t.filters,e,"same"),t.bias)}function $o(r,t,e){e===void 0&&(e=!0);var n=e?Ie(r):r;return n=ut(n,t.separable_conv0,[1,1]),n=ut(Ie(n),t.separable_conv1,[1,1]),n=Le(n,[3,3],[2,2],"same"),n=ue(n,Cc(r,t.expansion_conv,[2,2])),n}function ng(r,t){var e=ut(Ie(r),t.separable_conv0,[1,1]);return e=ut(Ie(e),t.separable_conv1,[1,1]),e=ut(Ie(e),t.separable_conv2,[1,1]),e=ue(e,r),e}var rg=function(r){re(t,r);function t(e){var n=r.call(this,"TinyXception")||this;return n._numMainBlocks=e,n}return t.prototype.forwardInput=function(e){var n=this,o=this.params;if(!o)throw new Error("TinyXception - load model before inference");return K(function(){var a=e.toBatchTensor(112,!0),i=[122.782,117.001,104.298],s=mr(a,i).div(q(256)),u=Ie(Cc(s,o.entry_flow.conv_in,[2,2]));return u=$o(u,o.entry_flow.reduction_block_0,!1),u=$o(u,o.entry_flow.reduction_block_1),ir(n._numMainBlocks,0,1).forEach(function(c){u=ng(u,o.middle_flow["main_block_"+c])}),u=$o(u,o.exit_flow.reduction_block),u=Ie(ut(u,o.exit_flow.separable_conv,[1,1])),u})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.getDefaultModelName=function(){return"tiny_xception_model"},t.prototype.extractParamsFromWeigthMap=function(e){return tg(e,this._numMainBlocks)},t.prototype.extractParams=function(e){return Zm(e,this._numMainBlocks)},t}(qt);function og(r){var t=[],e=Kt(r),n=e.extractWeights,o=e.getRemainingWeights,a=ri(n,t),i=a(512,1,"fc/age"),s=a(512,2,"fc/gender");if(o().length!==0)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:t,params:{fc:{age:i,gender:s}}}}function ag(r){var t=[],e=sn(r,t);function n(a){var i=e(a+"/weights",2),s=e(a+"/bias",1);return{weights:i,bias:s}}var o={fc:{age:n("fc/age"),gender:n("fc/gender")}};return jt(r,t),{params:o,paramMappings:t}}var eo;(function(r){r.FEMALE="female",r.MALE="male"})(eo||(eo={}));var ig=function(r){re(t,r);function t(e){e===void 0&&(e=new rg(2));var n=r.call(this,"AgeGenderNet")||this;return n._faceFeatureExtractor=e,n}return Object.defineProperty(t.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var n=this,o=this.params;if(!o)throw new Error(this._name+" - load model before inference");return K(function(){var a=e instanceof Zr?n.faceFeatureExtractor.forwardInput(e):e,i=dr(a,[7,7],[2,2],"valid").as2D(a.shape[0],-1),s=kt(i,o.fc.age).as1D(),u=kt(i,o.fc.gender);return{age:s,gender:u}})},t.prototype.forwardInput=function(e){var n=this;return K(function(){var o=n.runNet(e),a=o.age,i=o.gender;return{age:a,gender:Gt(i)}})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.predictAgeAndGender=function(e){return Q(this,void 0,void 0,function(){var n,o,a,i,s,u,c=this;return Z(this,function(l){switch(l.label){case 0:return[4,Ue(e)];case 1:return n=l.sent(),[4,this.forwardInput(n)];case 2:return o=l.sent(),a=Pe(o.age),i=Pe(o.gender),s=a.map(function(h,f){return{ageTensor:h,genderTensor:i[f]}}),[4,Promise.all(s.map(function(h){var f=h.ageTensor,p=h.genderTensor;return Q(c,void 0,void 0,function(){var d,g,v,m,x;return Z(this,function(b){switch(b.label){case 0:return[4,f.data()];case 1:return d=b.sent()[0],[4,p.data()];case 2:return g=b.sent()[0],v=g>.5,m=v?eo.MALE:eo.FEMALE,x=v?g:1-g,f.dispose(),p.dispose(),[2,{age:d,gender:m,genderProbability:x}]}})})}))];case 3:return u=l.sent(),o.age.dispose(),o.gender.dispose(),[2,n.isBatchInput?u:u[0]]}})})},t.prototype.getDefaultModelName=function(){return"age_gender_model"},t.prototype.dispose=function(e){e===void 0&&(e=!0),this.faceFeatureExtractor.dispose(e),r.prototype.dispose.call(this,e)},t.prototype.loadClassifierParams=function(e){var n=this.extractClassifierParams(e),o=n.params,a=n.paramMappings;this._params=o,this._paramMappings=a},t.prototype.extractClassifierParams=function(e){return og(e)},t.prototype.extractParamsFromWeigthMap=function(e){var n=xc(e),o=n.featureExtractorMap,a=n.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(o),ag(a)},t.prototype.extractParams=function(e){var n=1539,o=e.slice(0,e.length-n),a=e.slice(e.length-n);return this.faceFeatureExtractor.extractWeights(o),this.extractClassifierParams(a)},t}(qt),_c=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.postProcess=function(e,n,o){var a=o.map(function(s){var u=s.width,c=s.height,l=n/Math.max(c,u);return{width:u*l,height:c*l}}),i=a.length;return K(function(){var s=function(f,p){return ct([At([68],f),At([68],p)],1).as2D(1,136).as1D()},u=function(f,p){var d=a[f],g=d.width,v=d.height;return p(g,v)?Math.abs(g-v)/2:0},c=function(f){return u(f,function(p,d){return p<d})},l=function(f){return u(f,function(p,d){return d<p})},h=e.mul(At([i,136],n)).sub(ct(Array.from(Array(i),function(f,p){return s(c(p),l(p))}))).div(ct(Array.from(Array(i),function(f,p){return s(a[p].width,a[p].height)})));return h})},t.prototype.forwardInput=function(e){var n=this;return K(function(){var o=n.runNet(e);return n.postProcess(o,e.inputSize,e.inputDimensions.map(function(a){var i=a[0],s=a[1];return{height:i,width:s}}))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.detectLandmarks=function(e){return Q(this,void 0,void 0,function(){var n,o,a,i=this;return Z(this,function(s){switch(s.label){case 0:return[4,Ue(e)];case 1:return n=s.sent(),o=K(function(){return Pe(i.forwardInput(n))}),[4,Promise.all(o.map(function(u,c){return Q(i,void 0,void 0,function(){var l,h,f,p,d;return Z(this,function(g){switch(g.label){case 0:return f=(h=Array).from,[4,u.data()];case 1:return l=f.apply(h,[g.sent()]),p=l.filter(function(v,m){return vs(m)}),d=l.filter(function(v,m){return!vs(m)}),[2,new Mm(Array(68).fill(0).map(function(v,m){return new ge(p[m],d[m])}),{height:n.getInputHeight(c),width:n.getInputWidth(c)})]}})})}))];case 2:return a=s.sent(),o.forEach(function(u){return u.dispose()}),[2,n.isBatchInput?a:a[0]]}})})},t.prototype.getClassifierChannelsOut=function(){return 136},t}(bc),Ec=function(r){re(t,r);function t(e){return e===void 0&&(e=new yc),r.call(this,"FaceLandmark68Net",e)||this}return t.prototype.getDefaultModelName=function(){return"face_landmark_68_model"},t.prototype.getClassifierChannelsIn=function(){return 256},t}(_c);function sg(r){var t=[],e=gc(r,t).extractDenseBlock3Params,n={dense0:e("dense0",!0),dense1:e("dense1"),dense2:e("dense2")};return jt(r,t),{params:n,paramMappings:t}}function ug(r){var t=[],e=Kt(r),n=e.extractWeights,o=e.getRemainingWeights,a=vc(n,t).extractDenseBlock3Params,i=a(3,32,"dense0",!0),s=a(32,64,"dense1"),u=a(64,128,"dense2");if(o().length!==0)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:t,params:{dense0:i,dense1:s,dense2:u}}}var cg=function(r){re(t,r);function t(){return r.call(this,"TinyFaceFeatureExtractor")||this}return t.prototype.forwardInput=function(e){var n=this.params;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return K(function(){var o=e.toBatchTensor(112,!0),a=[122.782,117.001,104.298],i=mr(o,a).div(q(255)),s=Xo(i,n.dense0,!0);return s=Xo(s,n.dense1),s=Xo(s,n.dense2),s=dr(s,[14,14],[2,2],"valid"),s})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.getDefaultModelName=function(){return"face_feature_extractor_tiny_model"},t.prototype.extractParamsFromWeigthMap=function(e){return sg(e)},t.prototype.extractParams=function(e){return ug(e)},t}(qt),lg=function(r){re(t,r);function t(e){return e===void 0&&(e=new cg),r.call(this,"FaceLandmark68TinyNet",e)||this}return t.prototype.getDefaultModelName=function(){return"face_landmark_68_tiny_model"},t.prototype.getClassifierChannelsIn=function(){return 128},t}(_c);(function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t})(Ec);function hg(r,t){return ue(Xe(r,t.weights),t.biases)}function si(r,t,e,n,o){o===void 0&&(o="same");var a=t.conv,i=a.filters,s=a.bias,u=pt(r,i,e,o);return u=ue(u,s),u=hg(u,t.scale),n?Ie(u):u}function fg(r,t){return si(r,t,[1,1],!0)}function Ic(r,t){return si(r,t,[1,1],!1)}function Rc(r,t){return si(r,t,[2,2],!0,"valid")}function pg(r,t){function e(s,u,c){var l=r(s),h=l.length/(u*c*c);if(Im(h))throw new Error("depth has to be an integer: "+h+", weights.length: "+l.length+", numFilters: "+u+", filterSize: "+c);return K(function(){return nn(Je(l,[u,h,c,c]),[2,3,1,0])})}function n(s,u,c,l){var h=e(s,u,c),f=Te(r(u));return t.push({paramPath:l+"/filters"},{paramPath:l+"/bias"}),{filters:h,bias:f}}function o(s,u){var c=Te(r(s)),l=Te(r(s));return t.push({paramPath:u+"/weights"},{paramPath:u+"/biases"}),{weights:c,biases:l}}function a(s,u,c,l){var h=n(s,u,c,l+"/conv"),f=o(u,l+"/scale");return{conv:h,scale:f}}function i(s,u,c,l,h){h===void 0&&(h=!1);var f=a((h?.5:1)*s,u,c,l+"/conv1"),p=a(s,u,c,l+"/conv2");return{conv1:f,conv2:p}}return{extractConvLayerParams:a,extractResidualLayerParams:i}}function dg(r){var t=Kt(r),e=t.extractWeights,n=t.getRemainingWeights,o=[],a=pg(e,o),i=a.extractConvLayerParams,s=a.extractResidualLayerParams,u=i(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"),g=s(36864,64,3,"conv64_3"),v=s(147456,128,3,"conv128_down",!0),m=s(147456,128,3,"conv128_1"),x=s(147456,128,3,"conv128_2"),b=s(589824,256,3,"conv256_down",!0),y=s(589824,256,3,"conv256_1"),w=s(589824,256,3,"conv256_2"),C=s(589824,256,3,"conv256_down_out"),S=K(function(){return nn(Zt(e(256*128),[128,256]),[1,0])});if(o.push({paramPath:"fc"}),n().length!==0)throw new Error("weights remaing after extract: "+n().length);var k={conv32_down:u,conv32_1:c,conv32_2:l,conv32_3:h,conv64_down:f,conv64_1:p,conv64_2:d,conv64_3:g,conv128_down:v,conv128_1:m,conv128_2:x,conv256_down:b,conv256_1:y,conv256_2:w,conv256_down_out:C,fc:S};return{params:k,paramMappings:o}}function vg(r,t){var e=sn(r,t);function n(i){var s=e(i+"/scale/weights",1),u=e(i+"/scale/biases",1);return{weights:s,biases:u}}function o(i){var s=e(i+"/conv/filters",4),u=e(i+"/conv/bias",1),c=n(i);return{conv:{filters:s,bias:u},scale:c}}function a(i){return{conv1:o(i+"/conv1"),conv2:o(i+"/conv2")}}return{extractConvLayerParams:o,extractResidualLayerParams:a}}function mg(r){var t=[],e=vg(r,t),n=e.extractConvLayerParams,o=e.extractResidualLayerParams,a=n("conv32_down"),i=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"),g=o("conv128_2"),v=o("conv256_down"),m=o("conv256_1"),x=o("conv256_2"),b=o("conv256_down_out"),y=r.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!Em(y))throw new Error("expected weightMap[fc] to be a Tensor2D, instead have "+y);var w={conv32_down:a,conv32_1:i,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:g,conv256_down:v,conv256_1:m,conv256_2:x,conv256_down_out:b,fc:y};return jt(r,t),{params:w,paramMappings:t}}function Ct(r,t){var e=fg(r,t.conv1);return e=Ic(e,t.conv2),e=ue(e,r),e=Ie(e),e}function Dr(r,t){var e=Rc(r,t.conv1);e=Ic(e,t.conv2);var n=dr(r,2,2,"valid"),o=we(n.shape),a=n.shape[3]!==e.shape[3],i=n.shape[1]!==e.shape[1]||n.shape[2]!==e.shape[2];if(i){var s=er(e.shape);s[1]=1;var u=we(s);e=Fe([e,u],1);var c=er(e.shape);c[2]=1;var l=we(c);e=Fe([e,l],2)}return n=a?Fe([n,o],3):n,e=ue(n,e),e=Ie(e),e}var gg=function(r){re(t,r);function t(){return r.call(this,"FaceRecognitionNet")||this}return t.prototype.forwardInput=function(e){var n=this.params;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return K(function(){var o=e.toBatchTensor(150,!0).toFloat(),a=[122.782,117.001,104.298],i=mr(o,a).div(q(256)),s=Rc(i,n.conv32_down);s=Le(s,3,2,"valid"),s=Ct(s,n.conv32_1),s=Ct(s,n.conv32_2),s=Ct(s,n.conv32_3),s=Dr(s,n.conv64_down),s=Ct(s,n.conv64_1),s=Ct(s,n.conv64_2),s=Ct(s,n.conv64_3),s=Dr(s,n.conv128_down),s=Ct(s,n.conv128_1),s=Ct(s,n.conv128_2),s=Dr(s,n.conv256_down),s=Ct(s,n.conv256_1),s=Ct(s,n.conv256_2),s=Dr(s,n.conv256_down_out);var u=s.mean([1,2]),c=uo(u,n.fc);return c})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.computeFaceDescriptor=function(e){return Q(this,void 0,void 0,function(){var n,o,a,i=this;return Z(this,function(s){switch(s.label){case 0:return[4,Ue(e)];case 1:return n=s.sent(),o=K(function(){return Pe(i.forwardInput(n))}),[4,Promise.all(o.map(function(u){return u.data()}))];case 2:return a=s.sent(),o.forEach(function(u){return u.dispose()}),[2,n.isBatchInput?a:a[0]]}})})},t.prototype.getDefaultModelName=function(){return"face_recognition_model"},t.prototype.extractParamsFromWeigthMap=function(e){return mg(e)},t.prototype.extractParams=function(e){return dg(e)},t}(qt);function kc(r,t){var e={descriptor:t};return Object.assign({},r,e)}function Sc(r,t){var e={age:t};return Object.assign({},r,e)}function Dc(r,t,e){var n={gender:t,genderProbability:e};return Object.assign({},r,n)}var Ac=function(){function r(t){var e=t===void 0?{}:t,n=e.minFaceSize,o=e.scaleFactor,a=e.maxNumScales,i=e.scoreThresholds,s=e.scaleSteps;if(this._name="MtcnnOptions",this._minFaceSize=n||20,this._scaleFactor=o||.709,this._maxNumScales=a||10,this._scoreThresholds=i||[.6,.7,.7],this._scaleSteps=s,typeof this._minFaceSize!="number"||this._minFaceSize<0)throw new Error(this._name+" - expected minFaceSize to be a number > 0");if(typeof this._scaleFactor!="number"||this._scaleFactor<=0||this._scaleFactor>=1)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if(typeof this._maxNumScales!="number"||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||this._scoreThresholds.length!==3||this._scoreThresholds.some(function(u){return typeof u!="number"}))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(u){return typeof u!="number"})))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(r.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),r}();function yg(r,t){function e(u,c){var l=Je(r(9*u),[3,3,u,1]),h=Te(r(u)),f=Te(r(u)),p=Te(r(u)),d=Te(r(u));return t.push({paramPath:c+"/filters"},{paramPath:c+"/batch_norm_scale"},{paramPath:c+"/batch_norm_offset"},{paramPath:c+"/batch_norm_mean"},{paramPath:c+"/batch_norm_variance"}),{filters:l,batch_norm_scale:h,batch_norm_offset:f,batch_norm_mean:p,batch_norm_variance:d}}function n(u,c,l,h,f){var p=Je(r(u*c*l*l),[l,l,u,c]),d=Te(r(c));return t.push({paramPath:h+"/filters"},{paramPath:h+"/"+(f?"batch_norm_offset":"bias")}),{filters:p,bias:d}}function o(u,c,l,h){var f=n(u,c,l,h,!0),p=f.filters,d=f.bias;return{filters:p,batch_norm_offset:d}}function a(u,c,l){var h=e(u,l+"/depthwise_conv"),f=o(u,c,1,l+"/pointwise_conv");return{depthwise_conv:h,pointwise_conv:f}}function i(){var u=o(3,32,3,"mobilenetv1/conv_0"),c=a(32,64,"mobilenetv1/conv_1"),l=a(64,128,"mobilenetv1/conv_2"),h=a(128,128,"mobilenetv1/conv_3"),f=a(128,256,"mobilenetv1/conv_4"),p=a(256,256,"mobilenetv1/conv_5"),d=a(256,512,"mobilenetv1/conv_6"),g=a(512,512,"mobilenetv1/conv_7"),v=a(512,512,"mobilenetv1/conv_8"),m=a(512,512,"mobilenetv1/conv_9"),x=a(512,512,"mobilenetv1/conv_10"),b=a(512,512,"mobilenetv1/conv_11"),y=a(512,1024,"mobilenetv1/conv_12"),w=a(1024,1024,"mobilenetv1/conv_13");return{conv_0:u,conv_1:c,conv_2:l,conv_3:h,conv_4:f,conv_5:p,conv_6:d,conv_7:g,conv_8:v,conv_9:m,conv_10:x,conv_11:b,conv_12:y,conv_13:w}}function s(){var u=o(1024,256,1,"prediction_layer/conv_0"),c=o(256,512,3,"prediction_layer/conv_1"),l=o(512,128,1,"prediction_layer/conv_2"),h=o(128,256,3,"prediction_layer/conv_3"),f=o(256,128,1,"prediction_layer/conv_4"),p=o(128,256,3,"prediction_layer/conv_5"),d=o(256,64,1,"prediction_layer/conv_6"),g=o(64,128,3,"prediction_layer/conv_7"),v=n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),m=n(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),x=n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),b=n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),y=n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),w=n(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),C=n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),S=n(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),k=n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),I=n(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),R=n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),N=n(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),A={box_encoding_predictor:v,class_predictor:m},L={box_encoding_predictor:x,class_predictor:b},O={box_encoding_predictor:y,class_predictor:w},B={box_encoding_predictor:C,class_predictor:S},V={box_encoding_predictor:k,class_predictor:I},U={box_encoding_predictor:R,class_predictor:N};return{conv_0:u,conv_1:c,conv_2:l,conv_3:h,conv_4:f,conv_5:p,conv_6:d,conv_7:g,box_predictor_0:A,box_predictor_1:L,box_predictor_2:O,box_predictor_3:B,box_predictor_4:V,box_predictor_5:U}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:s}}function xg(r){var t=[],e=Kt(r),n=e.extractWeights,o=e.getRemainingWeights,a=yg(n,t),i=a.extractMobilenetV1Params,s=a.extractPredictionLayerParams,u=i(),c=s(),l=_a(n(5118*4),[1,5118,4]),h={extra_dim:l};if(t.push({paramPath:"output_layer/extra_dim"}),o().length!==0)throw new Error("weights remaing after extract: "+o().length);return{params:{mobilenetv1:u,prediction_layer:c,output_layer:h},paramMappings:t}}function bg(r,t){var e=sn(r,t);function n(c,l,h){var f=e(c+"/Conv2d_"+l+"_pointwise/weights",4,h+"/filters"),p=e(c+"/Conv2d_"+l+"_pointwise/convolution_bn_offset",1,h+"/batch_norm_offset");return{filters:f,batch_norm_offset:p}}function o(c){var l="mobilenetv1/conv_"+c,h="MobilenetV1/Conv2d_"+c+"_depthwise",f=l+"/depthwise_conv",p=l+"/pointwise_conv",d=e(h+"/depthwise_weights",4,f+"/filters"),g=e(h+"/BatchNorm/gamma",1,f+"/batch_norm_scale"),v=e(h+"/BatchNorm/beta",1,f+"/batch_norm_offset"),m=e(h+"/BatchNorm/moving_mean",1,f+"/batch_norm_mean"),x=e(h+"/BatchNorm/moving_variance",1,f+"/batch_norm_variance");return{depthwise_conv:{filters:d,batch_norm_scale:g,batch_norm_offset:v,batch_norm_mean:m,batch_norm_variance:x},pointwise_conv:n("MobilenetV1",c,p)}}function a(){return{conv_0:n("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)}}function i(c,l){var h=e(c+"/weights",4,l+"/filters"),f=e(c+"/biases",1,l+"/bias");return{filters:h,bias:f}}function s(c){var l=i("Prediction/BoxPredictor_"+c+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+c+"/box_encoding_predictor"),h=i("Prediction/BoxPredictor_"+c+"/ClassPredictor","prediction_layer/box_predictor_"+c+"/class_predictor");return{box_encoding_predictor:l,class_predictor:h}}function u(){return{conv_0:n("Prediction",0,"prediction_layer/conv_0"),conv_1:n("Prediction",1,"prediction_layer/conv_1"),conv_2:n("Prediction",2,"prediction_layer/conv_2"),conv_3:n("Prediction",3,"prediction_layer/conv_3"),conv_4:n("Prediction",4,"prediction_layer/conv_4"),conv_5:n("Prediction",5,"prediction_layer/conv_5"),conv_6:n("Prediction",6,"prediction_layer/conv_6"),conv_7:n("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:u}}function wg(r){var t=[],e=bg(r,t),n=e.extractMobilenetV1Params,o=e.extractPredictionLayerParams,a=r["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!fo(a))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+a);var i={mobilenetv1:n(),prediction_layer:o(),output_layer:{extra_dim:a}};return jt(r,t),{params:i,paramMappings:t}}function _t(r,t,e){return K(function(){var n=pt(r,t.filters,e,"same");return n=ue(n,t.batch_norm_offset),Pa(n,0,6)})}var Cg=.0010000000474974513;function _g(r,t,e){return K(function(){var n=so(r,t.filters,e,"same");return n=Eu(n,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Cg),Pa(n,0,6)})}function Eg(r){return[2,4,6,12].some(function(t){return t===r})?[2,2]:[1,1]}function Ig(r,t){return K(function(){var e=null,n=_t(r,t.conv_0,[2,2]),o=[t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13];if(o.forEach(function(a,i){var s=i+1,u=Eg(s);n=_g(n,a.depthwise_conv,u),n=_t(n,a.pointwise_conv,[1,1]),s===11&&(e=n)}),e===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:n,conv11:e}})}function Rg(r,t,e,n,o){var a=r.shape[0],i=Math.min(e,a),s=t.map(function(l,h){return{score:l,boxIndex:h}}).filter(function(l){return l.score>o}).sort(function(l,h){return h.score-l.score}),u=function(l){return l<=n?1:0},c=[];return s.forEach(function(l){if(!(c.length>=i)){for(var h=l.score,f=c.length-1;f>=0;--f){var p=kg(r,l.boxIndex,c[f]);if(p!==0&&(l.score*=u(p),l.score<=o))break}h===l.score&&c.push(l.boxIndex)}}),c}function kg(r,t,e){var n=r.arraySync(),o=Math.min(n[t][0],n[t][2]),a=Math.min(n[t][1],n[t][3]),i=Math.max(n[t][0],n[t][2]),s=Math.max(n[t][1],n[t][3]),u=Math.min(n[e][0],n[e][2]),c=Math.min(n[e][1],n[e][3]),l=Math.max(n[e][0],n[e][2]),h=Math.max(n[e][1],n[e][3]),f=(i-o)*(s-a),p=(l-u)*(h-c);if(f<=0||p<=0)return 0;var d=Math.max(o,u),g=Math.max(a,c),v=Math.min(i,l),m=Math.min(s,h),x=Math.max(v-d,0)*Math.max(m-g,0);return x/(f+p-x)}function Sg(r){var t=Pe(nn(r,[1,0])),e=[Oe(t[2],t[0]),Oe(t[3],t[1])],n=[ue(t[0],dt(e[0],q(2))),ue(t[1],dt(e[1],q(2)))];return{sizes:e,centers:n}}function Dg(r,t){var e=Sg(r),n=e.sizes,o=e.centers,a=Pe(nn(t,[1,0])),i=dt(Xe(ha(dt(a[2],q(5))),n[0]),q(2)),s=ue(Xe(dt(a[0],q(10)),n[0]),o[0]),u=dt(Xe(ha(dt(a[3],q(5))),n[1]),q(2)),c=ue(Xe(dt(a[1],q(10)),n[1]),o[1]);return nn(ct([Oe(s,i),Oe(c,u),ue(s,i),ue(c,u)]),[1,0])}function Ag(r,t,e){return K(function(){var n=r.shape[0],o=Dg(vt(Mn(e.extra_dim,[n,1,1]),[-1,4]),vt(r,[-1,4]));o=vt(o,[n,o.shape[0]/n,4]);var a=bu(Tt(t,[0,0,1],[-1,-1,-1])),i=Tt(a,[0,0,0],[-1,-1,1]);i=vt(i,[n,i.shape[1]]);var s=Pe(o),u=Pe(i);return{boxes:s,scores:u}})}function Dn(r,t){return K(function(){var e=r.shape[0],n=vt(mt(r,t.box_encoding_predictor),[e,-1,1,4]),o=vt(mt(r,t.class_predictor),[e,-1,3]);return{boxPredictionEncoding:n,classPrediction:o}})}function Tg(r,t,e){return K(function(){var n=_t(r,e.conv_0,[1,1]),o=_t(n,e.conv_1,[2,2]),a=_t(o,e.conv_2,[1,1]),i=_t(a,e.conv_3,[2,2]),s=_t(i,e.conv_4,[1,1]),u=_t(s,e.conv_5,[2,2]),c=_t(u,e.conv_6,[1,1]),l=_t(c,e.conv_7,[2,2]),h=Dn(t,e.box_predictor_0),f=Dn(r,e.box_predictor_1),p=Dn(o,e.box_predictor_2),d=Dn(i,e.box_predictor_3),g=Dn(u,e.box_predictor_4),v=Dn(l,e.box_predictor_5),m=Fe([h.boxPredictionEncoding,f.boxPredictionEncoding,p.boxPredictionEncoding,d.boxPredictionEncoding,g.boxPredictionEncoding,v.boxPredictionEncoding],1),x=Fe([h.classPrediction,f.classPrediction,p.classPrediction,d.classPrediction,g.classPrediction,v.classPrediction],1);return{boxPredictions:m,classPredictions:x}})}var gn=function(){function r(t){var e=t===void 0?{}:t,n=e.minConfidence,o=e.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=n||.5,this._maxResults=o||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if(typeof this._maxResults!="number")throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(r.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),r}(),Tc=function(r){re(t,r);function t(){return r.call(this,"SsdMobilenetv1")||this}return t.prototype.forwardInput=function(e){var n=this.params;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return K(function(){var o=e.toBatchTensor(512,!1).toFloat(),a=Oe(Xe(o,q(.007843137718737125)),q(1)),i=Ig(a,n.mobilenetv1),s=Tg(i.out,i.conv11,n.prediction_layer),u=s.boxPredictions,c=s.classPredictions;return Ag(u,c,n.output_layer)})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var n;return Z(this,function(o){switch(o.label){case 0:return n=this.forwardInput,[4,Ue(e)];case 1:return[2,n.apply(this,[o.sent()])]}})})},t.prototype.locateFaces=function(e,n){return n===void 0&&(n={}),Q(this,void 0,void 0,function(){var o,a,i,s,u,c,l,h,f,p,d,g,v,m,x,b,y,w,C,S,k;return Z(this,function(I){switch(I.label){case 0:return o=new gn(n),a=o.maxResults,i=o.minConfidence,[4,Ue(e)];case 1:for(s=I.sent(),u=this.forwardInput(s),c=u.boxes,l=u.scores,h=c[0],f=l[0],p=1;p<c.length;p++)c[p].dispose(),l[p].dispose();return v=(g=Array).from,[4,f.data()];case 2:return d=v.apply(g,[I.sent()]),m=.5,x=Rg(h,d,a,m,i),b=s.getReshapedInputDimensions(0),y=s.inputSize,w=y/b.width,C=y/b.height,S=h.arraySync(),k=x.map(function(R){var N=[Math.max(0,S[R][0]),Math.min(1,S[R][2])].map(function(U){return U*C}),A=N[0],L=N[1],O=[Math.max(0,S[R][1]),Math.min(1,S[R][3])].map(function(U){return U*w}),B=O[0],V=O[1];return new Mt(d[R],new Ja(B,A,V-B,L-A),{height:s.getInputHeight(0),width:s.getInputWidth(0)})}),h.dispose(),f.dispose(),[2,k]}})})},t.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},t.prototype.extractParamsFromWeigthMap=function(e){return wg(e)},t.prototype.extractParams=function(e){return xg(e)},t}(qt);(function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t})(Tc);var Ng=.4,Fg=[new ge(.738768,.874946),new ge(2.42204,2.65704),new ge(4.30971,7.04493),new ge(10.246,4.59428),new ge(12.6868,11.8741)],Pg=[new ge(1.603231,2.094468),new ge(6.041143,7.080126),new ge(2.882459,3.518061),new ge(4.266906,5.178857),new ge(9.041765,10.66308)],Mg=[117.001,114.697,97.404],Og="tiny_yolov2_model",Bg="tiny_yolov2_separable_conv_model",Ar=function(r){return typeof r=="number"};function Lg(r){if(!r)throw new Error("invalid config: "+r);if(typeof r.withSeparableConvs!="boolean")throw new Error("config.withSeparableConvs has to be a boolean, have: "+r.withSeparableConvs);if(!Ar(r.iouThreshold)||r.iouThreshold<0||r.iouThreshold>1)throw new Error("config.iouThreshold has to be a number between [0, 1], have: "+r.iouThreshold);if(!Array.isArray(r.classes)||!r.classes.length||!r.classes.every(function(t){return typeof t=="string"}))throw new Error("config.classes has to be an array class names: string[], have: "+JSON.stringify(r.classes));if(!Array.isArray(r.anchors)||!r.anchors.length||!r.anchors.map(function(t){return t||{}}).every(function(t){return Ar(t.x)&&Ar(t.y)}))throw new Error("config.anchors has to be an array of { x: number, y: number }, have: "+JSON.stringify(r.anchors));if(r.meanRgb&&(!Array.isArray(r.meanRgb)||r.meanRgb.length!==3||!r.meanRgb.every(Ar)))throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: "+JSON.stringify(r.meanRgb))}function ui(r){return K(function(){var t=Xe(r,q(.10000000149011612));return ue(Ie(Oe(r,t)),t)})}function $t(r,t){return K(function(){var e=xn(r,[[0,0],[1,1],[1,1],[0,0]]);return e=pt(e,t.conv.filters,[1,1],"valid"),e=Oe(e,t.bn.sub),e=Xe(e,t.bn.truediv),e=ue(e,t.conv.bias),ui(e)})}function Yt(r,t){return K(function(){var e=xn(r,[[0,0],[1,1],[1,1],[0,0]]);return e=La(e,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),e=ue(e,t.bias),ui(e)})}function Wg(r,t){var e=mo(r,t);function n(i,s){var u=Te(r(i)),c=Te(r(i));return t.push({paramPath:s+"/sub"},{paramPath:s+"/truediv"}),{sub:u,truediv:c}}function o(i,s,u){var c=e(i,s,3,u+"/conv"),l=n(s,u+"/bn");return{conv:c,bn:l}}var a=oi(r,t);return{extractConvParams:e,extractConvWithBatchNormParams:o,extractSeparableConvParams:a}}function Ug(r,t,e,n){var o=Kt(r),a=o.extractWeights,i=o.getRemainingWeights,s=[],u=Wg(a,s),c=u.extractConvParams,l=u.extractConvWithBatchNormParams,h=u.extractSeparableConvParams,f;if(t.withSeparableConvs){var p=n[0],d=n[1],g=n[2],v=n[3],m=n[4],x=n[5],b=n[6],y=n[7],w=n[8],C=t.isFirstLayerConv2d?c(p,d,3,"conv0"):h(p,d,"conv0"),S=h(d,g,"conv1"),k=h(g,v,"conv2"),I=h(v,m,"conv3"),R=h(m,x,"conv4"),N=h(x,b,"conv5"),A=y?h(b,y,"conv6"):void 0,L=w?h(y,w,"conv7"):void 0,O=c(w||y||b,5*e,1,"conv8");f={conv0:C,conv1:S,conv2:k,conv3:I,conv4:R,conv5:N,conv6:A,conv7:L,conv8:O}}else{var p=n[0],d=n[1],g=n[2],v=n[3],m=n[4],x=n[5],b=n[6],y=n[7],w=n[8],C=l(p,d,"conv0"),S=l(d,g,"conv1"),k=l(g,v,"conv2"),I=l(v,m,"conv3"),R=l(m,x,"conv4"),N=l(x,b,"conv5"),A=l(b,y,"conv6"),L=l(y,w,"conv7"),O=c(w,5*e,1,"conv8");f={conv0:C,conv1:S,conv2:k,conv3:I,conv4:R,conv5:N,conv6:A,conv7:L,conv8:O}}if(i().length!==0)throw new Error("weights remaing after extract: "+i().length);return{params:f,paramMappings:s}}function Vg(r,t){var e=sn(r,t);function n(s){var u=e(s+"/sub",1),c=e(s+"/truediv",1);return{sub:u,truediv:c}}function o(s){var u=e(s+"/filters",4),c=e(s+"/bias",1);return{filters:u,bias:c}}function a(s){var u=o(s+"/conv"),c=n(s+"/bn");return{conv:u,bn:c}}var i=ai(e);return{extractConvParams:o,extractConvWithBatchNormParams:a,extractSeparableConvParams:i}}function zg(r,t){var e=[],n=Vg(r,e),o=n.extractConvParams,a=n.extractConvWithBatchNormParams,i=n.extractSeparableConvParams,s;if(t.withSeparableConvs){var u=t.filterSizes&&t.filterSizes.length||9;s={conv0:t.isFirstLayerConv2d?o("conv0"):i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:u>7?i("conv6"):void 0,conv7:u>8?i("conv7"):void 0,conv8:o("conv8")}}else s={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:o("conv8")};return jt(r,e),{params:s,paramMappings:e}}var _s;(function(r){r[r.XS=224]="XS",r[r.SM=320]="SM",r[r.MD=416]="MD",r[r.LG=608]="LG"})(_s||(_s={}));var ci=function(){function r(t){var e=t===void 0?{}:t,n=e.inputSize,o=e.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=n||416,this._scoreThreshold=o||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(r.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),r}(),Nc=function(r){re(t,r);function t(e){var n=r.call(this,"TinyYolov2")||this;return Lg(e),n._config=e,n}return Object.defineProperty(t.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"withClassScores",{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boxEncodingSize",{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),t.prototype.runTinyYolov2=function(e,n){var o=$t(e,n.conv0);return o=Le(o,[2,2],[2,2],"same"),o=$t(o,n.conv1),o=Le(o,[2,2],[2,2],"same"),o=$t(o,n.conv2),o=Le(o,[2,2],[2,2],"same"),o=$t(o,n.conv3),o=Le(o,[2,2],[2,2],"same"),o=$t(o,n.conv4),o=Le(o,[2,2],[2,2],"same"),o=$t(o,n.conv5),o=Le(o,[2,2],[1,1],"same"),o=$t(o,n.conv6),o=$t(o,n.conv7),mt(o,n.conv8,"valid",!1)},t.prototype.runMobilenet=function(e,n){var o=this.config.isFirstLayerConv2d?ui(mt(e,n.conv0,"valid",!1)):Yt(e,n.conv0);return o=Le(o,[2,2],[2,2],"same"),o=Yt(o,n.conv1),o=Le(o,[2,2],[2,2],"same"),o=Yt(o,n.conv2),o=Le(o,[2,2],[2,2],"same"),o=Yt(o,n.conv3),o=Le(o,[2,2],[2,2],"same"),o=Yt(o,n.conv4),o=Le(o,[2,2],[2,2],"same"),o=Yt(o,n.conv5),o=Le(o,[2,2],[1,1],"same"),o=n.conv6?Yt(o,n.conv6):o,o=n.conv7?Yt(o,n.conv7):o,mt(o,n.conv8,"valid",!1)},t.prototype.forwardInput=function(e,n){var o=this,a=this.params;if(!a)throw new Error("TinyYolov2 - load model before inference");return K(function(){var i=e.toBatchTensor(n,!1).toFloat();return i=o.config.meanRgb?mr(i,o.config.meanRgb):i,i=i.div(q(256)),o.config.withSeparableConvs?o.runMobilenet(i,a):o.runTinyYolov2(i,a)})},t.prototype.forward=function(e,n){return Q(this,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return o=this.forwardInput,[4,Ue(e)];case 1:return[4,o.apply(this,[a.sent(),n])];case 2:return[2,a.sent()]}})})},t.prototype.detect=function(e,n){return n===void 0&&(n={}),Q(this,void 0,void 0,function(){var o,a,i,s,u,c,l,h,f,p,d,g,v,m,x=this;return Z(this,function(b){switch(b.label){case 0:return o=new ci(n),a=o.inputSize,i=o.scoreThreshold,[4,Ue(e)];case 1:return s=b.sent(),[4,this.forwardInput(s,a)];case 2:return u=b.sent(),c=K(function(){return Pe(u)[0].expandDims()}),l={width:s.getInputWidth(0),height:s.getInputHeight(0)},[4,this.extractBoxes(c,s.getReshapedInputDimensions(0),i)];case 3:return h=b.sent(),u.dispose(),c.dispose(),f=h.map(function(y){return y.box}),p=h.map(function(y){return y.score}),d=h.map(function(y){return y.classScore}),g=h.map(function(y){return x.config.classes[y.label]}),v=sr(f.map(function(y){return y.rescale(a)}),p,this.config.iouThreshold,!0),m=v.map(function(y){return new oc(p[y],d[y],g[y],f[y],l)}),[2,m]}})})},t.prototype.getDefaultModelName=function(){return""},t.prototype.extractParamsFromWeigthMap=function(e){return zg(e,this.config)},t.prototype.extractParams=function(e){var n=this.config.filterSizes||t.DEFAULT_FILTER_SIZES,o=n?n.length:void 0;if(o!==7&&o!==8&&o!==9)throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found "+o+" filterSizes in config");return Ug(e,this.config,this.boxEncodingSize,n)},t.prototype.extractBoxes=function(e,n,o){return Q(this,void 0,void 0,function(){var a,i,s,u,c,l,h,f,p,d,g,v,m,x,b,y,w,C,S,k,I,R,N,A,L,O,B,V,U,W=this;return Z(this,function(G){switch(G.label){case 0:return a=n.width,i=n.height,s=Math.max(a,i),u=s/a,c=s/i,l=e.shape[1],h=this.config.anchors.length,f=K(function(){var H=e.reshape([l,l,h,W.boxEncodingSize]),j=H.slice([0,0,0,0],[l,l,h,4]),ee=H.slice([0,0,0,4],[l,l,h,1]),te=W.withClassScores?Gt(H.slice([0,0,0,5],[l,l,h,W.config.classes.length]),3):q(0);return[j,ee,te]}),p=f[0],d=f[1],g=f[2],v=[],[4,d.array()];case 1:return m=G.sent(),[4,p.array()];case 2:x=G.sent(),b=0,G.label=3;case 3:if(!(b<l))return[3,12];y=0,G.label=4;case 4:if(!(y<l))return[3,11];w=0,G.label=5;case 5:return w<h?(C=Ko(m[b][y][w][0]),!o||C>o?(S=(y+Ko(x[b][y][w][0]))/l*u,k=(b+Ko(x[b][y][w][1]))/l*c,I=Math.exp(x[b][y][w][2])*this.config.anchors[w].x/l*u,R=Math.exp(x[b][y][w][3])*this.config.anchors[w].y/l*c,N=S-I/2,A=k-R/2,L={row:b,col:y,anchor:w},this.withClassScores?[4,this.extractPredictedClass(g,L)]:[3,7]):[3,9]):[3,10];case 6:return U=G.sent(),[3,8];case 7:U={classScore:1,label:0},G.label=8;case 8:O=U,B=O.classScore,V=O.label,v.push(qe({box:new po(N,A,N+I,A+R),score:C,classScore:C*B,label:V},L)),G.label=9;case 9:return w++,[3,5];case 10:return y++,[3,4];case 11:return b++,[3,3];case 12:return p.dispose(),d.dispose(),g.dispose(),[2,v]}})})},t.prototype.extractPredictedClass=function(e,n){return Q(this,void 0,void 0,function(){var o,a,i,s;return Z(this,function(u){switch(u.label){case 0:return o=n.row,a=n.col,i=n.anchor,[4,e.array()];case 1:return s=u.sent(),[2,Array(this.config.classes.length).fill(0).map(function(c,l){return s[o][a][i][l]}).map(function(c,l){return{classScore:c,label:l}}).reduce(function(c,l){return c.classScore>l.classScore?c:l})]}})})},t.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],t}(qt),Gg=function(r){re(t,r);function t(e){e===void 0&&(e=!0);var n=this,o=Object.assign({},{withSeparableConvs:e,iouThreshold:Ng,classes:["face"]},e?{anchors:Pg,meanRgb:Mg}:{anchors:Fg,withClassScores:!0});return n=r.call(this,o)||this,n}return Object.defineProperty(t.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,n){return Q(this,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return[4,this.detect(e,n)];case 1:return o=a.sent(),[2,o.map(function(i){return new Mt(i.score,i.relativeBox,{width:i.imageWidth,height:i.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return this.withSeparableConvs?Bg:Og},t.prototype.extractParamsFromWeigthMap=function(e){return r.prototype.extractParamsFromWeigthMap.call(this,e)},t}(Nc),Hg=function(r){re(t,r);function t(){var e=r!==null&&r.apply(this,arguments)||this;return e._name="TinyFaceDetectorOptions",e}return t}(ci),gr=function(){function r(){}return r.prototype.then=function(t){return Q(this,void 0,void 0,function(){var e;return Z(this,function(n){switch(n.label){case 0:return e=t,[4,this.run()];case 1:return[2,e.apply(void 0,[n.sent()])]}})})},r.prototype.run=function(){return Q(this,void 0,void 0,function(){return Z(this,function(t){throw new Error("ComposableTask - run is not implemented")})})},r}();function go(r,t,e,n,o){return o===void 0&&(o=function(a){var i=a.alignedRect;return i}),Q(this,void 0,void 0,function(){var a,i,s,u,c;return Z(this,function(l){switch(l.label){case 0:return a=r.map(function(h){return Jm(h)?o(h):h.detection}),s=n,s?[3,5]:t instanceof Ee?[4,ni(t,a)]:[3,2];case 1:return u=l.sent(),[3,4];case 2:return[4,ti(t,a)];case 3:u=l.sent(),l.label=4;case 4:s=u,l.label=5;case 5:return i=s,[4,e(i)];case 6:return c=l.sent(),i.forEach(function(h){return h instanceof Ee&&h.dispose()}),[2,c]}})})}function li(r,t,e,n,o){return Q(this,void 0,void 0,function(){var a=this;return Z(this,function(i){return[2,go([r],t,function(s){return Q(a,void 0,void 0,function(){return Z(this,function(u){return[2,e(s[0])]})})},n,o)]})})}function qg(r){return K(function(){return ct(Pe(r,3).reverse(),3)})}var Tr=2,to=12;function jg(r,t){var e=mo(r,t),n=ri(r,t);function o(c,l){var h=Te(r(c));return t.push({paramPath:l}),h}function a(c,l,h){h===void 0&&(h=!1);var f=e(c[0],c[1],3,l+"/conv1"),p=o(c[1],l+"/prelu1_alpha"),d=e(c[1],c[2],3,l+"/conv2"),g=o(c[2],l+"/prelu2_alpha"),v=e(c[2],c[3],h?2:3,l+"/conv3"),m=o(c[3],l+"/prelu3_alpha");return{conv1:f,prelu1_alpha:p,conv2:d,prelu2_alpha:g,conv3:v,prelu3_alpha:m}}function i(){var c=a([3,10,16,32],"pnet"),l=e(32,2,1,"pnet/conv4_1"),h=e(32,4,1,"pnet/conv4_2");return qe(qe({},c),{conv4_1:l,conv4_2:h})}function s(){var c=a([3,28,48,64],"rnet",!0),l=n(576,128,"rnet/fc1"),h=o(128,"rnet/prelu4_alpha"),f=n(128,2,"rnet/fc2_1"),p=n(128,4,"rnet/fc2_2");return qe(qe({},c),{fc1:l,prelu4_alpha:h,fc2_1:f,fc2_2:p})}function u(){var c=a([3,32,64,64],"onet"),l=e(64,128,2,"onet/conv4"),h=o(128,"onet/prelu4_alpha"),f=n(1152,256,"onet/fc1"),p=o(256,"onet/prelu5_alpha"),d=n(256,2,"onet/fc2_1"),g=n(256,4,"onet/fc2_2"),v=n(256,10,"onet/fc2_3");return qe(qe({},c),{conv4:l,prelu4_alpha:h,fc1:f,prelu5_alpha:p,fc2_1:d,fc2_2:g,fc2_3:v})}return{extractPNetParams:i,extractRNetParams:s,extractONetParams:u}}function Kg(r){var t=Kt(r),e=t.extractWeights,n=t.getRemainingWeights,o=[],a=jg(e,o),i=a.extractPNetParams,s=a.extractRNetParams,u=a.extractONetParams,c=i(),l=s(),h=u();if(n().length!==0)throw new Error("weights remaing after extract: "+n().length);return{params:{pnet:c,rnet:l,onet:h},paramMappings:o}}function Xg(r,t){var e=sn(r,t);function n(l){var h=e(l+"/weights",4,l+"/filters"),f=e(l+"/bias",1);return{filters:h,bias:f}}function o(l){var h=e(l+"/weights",2),f=e(l+"/bias",1);return{weights:h,bias:f}}function a(l){return e(l,1)}function i(l){var h=n(l+"/conv1"),f=a(l+"/prelu1_alpha"),p=n(l+"/conv2"),d=a(l+"/prelu2_alpha"),g=n(l+"/conv3"),v=a(l+"/prelu3_alpha");return{conv1:h,prelu1_alpha:f,conv2:p,prelu2_alpha:d,conv3:g,prelu3_alpha:v}}function s(){var l=i("pnet"),h=n("pnet/conv4_1"),f=n("pnet/conv4_2");return qe(qe({},l),{conv4_1:h,conv4_2:f})}function u(){var l=i("rnet"),h=o("rnet/fc1"),f=a("rnet/prelu4_alpha"),p=o("rnet/fc2_1"),d=o("rnet/fc2_2");return qe(qe({},l),{fc1:h,prelu4_alpha:f,fc2_1:p,fc2_2:d})}function c(){var l=i("onet"),h=n("onet/conv4"),f=a("onet/prelu4_alpha"),p=o("onet/fc1"),d=a("onet/prelu5_alpha"),g=o("onet/fc2_1"),v=o("onet/fc2_2"),m=o("onet/fc2_3");return qe(qe({},l),{conv4:h,prelu4_alpha:f,fc1:p,prelu5_alpha:d,fc2_1:g,fc2_2:v,fc2_3:m})}return{extractPNetParams:s,extractRNetParams:u,extractONetParams:c}}function $g(r){var t=[],e=Xg(r,t),n=e.extractPNetParams,o=e.extractRNetParams,a=e.extractONetParams,i=n(),s=o(),u=a();return jt(r,t),{params:{pnet:i,rnet:s,onet:u},paramMappings:t}}function xa(r,t){var e=t[0],n=t[1];return{height:Math.floor(e*r),width:Math.floor(n*r)}}function Yg(r,t,e){for(var n=e[0],o=e[1],a=to/r,i=[],s=Math.min(n,o)*a,u=0;s>=12;)i.push(a*Math.pow(t,u)),s=s*t,u+=1;return i}var hi=function(r){re(t,r);function t(e,n,o,a){return r.call(this,{left:e,top:n,right:o,bottom:a},!0)||this}return t}(rn);function Fc(r){return K(function(){return Xe(Oe(r,q(127.5)),q(.0078125))})}function Vn(r,t){return K(function(){return ue(Ie(r),Xe(t,Xr(Ie(Xr(r)))))})}function fi(r,t,e){return e===void 0&&(e=!1),K(function(){var n=mt(r,t.conv1,"valid");return n=Vn(n,t.prelu1_alpha),n=Le(n,e?[2,2]:[3,3],[2,2],"same"),n=mt(n,t.conv2,"valid"),n=Vn(n,t.prelu2_alpha),n=e?n:Le(n,[3,3],[2,2],"valid"),n=mt(n,t.conv3,"valid"),n=Vn(n,t.prelu3_alpha),n})}function Jg(r,t){return K(function(){var e=fi(r,t,!0),n=mt(e,t.conv4_1,"valid"),o=lt(co(n,3),3),a=Gt(Oe(n,o),3),i=mt(e,t.conv4_2,"valid");return{prob:a,regions:i}})}function Qg(r,t){return K(function(){var e=xa(t,r.shape.slice(1)),n=e.height,o=e.width,a=Ga.resizeBilinear(r,[n,o]),i=Fc(a);return nn(i,[0,2,1,3])})}function Zg(r,t,e,n){for(var o=[],a=r.arraySync(),i=0;i<r.shape[0];i++)for(var s=0;s<r.shape[1];s++)a[i][s]>=n&&o.push(new ge(s,i));var u=o.map(function(c){var l=new po(Math.round((c.y*Tr+1)/e),Math.round((c.x*Tr+1)/e),Math.round((c.y*Tr+to)/e),Math.round((c.x*Tr+to)/e)),h=a[c.y][c.x],f=t.arraySync(),p=new hi(f[c.y][c.x][0],f[c.y][c.x][1],f[c.y][c.x][2],f[c.y][c.x][3]);return{cell:l,score:h,region:p}});return u}function ey(r,t,e,n,o){o.stage1=[];var a=t.map(function(f){return K(function(){var p={scale:f},d=Qg(r,f),g=Date.now(),v=Jg(d,n),m=v.prob,x=v.regions;p.pnet=Date.now()-g;var b=Pe(Pe(m,3)[1])[0],y=Pe(x)[0];return{scoresTensor:b,regionsTensor:y,scale:f,statsForScale:p}})}),i=a.map(function(f){var p=f.scoresTensor,d=f.regionsTensor,g=f.scale,v=f.statsForScale,m=Zg(p,d,g,e);if(p.dispose(),d.dispose(),!m.length)return o.stage1.push(v),[];var x=Date.now(),b=sr(m.map(function(y){return y.cell}),m.map(function(y){return y.score}),.5);return v.nms=Date.now()-x,v.numBoxes=b.length,o.stage1.push(v),b.map(function(y){return m[y]})}),s=i.reduce(function(f,p){return f.concat(p)},[]),u=[],c=[];if(s.length>0){var l=Date.now(),h=sr(s.map(function(f){return f.cell}),s.map(function(f){return f.score}),.7);o.stage1_nms=Date.now()-l,c=h.map(function(f){return s[f].score}),u=h.map(function(f){return s[f]}).map(function(f){var p=f.cell,d=f.region;return new po(p.left+d.left*p.width,p.top+d.top*p.height,p.right+d.right*p.width,p.bottom+d.bottom*p.height).toSquare().round()})}return{boxes:u,scores:c}}function Pc(r,t,e){var n=e.width,o=e.height;return Q(this,void 0,void 0,function(){var a,i,s,u=this;return Z(this,function(c){switch(c.label){case 0:return a=mn(r),[4,Promise.all(t.map(function(l){return Q(u,void 0,void 0,function(){var h,f,p,d,g,v,m,x;return Z(this,function(b){return h=l.padAtBorders(r.height,r.width),f=h.y,p=h.ey,d=h.x,g=h.ex,v=d-1,m=f-1,x=a.getImageData(v,m,g-v,p-m),[2,$e.isNodejs()?ei(x):createImageBitmap(x)]})})}))];case 1:return i=c.sent(),s=[],i.forEach(function(l){var h=vo({width:n,height:o}),f=mn(h);f.drawImage(l,0,0,n,o);for(var p=f.getImageData(0,0,n,o).data,d=[],g=0;g<p.length;g+=4)d.push(p[g+2]),d.push(p[g+1]),d.push(p[g]);s.push(d)}),[2,s.map(function(l){var h=K(function(){var f=nn(Je(l,[1,n,o,3]),[0,2,1,3]).toFloat();return Fc(f)});return h})]}})})}function ty(r,t){return K(function(){var e=fi(r,t),n=vt(e,[e.shape[0],t.fc1.weights.shape[0]]),o=kt(n,t.fc1),a=Vn(o,t.prelu4_alpha),i=kt(a,t.fc2_1),s=lt(co(i,1),1),u=Gt(Oe(i,s),1),c=kt(a,t.fc2_2),l=Pe(u,1)[1];return{scores:l,regions:c}})}function ny(r,t,e,n,o){return Q(this,void 0,void 0,function(){var a,i,s,u,c,l,h,f,p,d,g,v,m,x;return Z(this,function(b){switch(b.label){case 0:return a=Date.now(),[4,Pc(r,t,{width:24,height:24})];case 1:return i=b.sent(),o.stage2_extractImagePatches=Date.now()-a,a=Date.now(),s=i.map(function(y){var w=ty(y,n);return y.dispose(),w}),o.stage2_rnet=Date.now()-a,u=s.length>1?Fe(s.map(function(y){return y.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(y,w){return{score:y,idx:w}}).filter(function(y){return y.score>e}).map(function(y){var w=y.idx;return w}),p=f.map(function(y){return t[y]}),d=f.map(function(y){return c[y]}),g=[],v=[],p.length>0&&(a=Date.now(),m=sr(p,d,.7),o.stage2_nms=Date.now()-a,x=m.map(function(y){var w=s[f[y]].regions.arraySync();return new hi(w[0][0],w[0][1],w[0][2],w[0][3])}),v=m.map(function(y){return d[y]}),g=m.map(function(y,w){return p[y].calibrate(x[w])})),s.forEach(function(y){y.regions.dispose(),y.scores.dispose()}),[2,{boxes:g,scores:v}]}})})}function ry(r,t){return K(function(){var e=fi(r,t);e=Le(e,[2,2],[2,2],"same"),e=mt(e,t.conv4,"valid"),e=Vn(e,t.prelu4_alpha);var n=vt(e,[e.shape[0],t.fc1.weights.shape[0]]),o=kt(n,t.fc1),a=Vn(o,t.prelu5_alpha),i=kt(a,t.fc2_1),s=lt(co(i,1),1),u=Gt(Oe(i,s),1),c=kt(a,t.fc2_2),l=kt(a,t.fc2_3),h=Pe(u,1)[1];return{scores:h,regions:c,points:l}})}function oy(r,t,e,n,o){return Q(this,void 0,void 0,function(){var a,i,s,u,c,l,h,f,p,d,g,v,m,x,b;return Z(this,function(y){switch(y.label){case 0:return a=Date.now(),[4,Pc(r,t,{width:48,height:48})];case 1:return i=y.sent(),o.stage3_extractImagePatches=Date.now()-a,a=Date.now(),s=i.map(function(w){var C=ry(w,n);return w.dispose(),C}),o.stage3_onet=Date.now()-a,u=s.length>1?Fe(s.map(function(w){return w.scores})):s[0].scores,h=(l=Array).from,[4,u.data()];case 2:return c=h.apply(l,[y.sent()]),u.dispose(),f=c.map(function(w,C){return{score:w,idx:C}}).filter(function(w){return w.score>e}).map(function(w){var C=w.idx;return C}),p=f.map(function(w){var C=s[w].regions.arraySync();return new hi(C[0][0],C[0][1],C[0][2],C[0][3])}),d=f.map(function(w,C){return t[w].calibrate(p[C])}),g=f.map(function(w){return c[w]}),v=[],m=[],x=[],d.length>0&&(a=Date.now(),b=sr(d,g,.7,!1),o.stage3_nms=Date.now()-a,v=b.map(function(w){return d[w]}),m=b.map(function(w){return g[w]}),x=b.map(function(w,C){return Array(5).fill(0).map(function(S,k){var I=s[w].points.arraySync();return new ge(I[0][k]*(v[C].width+1)+v[C].left,I[0][k+5]*(v[C].height+1)+v[C].top)})})),s.forEach(function(w){w.regions.dispose(),w.scores.dispose(),w.points.dispose()}),[2,{boxes:v,scores:m,points:x}]}})})}var ay=function(r){re(t,r);function t(){return r.call(this,"Mtcnn")||this}return t.prototype.load=function(e){return Q(this,void 0,void 0,function(){return Z(this,function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,r.prototype.load.call(this,e)]})})},t.prototype.loadFromDisk=function(e){return Q(this,void 0,void 0,function(){return Z(this,function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,r.prototype.loadFromDisk.call(this,e)]})})},t.prototype.forwardInput=function(e,n){return n===void 0&&(n={}),Q(this,void 0,void 0,function(){var o,a,i,s,u,c,l,h,f,p,d,g,v,m,x,b,y,w,C,S,k;return Z(this,function(I){switch(I.label){case 0:if(o=this.params,!o)throw new Error("Mtcnn - load model before inference");if(a=e.canvases[0],!a)throw new Error("Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.");return i={},s=Date.now(),u=K(function(){return qg(lt($a.fromPixels(a)).toFloat())}),c=function(R){return u.dispose(),i.total=Date.now()-s,R},l=u.shape.slice(1),h=l[0],f=l[1],p=new Ac(n),d=p.minFaceSize,g=p.scaleFactor,v=p.maxNumScales,m=p.scoreThresholds,x=p.scaleSteps,b=(x||Yg(d,g,[h,f])).filter(function(R){var N=xa(R,[h,f]);return Math.min(N.width,N.height)>to}).slice(0,v),i.scales=b,i.pyramid=b.map(function(R){return xa(R,[h,f])}),y=Date.now(),[4,ey(u,b,m[0],o.pnet,i)];case 1:return w=I.sent(),i.total_stage1=Date.now()-y,w.boxes.length?(i.stage2_numInputBoxes=w.boxes.length,y=Date.now(),[4,ny(a,w.boxes,m[1],o.rnet,i)]):[2,c({results:[],stats:i})];case 2:return C=I.sent(),i.total_stage2=Date.now()-y,C.boxes.length?(i.stage3_numInputBoxes=C.boxes.length,y=Date.now(),[4,oy(a,C.boxes,m[2],o.onet,i)]):[2,c({results:[],stats:i})];case 3:return S=I.sent(),i.total_stage3=Date.now()-y,k=S.boxes.map(function(R,N){return ii(Qa({},new Mt(S.scores[N],new Ja(R.left/f,R.top/h,R.width/f,R.height/h),{height:h,width:f})),new Pm(S.points[N].map(function(A){return A.sub(new ge(R.left,R.top)).div(new ge(R.width,R.height))}),{width:R.width,height:R.height}))}),[2,c({results:k,stats:i})]}})})},t.prototype.forward=function(e,n){return n===void 0&&(n={}),Q(this,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return o=this.forwardInput,[4,Ue(e)];case 1:return[4,o.apply(this,[a.sent(),n])];case 2:return[2,a.sent().results]}})})},t.prototype.forwardWithStats=function(e,n){return n===void 0&&(n={}),Q(this,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return o=this.forwardInput,[4,Ue(e)];case 1:return[2,o.apply(this,[a.sent(),n])]}})})},t.prototype.getDefaultModelName=function(){return"mtcnn_model"},t.prototype.extractParamsFromWeigthMap=function(e){return $g(e)},t.prototype.extractParams=function(e){return Kg(e)},t}(qt),iy=.4,sy=[new ge(1.603231,2.094468),new ge(6.041143,7.080126),new ge(2.882459,3.518061),new ge(4.266906,5.178857),new ge(9.041765,10.66308)],uy=[117.001,114.697,97.404],cy=function(r){re(t,r);function t(){var e=this,n={withSeparableConvs:!0,iouThreshold:iy,classes:["face"],anchors:sy,meanRgb:uy,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return e=r.call(this,n)||this,e}return Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,n){return Q(this,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return[4,this.detect(e,n)];case 1:return o=a.sent(),[2,o.map(function(i){return new Mt(i.score,i.relativeBox,{width:i.imageWidth,height:i.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},t.prototype.extractParamsFromWeigthMap=function(e){return r.prototype.extractParamsFromWeigthMap.call(this,e)},t}(Nc),Ye={ssdMobilenetv1:new Tc,tinyFaceDetector:new cy,tinyYolov2:new Gg,mtcnn:new ay,faceLandmark68Net:new Ec,faceLandmark68TinyNet:new lg,faceRecognitionNet:new gg,faceExpressionNet:new Ym,ageGenderNet:new ig},Mc=function(r){re(t,r);function t(e,n,o){var a=r.call(this)||this;return a.parentTask=e,a.input=n,a.extractedFaces=o,a}return t}(gr),pi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o=this;return Z(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),[4,go(e,this.input,function(i){return Q(o,void 0,void 0,function(){return Z(this,function(s){switch(s.label){case 0:return[4,Promise.all(i.map(function(u){return Ye.faceExpressionNet.predictExpressions(u)}))];case 1:return[2,s.sent()]}})})},this.extractedFaces)];case 2:return n=a.sent(),[2,e.map(function(i,s){return wc(i,n[s])})]}})})},t.prototype.withAgeAndGender=function(){return new gi(this,this.input)},t}(Mc),di=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n;return Z(this,function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return e=o.sent(),e?[4,li(e,this.input,function(a){return Ye.faceExpressionNet.predictExpressions(a)},this.extractedFaces)]:[2];case 2:return n=o.sent(),[2,wc(e,n)]}})})},t.prototype.withAgeAndGender=function(){return new yi(this,this.input)},t}(Mc),vi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new xi(this,this.input)},t.prototype.withFaceDescriptors=function(){return new wi(this,this.input)},t}(pi),mi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new bi(this,this.input)},t.prototype.withFaceDescriptor=function(){return new Ci(this,this.input)},t}(di),Oc=function(r){re(t,r);function t(e,n,o){var a=r.call(this)||this;return a.parentTask=e,a.input=n,a.extractedFaces=o,a}return t}(gr),gi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o=this;return Z(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),[4,go(e,this.input,function(i){return Q(o,void 0,void 0,function(){return Z(this,function(s){switch(s.label){case 0:return[4,Promise.all(i.map(function(u){return Ye.ageGenderNet.predictAgeAndGender(u)}))];case 1:return[2,s.sent()]}})})},this.extractedFaces)];case 2:return n=a.sent(),[2,e.map(function(i,s){var u=n[s],c=u.age,l=u.gender,h=u.genderProbability;return Sc(Dc(i,l,h),c)})]}})})},t.prototype.withFaceExpressions=function(){return new pi(this,this.input)},t}(Oc),yi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o,a,i;return Z(this,function(s){switch(s.label){case 0:return[4,this.parentTask];case 1:return e=s.sent(),e?[4,li(e,this.input,function(u){return Ye.ageGenderNet.predictAgeAndGender(u)},this.extractedFaces)]:[2];case 2:return n=s.sent(),o=n.age,a=n.gender,i=n.genderProbability,[2,Sc(Dc(e,a,i),o)]}})})},t.prototype.withFaceExpressions=function(){return new di(this,this.input)},t}(Oc),xi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new vi(this,this.input)},t.prototype.withFaceDescriptors=function(){return new wi(this,this.input)},t}(gi),bi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new mi(this,this.input)},t.prototype.withFaceDescriptor=function(){return new Ci(this,this.input)},t}(yi),Bc=function(r){re(t,r);function t(e,n){var o=r.call(this)||this;return o.parentTask=e,o.input=n,o}return t}(gr),wi=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n;return Z(this,function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return e=o.sent(),[4,go(e,this.input,function(a){return Promise.all(a.map(function(i){return Ye.faceRecognitionNet.computeFaceDescriptor(i)}))},null,function(a){return a.landmarks.align(null,{useDlibAlignment:!0})})];case 2:return n=o.sent(),[2,n.map(function(a,i){return kc(e[i],a)})]}})})},t.prototype.withFaceExpressions=function(){return new vi(this,this.input)},t.prototype.withAgeAndGender=function(){return new xi(this,this.input)},t}(Bc),Ci=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n;return Z(this,function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return e=o.sent(),e?[4,li(e,this.input,function(a){return Ye.faceRecognitionNet.computeFaceDescriptor(a)},null,function(a){return a.landmarks.align(null,{useDlibAlignment:!0})})]:[2];case 2:return n=o.sent(),[2,kc(e,n)]}})})},t.prototype.withFaceExpressions=function(){return new mi(this,this.input)},t.prototype.withAgeAndGender=function(){return new bi(this,this.input)},t}(Bc),Lc=function(r){re(t,r);function t(e,n,o){var a=r.call(this)||this;return a.parentTask=e,a.input=n,a.useTinyLandmarkNet=o,a}return Object.defineProperty(t.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?Ye.faceLandmark68TinyNet:Ye.faceLandmark68Net},enumerable:!0,configurable:!0}),t}(gr),ly=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o,a,i,s=this;return Z(this,function(u){switch(u.label){case 0:return[4,this.parentTask];case 1:return e=u.sent(),n=e.map(function(c){return c.detection}),this.input instanceof Ee?[4,ni(this.input,n)]:[3,3];case 2:return a=u.sent(),[3,5];case 3:return[4,ti(this.input,n)];case 4:a=u.sent(),u.label=5;case 5:return o=a,[4,Promise.all(o.map(function(c){return s.landmarkNet.detectLandmarks(c)}))];case 6:return i=u.sent(),o.forEach(function(c){return c instanceof Ee&&c.dispose()}),[2,e.map(function(c,l){return ii(c,i[l])})]}})})},t.prototype.withFaceExpressions=function(){return new vi(this,this.input)},t.prototype.withAgeAndGender=function(){return new xi(this,this.input)},t.prototype.withFaceDescriptors=function(){return new wi(this,this.input)},t}(Lc),hy=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o,a,i;return Z(this,function(s){switch(s.label){case 0:return[4,this.parentTask];case 1:return e=s.sent(),e?(n=e.detection,this.input instanceof Ee?[4,ni(this.input,[n])]:[3,3]):[2];case 2:return a=s.sent(),[3,5];case 3:return[4,ti(this.input,[n])];case 4:a=s.sent(),s.label=5;case 5:return o=a,[4,this.landmarkNet.detectLandmarks(o[0])];case 6:return i=s.sent(),o.forEach(function(u){return u instanceof Ee&&u.dispose()}),[2,ii(e,i)]}})})},t.prototype.withFaceExpressions=function(){return new mi(this,this.input)},t.prototype.withAgeAndGender=function(){return new bi(this,this.input)},t.prototype.withFaceDescriptor=function(){return new Ci(this,this.input)},t}(Lc),Wc=function(r){re(t,r);function t(e,n){n===void 0&&(n=new gn);var o=r.call(this)||this;return o.input=e,o.options=n,o}return t}(gr),Uc=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n,o,a;return Z(this,function(i){switch(i.label){case 0:return e=this,n=e.input,o=e.options,o instanceof Ac?[4,Ye.mtcnn.forward(n,o)]:[3,2];case 1:return[2,i.sent().map(function(s){return s.detection})];case 2:if(a=o instanceof Hg?function(s){return Ye.tinyFaceDetector.locateFaces(s,o)}:o instanceof gn?function(s){return Ye.ssdMobilenetv1.locateFaces(s,o)}:o instanceof ci?function(s){return Ye.tinyYolov2.locateFaces(s,o)}:null,!a)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,a(n)]}})})},t.prototype.runAndExtendWithFaceDetections=function(){var e=this;return new Promise(function(n){return Q(e,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return[4,this.run()];case 1:return o=a.sent(),[2,n(o.map(function(i){return Qa({},i)}))]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new ly(this.runAndExtendWithFaceDetections(),this.input,e)},t.prototype.withFaceExpressions=function(){return new pi(this.runAndExtendWithFaceDetections(),this.input)},t.prototype.withAgeAndGender=function(){return new gi(this.runAndExtendWithFaceDetections(),this.input)},t}(Wc),fy=function(r){re(t,r);function t(){return r!==null&&r.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,n;return Z(this,function(o){switch(o.label){case 0:return[4,new Uc(this.input,this.options)];case 1:return e=o.sent(),n=e[0],e.forEach(function(a){a.score>n.score&&(n=a)}),[2,n]}})})},t.prototype.runAndExtendWithFaceDetection=function(){var e=this;return new Promise(function(n){return Q(e,void 0,void 0,function(){var o;return Z(this,function(a){switch(a.label){case 0:return[4,this.run()];case 1:return o=a.sent(),[2,n(o?Qa({},o):void 0)]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new hy(this.runAndExtendWithFaceDetection(),this.input,e)},t.prototype.withFaceExpressions=function(){return new di(this.runAndExtendWithFaceDetection(),this.input)},t.prototype.withAgeAndGender=function(){return new yi(this.runAndExtendWithFaceDetection(),this.input)},t}(Wc);function py(r,t){return t===void 0&&(t=new gn),new fy(r,t)}function dy(r,t){return t===void 0&&(t=new gn),new Uc(r,t)}function Vc(r,t){if(r.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var e=Array.from(r),n=Array.from(t);return Math.sqrt(e.map(function(o,a){return o-n[a]}).reduce(function(o,a){return o+Math.pow(a,2)},0))}(function(){function r(t,e){e===void 0&&(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 o=1,a=function(){return"person "+o++};this._labeledDescriptors=n.map(function(i){if(i instanceof kr)return i;if(i instanceof Float32Array)return new kr(a(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new kr(a(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}return Object.defineProperty(r.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),r.prototype.computeMeanDistance=function(t,e){return e.map(function(n){return Vc(n,t)}).reduce(function(n,o){return n+o},0)/(e.length||1)},r.prototype.matchDescriptor=function(t){var e=this;return this.labeledDescriptors.map(function(n){var o=n.descriptors,a=n.label;return new ys(a,e.computeMeanDistance(t,o))}).reduce(function(n,o){return n.distance<o.distance?n:o})},r.prototype.findBestMatch=function(t){var e=this.matchDescriptor(t);return e.distance<this.distanceThreshold?e:new ys("unknown",e.distance)},r.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(function(t){return t.toJSON()})}},r.fromJSON=function(t){var e=t.labeledDescriptors.map(function(n){return kr.fromJSON(n)});return new r(e,t.distanceThreshold)},r})();const Yo="https://cdn.jsdelivr.net/npm/@vladmandic/[email protected]/model",my=()=>{const[r,t]=rt.useState(!1),[e,n]=rt.useState(!1),[o,a]=rt.useState(null),i=rt.useRef(!1),s=rt.useRef(!1),u=rt.useRef(null),c=rt.useCallback(async()=>
3828{if(s.current||r)return!0;if(u.current)return u.current;i.current=!0,n(!0),a(null);const v=(async()=>{try{return console.log("🔄 Cargando modelos de face-api.js..."),await Promise.all([Ye.ssdMobilenetv1.loadFromUri(Yo),Ye.faceLandmark68Net.loadFromUri(Yo),Ye.faceRecognitionNet.loadFromUri(Yo)]),console.log("✅ Modelos de face-api.js cargados correctamente"),s.current=!0,t(!0),!0}catch(m){return console.error("❌ Error cargando modelos de face-api.js:",m),s.current=!1,t(!1),a("Error cargando modelos de reconocimiento facial"),!1}finally{n(!1),i.current=!1,u.current=null}})();return u.current=v,v},[r]),l=rt.useCallback(async v=>{if(!s.current&&!await c())return console.warn("⚠️ Modelos no cargados"),null;try{const m=await py(v,new gn({minConfidence:.65})).withFaceLandmarks().withFaceDescriptor();return m?(console.log("✅ Rostro detectado"),m.descriptor):(console.warn("⚠️ No se detectó ningún rostro"),null)}catch(m){return console.error("❌ Error detectando rostro:",m),null}},[c]),h=rt.useCallback(async v=>{if(!s.current&&!await c())return console.warn("⚠️ Modelos no cargados"),[];try{const m=await dy(v,new gn({minConfidence:.65})).withFaceLandmarks().withFaceDescriptors();return m.length>0?console.log(`✅ ${m.length} rostro(s) detectado(s)`):console.warn("⚠️ No se detectó ningún rostro"),m.map(x=>({descriptor:x.descriptor,score:x.detection.score,box:{x:x.detection.box.x,y:x.detection.box.y,width:x.detection.box.width,height:x.detection.box.height}}))}catch(m){return console.error("❌ Error detectando rostros:",m),[]}},[c]),f=rt.useCallback(async v=>(await h(v)).map(x=>x.descriptor),[h]),p=rt.useCallback(async v=>{if(!s.current&&!await c())return console.warn("⚠️ Modelos no cargados"),null;try{console.log("🔄 Cargando imagen para detección:",v);const m=await fetch(v,{mode:"cors",credentials:"omit"});if(!m.ok)throw new Error(`HTTP error: ${m.status}`);const x=await m.blob(),b=URL.createObjectURL(x),y=new Image;await new Promise((k,I)=>{y.onload=()=>{console.log("✅ Imagen cargada:",y.width,"x",y.height),k()},y.onerror=R=>{console.error("❌ Error cargando imagen:",R),I(new Error("Error cargando imagen"))},y.src=b});const w=document.createElement("canvas");w.width=y.width,w.height=y.height;const C=w.getContext("2d");if(!C)throw URL.revokeObjectURL(b),new Error("No se pudo crear contexto de canvas");return C.drawImage(y,0,0),URL.revokeObjectURL(b),await l(w)}catch(m){return console.error("❌ Error procesando imagen:",m),null}},[c,l]),d=rt.useCallback(async v=>{if(!s.current&&!await c())return console.warn("⚠️ Modelos no cargados"),[];const m=[];for(const x of v){const b=await p(x);b&&m.push(b)}return m},[c,p]),g=rt.useCallback((v,m)=>Vc(v,m),[]);return{isModelLoaded:r,isLoading:e,error:o,loadModels:c,detectFaceFromImage:p,detectFaceFromElement:l,detectFacesFromElement:f,detectFaceDetailsFromElement:h,detectMultipleFaces:d,compareFaces:g}};export{my as u};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.