mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-08 10:56:15 -08:00
- Removed the assignment of Artplayer to the global window object in index.js of the artplayer package. - Eliminated the window export for the template plugin in index.js, streamlining the code and reducing global scope pollution.
8 lines
883 KiB
JavaScript
8 lines
883 KiB
JavaScript
/*!
|
|
* artplayer-plugin-danmuku-mask.js v1.0.1
|
|
* Github: https://github.com/zhw2590582/ArtPlayer
|
|
* (c) 2017-2026 Harvey Zhao
|
|
* Released under the MIT License.
|
|
*/
|
|
!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.ArtplayerPluginDanmukuMask=t(),define(function(){return t.ArtplayerPluginDanmukuMask})):(e="undefined"!==typeof globalThis?globalThis:e||self).ArtplayerPluginDanmukuMask=t()}(this,function(){"use strict";function e(e,t){for(var n=0;n<t.length;n++){const r=t[n];if("string"!==typeof r&&!Array.isArray(r))for(const t in r)if("default"!==t&&!(t in e)){const n=Object.getOwnPropertyDescriptor(r,t);n&&Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}class t{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class n{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,a,s){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function a(e,t,n){return Math.max(e,Math.min(t,n))}function s(e){return e%2===0?e:e+1}function o(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function i(e,t){if(!e)throw new Error("string"===typeof t?t:t())}function u(e,t,n=""){i(d(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function l(e){i(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function c(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function d(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function p(e){return e%1===0}function h(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function f(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function m(e,t=e=>0,n,r){return new Promise((a,s)=>{let o=0;const i=()=>{if(e())return void a();o++;const u=t(o);null!=n&&o>=n?s():null!=r?r(i,u):setTimeout(i,u)};i()})}function g(e,t){let n=1,r=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)n*=e[s];else if(-1===e[s]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${s}`);r=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function y(e,t){const n=t.length;return i((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),i(e.every(e=>p(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function b(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:y(t,e).sort();let o=0;for(let i=0;i<e.length;++i){if(null!=s){if(s[o]===i&&1!==e[i])throw new Error(`Can't squeeze axis ${i} since its dim '${e[i]}' is not 1`);(null==s[o]||s[o]>i)&&1===e[i]&&(n.push(e[i]),r.push(i)),s[o]<=i&&o++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function x(e,t){return v(e,t)}function v(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function w(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function k(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function I(e){return"string"===typeof e||e instanceof String}function N(e){return Array.isArray(e)?N(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"===typeof e?"float32":I(e)?"string":function(e){return"boolean"===typeof e}(e)?"bool":"float32"}function S(e){return!!(e&&e.constructor&&e.call&&e.apply)}function T(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function C(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function $(e,t,n,r=!1){const a=new Array;if(1===t.length){const s=t[0]*(r?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],o=t.slice(1),i=o.reduce((e,t)=>e*t)*(r?2:1);for(let t=0;t<s;t++)a[t]=$(e+t*i,o,n,r)}return a}function E(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce((e,t)=>e*t)*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return $(0,e,t,n)}function R(e,t){const n=_(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function _(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function A(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return E(e,new Float32Array(n));if("int32"===t)return E(e,new Int32Array(n));if("bool"===t)return E(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function O(e){e.forEach(t=>{i(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function F(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let a=0;a<e.length-1;++a)r+=n[a]*e[a];return r}function D(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let a=0;a<r.length-1;++a)r[a]=Math.floor(e/n[a]),e-=r[a]*n[a];return r[r.length-1]=e,r}function M(e){return e&&e.then&&"function"===typeof e.then}const P="tfjsflags";class L{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=B,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(M(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if("undefined"===typeof this.global||"undefined"===typeof this.global.location||"undefined"===typeof this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(P in e){e[P].split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)})}}}function B(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}function V(){return z}let W,z=null;function U(){if(null==W){let e;if("undefined"!==typeof window)e=window;else if("undefined"!==typeof global)e=global;else if("undefined"!==typeof process)e=process;else{if("undefined"===typeof self)throw new Error("Could not find a global object");e=self}W=e}return W}function G(e,t){const n=function(){const e=U();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const H="Abs",j="Acos",q="Acosh",K="Add",X="AddN",Y="All",Q="Any",Z="ArgMax",J="ArgMin",ee="Asin",te="Asinh",ne="Atan",re="Atanh",ae="Atan2",se="AvgPool",oe="AvgPoolGrad",ie="AvgPool3D",ue="AvgPool3DGrad",le="BatchMatMul",ce="BatchToSpaceND",de="Bincount",pe="BitwiseAnd",he="BroadcastArgs",fe="Cast",me="Ceil",ge="ClipByValue",ye="Complex",be="ComplexAbs",xe="Concat",ve="Conv2D",we="Conv2DBackpropFilter",ke="Conv2DBackpropInput",Ie="Conv3D",Ne="Conv3DBackpropFilterV2",Se="Conv3DBackpropInputV2",Te="Cos",Ce="Cosh",$e="Cumprod",Ee="Cumsum",Re="CropAndResize",_e="DenseBincount",Ae="DepthToSpace",Oe="DepthwiseConv2dNative",Fe="DepthwiseConv2dNativeBackpropFilter",De="DepthwiseConv2dNativeBackpropInput",Me="Diag",Pe="Dilation2D",Le="Dilation2DBackpropInput",Be="Dilation2DBackpropFilter",Ve="Draw",We="RealDiv",ze="Einsum",Ue="Elu",Ge="EluGrad",He="Erf",je="Equal",qe="Exp",Ke="ExpandDims",Xe="Expm1",Ye="FFT",Qe="Fill",Ze="FlipLeftRight",Je="Floor",et="FloorDiv",tt="FusedBatchNorm",nt="GatherV2",rt="GatherNd",at="Greater",st="GreaterEqual",ot="Identity",it="IFFT",ut="Imag",lt="IsFinite",ct="IsInf",dt="IsNan",pt="LeakyRelu",ht="Less",ft="LessEqual",mt="LinSpace",gt="Log",yt="Log1p",bt="LogicalAnd",xt="LogicalNot",vt="LogicalOr",wt="LRN",kt="LRNGrad",It="Max",Nt="Maximum",St="MaxPool",Tt="MaxPoolGrad",Ct="MaxPool3D",$t="MaxPool3DGrad",Et="MaxPoolWithArgmax",Rt="Mean",_t="Min",At="Minimum",Ot="MirrorPad",Ft="Mod",Dt="Multinomial",Mt="Multiply",Pt="Neg",Lt="NotEqual",Bt="NonMaxSuppressionV3",Vt="NonMaxSuppressionV4",Wt="NonMaxSuppressionV5",zt="OnesLike",Ut="OneHot",Gt="Pack",Ht="PadV2",jt="Pow",qt="Prelu",Kt="Prod",Xt="RaggedGather",Yt="RaggedRange",Qt="RaggedTensorToTensor",Zt="Range",Jt="Real",en="Reciprocal",tn="Relu",nn="Reshape",rn="ResizeNearestNeighbor",an="ResizeNearestNeighborGrad",sn="ResizeBilinear",on="ResizeBilinearGrad",un="Relu6",ln="Reverse",cn="Round",dn="Rsqrt",pn="ScatterNd",hn="TensorScatterUpdate",fn="SearchSorted",mn="Select",gn="Selu",yn="Slice",bn="Sin",xn="Sinh",vn="Sign",wn="Sigmoid",kn="Softplus",In="Sqrt",Nn="Sum",Sn="SpaceToBatchND",Tn="SplitV",Cn="Softmax",$n="SparseFillEmptyRows",En="SparseReshape",Rn="SparseSegmentMean",_n="SparseSegmentSum",An="SparseToDense",On="SquaredDifference",Fn="Square",Dn="StaticRegexReplace",Mn="StridedSlice",Pn="StringNGrams",Ln="StringSplit",Bn="StringToHashBucketFast",Vn="Sub",Wn="Tan",zn="Tanh",Un="Tile",Gn="TopK",Hn="Transform",jn="Transpose",qn="Unique",Kn="Unpack",Xn="UnsortedSegmentSum",Yn="ZerosLike",Qn="Step",Zn="FromPixels",Jn="RotateWithOffset",er="_FusedMatMul",tr="FusedConv2D",nr="FusedDepthwiseConv2D";function rr(...e){V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(...e)}const ar=G("kernelRegistry",()=>new Map),sr=G("gradRegistry",()=>new Map);function or(e,t){const n=cr(e,t);return ar.get(n)}function ir(e){return sr.get(e)}function ur(e){const t=ar.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function lr(e){const{kernelName:t,backendName:n}=e,r=cr(t,n);ar.has(r)&&rr(`The kernel '${t}' for backend '${n}' is already registered`),ar.set(r,e)}function cr(e,t){return`${t}_${e}`}function dr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var pr,hr,fr="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{};function mr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function gr(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var yr=function(){if(hr)return pr;hr=1,pr=t;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(N){}function t(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function n(e){return!0===(e&&e.__isLong__)}t.prototype.__isLong__,Object.defineProperty(t.prototype,"__isLong__",{value:!0}),t.isLong=n;var r={},a={};function s(e,t){var n,s,o;return t?(o=0<=(e>>>=0)&&e<256)&&(s=a[e])?s:(n=i(e,(0|e)<0?-1:0,!0),o&&(a[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(s=r[e])?s:(n=i(e,e<0?-1:0,!1),o&&(r[e]=n),n)}function o(e,t){if(isNaN(e))return t?g:m;if(t){if(e<0)return g;if(e>=p)return w}else{if(e<=-h)return k;if(e+1>=h)return v}return e<0?o(-e,t).neg():i(e%d|0,e/d|0,t)}function i(e,n,r){return new t(e,n,r)}t.fromInt=s,t.fromNumber=o,t.fromBits=i;var u=Math.pow;function l(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return m;if("number"===typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return l(e.substring(1),t,n).neg();for(var a=o(u(n,8)),s=m,i=0;i<e.length;i+=8){var c=Math.min(8,e.length-i),d=parseInt(e.substring(i,i+c),n);if(c<8){var p=o(u(n,c));s=s.mul(p).add(o(d))}else s=(s=s.mul(a)).add(o(d))}return s.unsigned=t,s}function c(e,t){return"number"===typeof e?o(e,t):"string"===typeof e?l(e,t):i(e.low,e.high,"boolean"===typeof t?t:e.unsigned)}t.fromString=l,t.fromValue=c;var d=4294967296,p=d*d,h=p/2,f=s(1<<24),m=s(0);t.ZERO=m;var g=s(0,!0);t.UZERO=g;var y=s(1);t.ONE=y;var b=s(1,!0);t.UONE=b;var x=s(-1);t.NEG_ONE=x;var v=i(-1,2147483647,!1);t.MAX_VALUE=v;var w=i(-1,-1,!0);t.MAX_UNSIGNED_VALUE=w;var k=i(0,-2147483648,!1);t.MIN_VALUE=k;var I=t.prototype;return I.toInt=function(){return this.unsigned?this.low>>>0:this.low},I.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},I.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(k)){var t=o(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var a=o(u(e,6),this.unsigned),s=this,i="";;){var l=s.div(a),c=(s.sub(l.mul(a)).toInt()>>>0).toString(e);if((s=l).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},I.getHighBits=function(){return this.high},I.getHighBitsUnsigned=function(){return this.high>>>0},I.getLowBits=function(){return this.low},I.getLowBitsUnsigned=function(){return this.low>>>0},I.getNumBitsAbs=function(){if(this.isNegative())return this.eq(k)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},I.isZero=function(){return 0===this.high&&0===this.low},I.eqz=I.isZero,I.isNegative=function(){return!this.unsigned&&this.high<0},I.isPositive=function(){return this.unsigned||this.high>=0},I.isOdd=function(){return 1===(1&this.low)},I.isEven=function(){return 0===(1&this.low)},I.equals=function(e){return n(e)||(e=c(e)),(this.unsigned===e.unsigned||this.high>>>31!==1||e.high>>>31!==1)&&(this.high===e.high&&this.low===e.low)},I.eq=I.equals,I.notEquals=function(e){return!this.eq(e)},I.neq=I.notEquals,I.ne=I.notEquals,I.lessThan=function(e){return this.comp(e)<0},I.lt=I.lessThan,I.lessThanOrEqual=function(e){return this.comp(e)<=0},I.lte=I.lessThanOrEqual,I.le=I.lessThanOrEqual,I.greaterThan=function(e){return this.comp(e)>0},I.gt=I.greaterThan,I.greaterThanOrEqual=function(e){return this.comp(e)>=0},I.gte=I.greaterThanOrEqual,I.ge=I.greaterThanOrEqual,I.compare=function(e){if(n(e)||(e=c(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},I.comp=I.compare,I.negate=function(){return!this.unsigned&&this.eq(k)?k:this.not().add(y)},I.neg=I.negate,I.add=function(e){n(e)||(e=c(e));var t=this.high>>>16,r=65535&this.high,a=this.low>>>16,s=65535&this.low,o=e.high>>>16,u=65535&e.high,l=e.low>>>16,d=0,p=0,h=0,f=0;return h+=(f+=s+(65535&e.low))>>>16,p+=(h+=a+l)>>>16,d+=(p+=r+u)>>>16,d+=t+o,i((h&=65535)<<16|(f&=65535),(d&=65535)<<16|(p&=65535),this.unsigned)},I.subtract=function(e){return n(e)||(e=c(e)),this.add(e.neg())},I.sub=I.subtract,I.multiply=function(t){if(this.isZero())return m;if(n(t)||(t=c(t)),e)return i(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return m;if(this.eq(k))return t.isOdd()?k:m;if(t.eq(k))return this.isOdd()?k:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(f)&&t.lt(f))return o(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,a=65535&this.high,s=this.low>>>16,u=65535&this.low,l=t.high>>>16,d=65535&t.high,p=t.low>>>16,h=65535&t.low,g=0,y=0,b=0,x=0;return b+=(x+=u*h)>>>16,y+=(b+=s*h)>>>16,b&=65535,y+=(b+=u*p)>>>16,g+=(y+=a*h)>>>16,y&=65535,g+=(y+=s*p)>>>16,y&=65535,g+=(y+=u*d)>>>16,g+=r*h+a*p+s*d+u*l,i((b&=65535)<<16|(x&=65535),(g&=65535)<<16|(y&=65535),this.unsigned)},I.mul=I.multiply,I.divide=function(t){if(n(t)||(t=c(t)),t.isZero())throw Error("division by zero");var r,a,s;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?i((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?g:m;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return g;if(t.gt(this.shru(1)))return b;s=g}else{if(this.eq(k))return t.eq(y)||t.eq(x)?k:t.eq(k)?y:(r=this.shr(1).div(t).shl(1)).eq(m)?t.isNegative()?y:x:(a=this.sub(t.mul(r)),s=r.add(a.div(t)));if(t.eq(k))return this.unsigned?g:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=m}for(a=this;a.gte(t);){r=Math.max(1,Math.floor(a.toNumber()/t.toNumber()));for(var l=Math.ceil(Math.log(r)/Math.LN2),d=l<=48?1:u(2,l-48),p=o(r),h=p.mul(t);h.isNegative()||h.gt(a);)h=(p=o(r-=d,this.unsigned)).mul(t);p.isZero()&&(p=y),s=s.add(p),a=a.sub(h)}return s},I.div=I.divide,I.modulo=function(t){return n(t)||(t=c(t)),e?i((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},I.mod=I.modulo,I.rem=I.modulo,I.not=function(){return i(~this.low,~this.high,this.unsigned)},I.and=function(e){return n(e)||(e=c(e)),i(this.low&e.low,this.high&e.high,this.unsigned)},I.or=function(e){return n(e)||(e=c(e)),i(this.low|e.low,this.high|e.high,this.unsigned)},I.xor=function(e){return n(e)||(e=c(e)),i(this.low^e.low,this.high^e.high,this.unsigned)},I.shiftLeft=function(e){return n(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?i(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):i(0,this.low<<e-32,this.unsigned)},I.shl=I.shiftLeft,I.shiftRight=function(e){return n(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?i(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):i(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},I.shr=I.shiftRight,I.shiftRightUnsigned=function(e){if(n(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?i(this.low>>>e|t<<32-e,t>>>e,this.unsigned):i(32===e?t:t>>>e-32,0,this.unsigned)},I.shru=I.shiftRightUnsigned,I.shr_u=I.shiftRightUnsigned,I.toSigned=function(){return this.unsigned?i(this.low,this.high,!1):this},I.toUnsigned=function(){return this.unsigned?this:i(this.low,this.high,!0)},I.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},I.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},I.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},t.fromBytes=function(e,n,r){return r?t.fromBytesLE(e,n):t.fromBytesBE(e,n)},t.fromBytesLE=function(e,n){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)},t.fromBytesBE=function(e,n){return new t(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)},pr}();const br=mr(yr),xr=br||e({__proto__:null,default:br},[yr]);function vr(e){return xr.fromString(e,!0,16)}const wr=vr("c3a5c85c97cb3127"),kr=vr("b492b66fbe98f273"),Ir=vr("9ae16a3b2f90404f");function Nr(e){return e.xor(e.shru(47))}function Sr(e,t,n){const r=e.slice(t,t+n);return xr.fromBytes(Array.from(r),!0,!0)}function Tr(e,t){return Sr(e,t,8)}function Cr(e,t){return Sr(e,t,4)}function $r(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Er(e,t,n=vr("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let a=t.xor(r).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function Rr(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=$r(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add($r(a,44)),[a.add(r),s.add(o)]}(Tr(e,t),Tr(e,t+8),Tr(e,t+16),Tr(e,t+24),n,r)}function _r(e,t=e.length){const n=xr.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Ir.add(2*t),r=Tr(e,0).add(Ir),a=Tr(e,t-8);return Er($r(a,37).mul(n).add(r),$r(r,25).add(a).mul(n),n)}if(t>=4){const n=Ir.add(2*t);return Er(Cr(e,0).shl(3).add(t),Cr(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Nr(Ir.mul(n).xor(wr.mul(r))).mul(Ir)}return Ir}(e,t):function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(kr),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir);return Er($r(r.add(a),43).add($r(s,30)).add(o),r.add($r(a.add(Ir),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(Ir),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir),i=$r(r.add(a),43).add($r(s,30)).add(o),u=Er(i,r.add($r(a.add(Ir),18)).add(s),n),l=Tr(e,16).mul(n),c=Tr(e,24),d=i.add(Tr(e,t-32)).mul(n),p=u.add(Tr(e,t-24)).mul(n);return Er($r(l.add(c),43).add($r(d,30)).add(p),l.add($r(c.add(r),18)).add(d),n)}(e,t);let r=n,a=n.mul(kr).add(113),s=Nr(a.mul(Ir).add(113)).mul(Ir),o=[xr.UZERO,xr.UZERO],i=[xr.UZERO,xr.UZERO];r=r.mul(Ir).add(Tr(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(kr),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(kr),r=r.xor(i[1]),a=a.add(o[0]).add(Tr(e,u+40)),s=$r(s.add(i[0]),33).mul(kr),o=Rr(e,u,o[1].mul(kr),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const d=kr.add(s.and(255).shl(1));return u=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(d),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(d),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(Tr(e,u+40))),s=$r(s.add(i[0]),33).mul(d),o=Rr(e,u,o[1].mul(d),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],Er(Er(o[0],i[0],d).add(Nr(a).mul(wr)).add(s),Er(o[1],i[1],d).add(r),d)}function Ar(e,t){return"string"===t?Dr(e):Or([e],t)}function Or(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Lr(e)),V().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Fr(){return V().platform.now()}function Dr(e,t="utf-8"){return t=t||"utf-8",V().platform.encode(e,t)}function Mr(e,t="utf-8"){return t=t||"utf-8",V().platform.decode(e,t)}function Pr(e){return null!=V().platform.isTypedArray?V().platform.isTypedArray(e):dr(e)}function Lr(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"===typeof e||"number"===typeof e||"string"===typeof e||M(e)||null==e||Pr(e)&&n)t.push(e);else if(Array.isArray(e)||Pr(e))for(let r=0;r<e.length;++r)Lr(e[r],t,n);else{let r=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(r=Math.max(r,Number(t)));for(let a=0;a<=r;a++)Lr(e[a],t,n)}return t}class Br{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Wr)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=Fr();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Fr()-o})}if(V().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let i=0;i<r.length;i++){const t=r[i];t.data().then(n=>{Vr(n,t.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then(e=>e.kernelMs),extraInfo:s.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach(e=>{Promise.all([e.data(),r,s]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function Vr(e,t,n){if("float32"!==t)return!1;for(let r=0;r<e.length;r++){const t=e[r];if(isNaN(t)||!isFinite(t))return console.warn(`Found ${t} in the result of '${n}'`),!0}return!1}class Wr{logKernelProfile(e,t,n,r,a,s){const o="number"===typeof r?f(`${r}ms`,9):r.error,i=f(e,25),u=t.rank,l=t.size,c=f(t.shape.toString(),14);let d="";for(const p in a){const e=a[p];if(null!=e){const n=e.shape||t.shape,r=n.length;d+=`${p}: ${r}D ${r>0?n:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${d}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function zr(e,t,n,r){const a=C(t),s=function(e,t,n,r){const a=c(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?jr(e):e;if(i>1)for(let l=0;l<a/s;l++){const e=l*s;for(let t=0;t<s;t++)o[t]=Math.max(o[t],Ur(u[e+t],0,n).length)}return o}(e,t,n,a),o=t.length,i=Hr(e,t,n,a,s),u=["Tensor"];return r&&(u.push(` dtype: ${n}`),u.push(` rank: ${o}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(i.map(e=>" "+e).join("\n")),u.join("\n")}function Ur(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:I(e)?`'${e}'`:"bool"===n?Gr(e):parseFloat(e.toFixed(7)).toString(),f(r,t)}function Gr(e){return 0===e?"false":"true"}function Hr(e,t,n,r,a,s=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u){if("complex64"===n){return[Ur(jr(e)[0],0,n)]}return"bool"===n?[Gr(e[0])]:[e[0].toString()]}if(1===u){if(i>20){const t=3*o;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((i-3)*o,i*o));return"complex64"===n&&(r=jr(r),s=jr(s)),["["+r.map((e,t)=>Ur(e,a[t],n)).join(", ")+", ..., "+s.map((e,t)=>Ur(e,a[i-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?jr(e):Array.from(e)).map((e,t)=>Ur(e,a[t],n)).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),d=r[0]*o,p=[];if(i>20){for(let t=0;t<3;t++){const r=t*d,s=r+d;p.push(...Hr(e.slice(r,s),l,n,c,a,!1))}p.push("...");for(let t=i-3;t<i;t++){const r=t*d,s=r+d;p.push(...Hr(e.slice(r,s),l,n,c,a,t===i-1))}}else for(let m=0;m<i;m++){const t=m*d,r=t+d;p.push(...Hr(e.slice(t,r),l,n,c,a,m===i-1))}const h=2===u?",":"";p[0]="["+(i>0?p[0]+h:"");for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=",\n";for(let m=2;m<u;m++)f+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":f),p}function jr(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class qr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=c(e),null!=n){const e=n.length;i(e===this.size,()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)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||v(t,this.size),this.strides=C(e)}set(e,...t){0===t.length&&(t=[0]),i(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Kr().makeTensor(this.values,this.shape,this.dtype)}}let Kr=null,Xr=null;class Yr{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=c(e),this.strides=C(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Xr.buffer(this.shape,this.dtype,e)}bufferSync(){return Xr.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return E(this.shape,e,"complex64"===this.dtype)}arraySync(){return E(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Kr().read(this.dataId);if("string"===this.dtype){const n=await e;try{return n.map(e=>Mr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Kr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Kr().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>Mr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Kr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Kr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Xr.print(this,e)}clone(){return this.throwIfDisposed(),Xr.clone(this)}toString(e=!1){return zr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Xr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Kr().makeVariable(this,e,t,n)}}function Qr(){return G("Tensor",()=>Yr)}Object.defineProperty(Yr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Qr();class Zr extends Yr{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!d(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Kr().disposeTensor(this),this.dataId=e.dataId,Kr().incRef(this,null)}dispose(){Kr().disposeVariable(this),this.isDisposedInternal=!0}}var Jr,ea,ta,na,ra,aa,sa,oa,ia,ua;Object.defineProperty(Zr,Symbol.hasInstance,{value:e=>e instanceof Yr&&null!=e.assign&&e.assign instanceof Function}),(ea=Jr||(Jr={})).R0="R0",ea.R1="R1",ea.R2="R2",ea.R3="R3",ea.R4="R4",ea.R5="R5",ea.R6="R6",(na=ta||(ta={})).float32="float32",na.int32="int32",na.bool="int32",na.complex64="complex64",(aa=ra||(ra={})).float32="float32",aa.int32="int32",aa.bool="bool",aa.complex64="complex64",(oa=sa||(sa={})).float32="float32",oa.int32="float32",oa.bool="float32",oa.complex64="complex64",(ua=ia||(ia={})).float32="complex64",ua.int32="complex64",ua.bool="complex64",ua.complex64="complex64";const la={float32:sa,int32:ta,bool:ra,complex64:ia};function ca(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return la[e][t]}function da(e){return ca(e,"int32")}function pa(e){return null!=e&&"object"===typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function ha(e){return"undefined"!==typeof GPUBuffer&&null!=e&&"object"===typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function fa(e,t){if(e.dtype===t.dtype)return[e,t];const n=ca(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ma(e){const t=[];return ga(e,t,new Set),t}function ga(e,t,n){if(null==e)return;if(e instanceof Yr)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!==typeof r)return;var r;const a=e;for(const s in a){const e=a[s];n.has(e)||(n.add(e),ga(e,t,n))}}function ya(e){return null!=e.kernelName}class ba{constructor(){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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class xa{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ba}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void(await this.setBackend(n))}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)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}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(rr(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Br(this.backendInstance),!0}setupRegisteredKernels(){ur(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){ur(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=t.factory();if(!r||r instanceof n||"function"!==typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then(n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0)).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,rr(`Initialization of backend ${e} failed`),rr(n.stack||n.message)),!1));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}}catch(r){return rr(`Initialization of backend ${e} failed`),rr(r.stack||r.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,a=this.readSync(t),s=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!==typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!==typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!==typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(r){throw t(),r}}nextTensorId(){return xa.nextTensorId++}nextVariableId(){return xa.nextVariableId++}clone(e){const t=wa.runKernel(ot,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return wa.runKernel(fe,t,n)}}),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=or(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ya(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(ya(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=or(t,this.backendName);i(null!=l,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),o=()=>{const e=this.backend.numDataIds();u=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const i=o.map(e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e));if(r){const e=this.getTensorsForGradient(t,a,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();u=this.tidy(()=>t(this.backend,a));const n=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:d}=e,p=ya(e)?null:e.backwardsFunc;let h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()}),r&&this.addTapeNode(l,c,t,p,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(e=>null!=c[e]?c[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=ir(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(i(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),s=Object.keys(t).map(e=>t[e])):s=e.map(e=>t[e]);const o=n.filter((e,t)=>a[t]);return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&I(e[0])&&(a=e.map(e=>Dr(e)));const s=r.write(a,t,n),o=new Yr(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,s=new Yr(r,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Zr(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*k(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Zr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*k(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=ir(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=_(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=ma(e),n=new Set(t.map(e=>e.id));for(let a=0;a<this.state.activeScope.track.length;a++){const e=this.state.activeScope.track[a];e.kept||n.has(e.id)||e.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(e=>{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(i(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));i(a instanceof Yr,()=>"The result y returned by f() must be a tensor.");const s=function(e,t,n){const r={},a={};for(let u=0;u<t.length;u++)r[t[u].id]=!0;for(let u=0;u<e.length;u++){const n=e[u],s=n.inputs;for(const e in s){const o=s[e];let i=!1;for(let e=0;e<t.length;e++)if(r[o.id]){n.outputs.forEach(e=>r[e.id]=!0),i=!0,a[n.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let u=e.length-1;u>=0;u--){const t=e[u],n=t.inputs;for(let e=0;e<t.outputs.length;e++)if(s[t.outputs[e].id]){for(const e in n)s[n[e].id]=!0,o[t.id]=!0;break}}const i=[];for(let u=0;u<e.length;u++){const t=e[u];if(a[t.id]&&o[t.id]){const e={};for(const a in t.inputs){const n=t.inputs[a];r[n.id]&&(e[a]=n)}const n=Object.assign({},t);n.inputs=e,n.outputs=t.outputs,i.push(n)}}return i}(this.state.activeTape,t,a);if(!r&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const e={};e[a.id]=n??function(e){const t=R(c(e),"float32");return wa.makeTensor(t,e,"float32")}(a.shape),function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach(t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)}),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n(()=>i[t]());if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!d(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,e=>this.tidy(e),ka);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:a,grads:r}})}customGrad(e){return i(S(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;i(t.every(e=>e instanceof Yr),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};t.forEach((e,t)=>{r[t]=e});return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),i(n.value instanceof Yr,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),i(S(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];i(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),i(s.every(e=>e instanceof Yr),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const o={};return s.forEach((e,t)=>{o[t]=()=>e}),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Fr(),n=await this.backend.time(e);return n.wallMs=Fr()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ba;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function va(){const e=U();if(null==e._tfengine){const t=new L(e);e._tfengine=new xa(t)}var t;return t=e._tfengine.ENV,z=t,Kr=()=>e._tfengine,e._tfengine}xa.nextTensorId=0,xa.nextVariableId=0;const wa=va();function ka(e,t){const n={a:e,b:t};return wa.runKernel(K,n)}function Ia(e){if(e||"undefined"!==typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!==typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function Na(){return"undefined"!==typeof window&&null!=window.document||"undefined"!==typeof WorkerGlobalScope}const Sa=V();function Ta(e,t){let n=e;if(Pr(e))return"string"===t?[]:[e.length];if(pa(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(ha(e))return[e.buffer.size/(null==t?4:k(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Pr(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&V().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Ca(e,r,[]),r}function Ca(e,t,n){if(n=n||[],!Array.isArray(e)&&!Pr(e))return void i(0===t.length,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);i(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),i(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let a=0;a<e.length;++a)Ca(e[a],r,n.concat(a))}function $a(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function Ea(e,t,n,r="numeric"){if(e instanceof Qr())return $a(r,e.dtype,t,n),e;let a=N(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),$a(r,a,t,n),null==e||!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=Ta(e,a);Pr(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?Or(e,a):Lr(e,[],!0);return wa.makeTensor(o,s,a)}function Ra(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((e,a)=>Ea(e,`${t}[${a}]`,n,r))}Sa.registerFlag("DEBUG",()=>!1,e=>{e&&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.")}),Sa.registerFlag("IS_BROWSER",()=>Na()),Sa.registerFlag("IS_NODE",()=>"undefined"!==typeof process&&"undefined"!==typeof process.versions&&"undefined"!==typeof process.versions.node),Sa.registerFlag("IS_CHROME",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Sa.registerFlag("IS_SAFARI",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Sa.registerFlag("PROD",()=>!1),Sa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Sa.getBool("DEBUG")),Sa.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Sa.registerFlag("IS_TEST",()=>!1),Sa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Sa.getBool("DEBUG")),Sa.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Sa.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Sa.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const _a="__op";function Aa(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=_a;const a=(...e)=>{wa.startScope(n);try{const t=r(...e);return M(t)&&console.error("Cannot return a Promise inside of tidy."),wa.endScope(t),t}catch(t){throw wa.endScope(null),t}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const Oa=Aa({complex_:function(e,t){const n=Ea(e,"real","complex"),r=Ea(t,"imag","complex");u(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return wa.runKernel(ye,a)}});function Fa(e,t,n,r){if(null==r)r=N(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(ha(e)||pa(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return wa.backend.createTensorFromGPUData(e,t||n,r)}if(!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){O(t);const e=c(t),r=c(n);i(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let a=0;a<n.length;++a){const e=n[a],r=a!==n.length-1||e!==c(t.slice(a));i(n[a]===t[a]||!r,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return Pr(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Or(e,r):Lr(e,[],!0),wa.makeTensor(e,t,r)}function Da(e,t,n){return Fa(e,t,Ta(e,n),n)}const Ma={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Pa{static join(e){return new Pa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map(e=>Pr(e)?e.buffer:e)).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const r=e[n];n!==e.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const a=t+r.byteLength;this.shards.push({buffer:r,start:t,end:a}),t=a}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const r=new ArrayBuffer(t-e),a=new Uint8Array(r);let s=0;for(let o=n;o<this.shards.length;o++){const n=this.shards[o],r=e+s-n.start,i=s,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,r,u-r);if(a.set(l,i),s+=l.length,t<n.end)break}return r}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const a=Math.floor((r-n)/2)+n,s=t(e[a]);if(0===s)return a;s<0?r=a:n=a+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function La(){return wa}function Ba(e,t){return wa.tidy(e,t)}function Va(e){ma(e).forEach(e=>e.dispose())}function Wa(e){return wa.keep(e)}function za(e){return wa.setBackend(e)}function Ua(){return wa.backendName}function Ga(e,t,n=1){return wa.registerBackend(e,t,n)}function Ha(){return wa.backend}function ja(e,t){const n=new Pa(e),r={};let a=0;for(const s of t){const e=qa(s,(e,t)=>n.slice(a+e,a+t));r[s.name]=Xa(s,n.slice(a,a+e)),a+=e}return r}function qa(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Ma[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(t(e,e+4))[0];return e}r=Ma[e.dtype]}return n*r}async function Ka(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Ma[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(await t(e,e+4))[0];return e}r=Ma[e.dtype]}return n*r}function Xa(e,t){const n=e.name,r=e.dtype,a=e.shape,s=c(a);let o,i=0;if("quantization"in e){const a=e.quantization;if("uint8"===a.dtype||"uint16"===a.dtype){if(!("min"in a)||!("scale"in a))throw new Error(`Weight ${e.name} with quantization ${a.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==a.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${a.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${e.name} is quantized with ${a.dtype} which only supports weights of type float32 not ${r}.`)}const u=Ma[a.dtype],l="uint8"===a.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===r)if("uint8"===a.dtype||"uint16"===a.dtype){o=new Float32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];o[e]=t*a.scale+a.min}}else{if("float16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0===(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let o=0;o<r.length;o++){const a=r[o],i=e[n[a>>10]+(1023&a)]+t[a>>10];s[o]=i}return new Float32Array(a)}}();o=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);o=new Int32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];o[e]=Math.round(t*a.scale+a.min)}}i+=s*u}else if("string"===r){const n=c(e.shape);o=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(i,i+4))[0];i+=4;const n=new Uint8Array(t.slice(i,i+e));o.push(n),i+=e}}else{const e=Ma[r];if("float32"===r)o=new Float32Array(t);else if("int32"===r)o=new Int32Array(t);else{if("bool"!==r){if("complex64"===r){o=new Float32Array(t);const e=new Float32Array(o.length/2),n=new Float32Array(o.length/2);for(let t=0;t<e.length;t++)e[t]=o[2*t],n[t]=o[2*t+1];const r=Da(e,a,"float32"),s=Da(n,a,"float32"),i=Oa(r,s);return r.dispose(),s.dispose(),i}throw new Error(`Unsupported dtype in weight '${n}': ${r}`)}o=new Uint8Array(t)}i+=s*e}return Da(o,a,r)}async function Ya(e,t,n){let r=new Uint8Array(t);for(;r.byteLength<n;){const{done:t,value:a}=await e.read();if(t&&null==a){const e=n-r.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const s=new Uint8Array(r.length+a.byteLength);s.set(r,0),s.set(new Uint8Array(a),r.length),r=s}return r.buffer}async function Qa(e,t){const n={},r=e.getReader();let a=new ArrayBuffer(0);for(const s of t){const e=await Ka(s,async(e,t)=>(a=await Ya(r,a,t),a.slice(e,t)));a=await Ya(r,a,e);const t=a.slice(0,e);a=a.slice(e);const o=Xa(s,t);if(n[s.name]=o,"webgpu"===Ua()){const e=Ha();"uploadToGPU"in e&&c(o.shape)>=V().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}function Za(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)});const r=new Uint8Array(t);let a=0;return n.forEach(e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}const Ja="undefined"!==typeof Buffer&&("undefined"===typeof Blob||"undefined"===typeof atob||"undefined"===typeof btoa);function es(e){return Ja?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function ts(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function ns(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function rs(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function as(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),rs(e,n,r)}function ss(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:es(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:es(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new Pa(e.weightData).byteLength}}function os(e){const t=[];for(const n of e)t.push(...n.weights);return t}class is{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==is.instance&&(is.instance=new is),is.instance}static registerSaveRouter(e){is.getInstance().saveRouters.push(e)}static registerLoadRouter(e){is.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return is.getHandlers(e,"save")}static getLoadHandlers(e,t){return is.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?is.getInstance().loadRouters:is.getInstance().saveRouters).forEach(t=>{const a=t(e,n);null!==a&&r.push(a)}),r}}const us="tensorflowjs",ls="models_store",cs="model_info_store";function ds(){if(!V().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"===typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ps(e){const t=e.result;t.createObjectStore(ls,{keyPath:"modelPath"}),t.createObjectStore(cs,{keyPath:"modelPath"})}class hs{constructor(e){if(this.indexedDB=ds(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((e,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(ls,"readonly"),r=t.objectStore(ls).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{t.weightData=Pa.join(t.weightData);const r=ss(t),o=a.transaction(cs,"readwrite");let i,u,l=o.objectStore(cs);try{i=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(s){return n(s)}i.onsuccess=()=>{u=a.transaction(ls,"readwrite");const i=u.objectStore(ls);let c;try{c=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(s){return n(s)}c.onsuccess=()=>e({modelArtifactsInfo:r}),c.onerror=e=>{l=o.objectStore(cs);const t=l.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(c.error)),t.onerror=e=>(a.close(),n(c.error))}},i.onerror=e=>(a.close(),n(i.error)),o.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)})}}hs.URL_SCHEME="indexeddb://";const fs=e=>{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(hs.URL_SCHEME)?(t=e.slice(hs.URL_SCHEME.length),new hs(t)):null;var t};is.registerSaveRouter(fs),is.registerLoadRouter(fs);class ms{constructor(){this.indexedDB=ds()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(us,1);n.onupgradeneeded=()=>ps(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(cs,"readonly"),s=a.objectStore(cs).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(hs.URL_SCHEME)?t.slice(hs.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(cs,"readwrite"),o=s.objectStore(cs),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction(ls,"readwrite");const r=u.objectStore(ls).delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)})}}const gs="/",ys="tensorflowjs_models",bs="info",xs="model_topology",vs="weight_specs",ws="weight_data",ks="model_metadata";function Is(e){return{info:[ys,e,bs].join(gs),topology:[ys,e,xs].join(gs),weightSpecs:[ys,e,vs].join(gs),weightData:[ys,e,ws].join(gs),modelMetadata:[ys,e,ks].join(gs)}}function Ns(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Ss(e){const t=e.split(gs);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(gs)}class Ts{constructor(e){if(!V().getBool("IS_BROWSER")||"undefined"===typeof window||"undefined"===typeof window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Is(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const n=JSON.stringify(e.modelTopology),r=JSON.stringify(e.weightSpecs),a=ss(e),s=Pa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,n),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,function(e){if(Ja)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let r=0,a=t.length;r<a;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(s));const t={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(t)),{modelArtifactsInfo:a}}catch(t){throw Ns(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(Ja){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;++r)n.set([t.charCodeAt(r)],r);return n.buffer}(s),t}}Ts.URL_SCHEME="localstorage://";const Cs=e=>{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ts.URL_SCHEME)?(t=e.slice(Ts.URL_SCHEME.length),new Ts(t)):null;var t};is.registerSaveRouter(Cs),is.registerLoadRouter(Cs);class $s{constructor(){i(V().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),i("undefined"===typeof window||"undefined"!==typeof window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=ys+gs,n=gs+bs;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);if(a.startsWith(t)&&a.endsWith(n)){e[Ss(a)]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){var t;const n=Is(e=(t=e).startsWith(Ts.URL_SCHEME)?t.slice(Ts.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return Ns(n),r}}const Es="://";class Rs{constructor(){this.managers={}}static getInstance(){return null==Rs.instance&&(Rs.instance=new Rs),Rs.instance}static registerManager(e,t){i(null!=e,()=>"scheme must not be undefined or null."),e.endsWith(Es)&&(e=e.slice(0,e.indexOf(Es))),i(e.length>0,()=>"scheme must not be an empty string.");const n=Rs.getInstance();i(null==n.managers[e],()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=Rs.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Rs.getInstance().managers)}}function _s(e){if(-1===e.indexOf(Es))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Rs.getSchemes().join(",")}`);return{scheme:e.split(Es)[0],path:e.split(Es)[1]}}async function As(e,t,n=!1){i(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=is.getLoadHandlers(e);i(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),i(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const a=r[0],s=is.getSaveHandlers(t);i(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),i(s.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const o=s[0],u=_s(e).scheme,l=_s(e).path,c=u===_s(e).scheme,d=await a.load();n&&c&&await Rs.getManager(u).removeModel(l);const p=await o.save(d);return n&&!c&&await Rs.getManager(u).removeModel(l),p.modelArtifactsInfo}class Os{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!==typeof window&&V().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))):setTimeout(e,t)}isTypedArray(e){return dr(e)}}if(V().get("IS_BROWSER")){V().setPlatform("browser",new Os);try{Rs.registerManager(Ts.URL_SCHEME,new $s)}catch(hO){}try{Rs.registerManager(hs.URL_SCHEME,new ms)}catch(hO){}}const Fs=()=>require("node-fetch");let Ds;class Ms{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=V().global.fetch?V().global.fetch(e,t):(null==Ds&&(Ds=Fs()),Ds(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}function Ps(e,t="float32",n){return t=t||"float32",O(e),new qr(e,t,n)}V().get("IS_NODE")&&!V().get("IS_BROWSER")&&V().setPlatform("node",new Ms);const Ls=Aa({cast_:function(e,t){const n=Ea(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return wa.runKernel(fe,r,a)}});const Bs=Aa({clone_:function(e){const t={x:Ea(e,"x","clone","string_or_numeric")};return wa.runKernel(ot,t)}});function Vs(e,t=!1){console.log(e.toString(t))}va();Xr={buffer:Ps,cast:Ls,clone:Bs,print:Vs};const Ws=Aa({add_:function(e,t){let n=Ea(e,"a","add"),r=Ea(t,"b","add");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(K,a)}});const zs=Aa({floorDiv_:function(e,t){let n=Ea(e,"a","floorDiv"),r=Ea(t,"b","floorDiv");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(et,a)}});const Us=Aa({div_:function(e,t){let n=Ea(e,"a","div"),r=Ea(t,"b","div");if([n,r]=fa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return zs(n,r);const a={a:n,b:r};return wa.runKernel(We,a,{})}});const Gs=Aa({mul_:function(e,t){let n=Ea(e,"a","mul"),r=Ea(t,"b","mul");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Mt,a)}});const Hs=Aa({abs_:function(e){const t=Ea(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return wa.runKernel(be,e)}{const e={x:t};return wa.runKernel(H,e)}}});const js=Aa({acos_:function(e){const t={x:Ea(e,"x","acos")};return wa.runKernel(j,t)}});const qs=Aa({acosh_:function(e){const t={x:Ea(e,"x","acosh")};return wa.runKernel(q,t)}});const Ks=Aa({addN_:function(e){i(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),i(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((e,t)=>Ea(e,`tensors${t}`,"addN")),n=t[0];t.forEach(e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(e=>{if(!d(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=t;return wa.runKernel(X,r)}});const Xs=Aa({all_:function(e,t=null,n=!1){const r={x:Ea(e,"x","all","bool")},a={axis:t,keepDims:n};return wa.runKernel(Y,r,a)}});const Ys=Aa({any_:function(e,t=null,n=!1){const r={x:Ea(e,"x","any","bool")},a={axis:t,keepDims:n};return wa.runKernel(Q,r,a)}});const Qs=Aa({argMax_:function(e,t=0){const n={x:Ea(e,"x","argMax")},r={axis:t};return wa.runKernel(Z,n,r)}});const Zs=Aa({argMin_:function(e,t=0){const n={x:Ea(e,"x","argMin")},r={axis:t};return wa.runKernel(J,n,r)}});const Js=Aa({asin_:function(e){const t={x:Ea(e,"x","asin")};return wa.runKernel(ee,t)}});const eo=Aa({asinh_:function(e){const t={x:Ea(e,"x","asinh")};return wa.runKernel(te,t)}});const to=Aa({atan_:function(e){const t={x:Ea(e,"x","atan")};return wa.runKernel(ne,t)}});const no=Aa({atan2_:function(e,t){let n=Ea(e,"a","atan2"),r=Ea(t,"b","atan2");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(ae,a)}});const ro=Aa({atanh_:function(e){const t={x:Ea(e,"x","atanh")};return wa.runKernel(re,t)}});function ao(e,t,n,r,a="NHWC",s){return io(e,[...t,e[3]],n,s,r,null,null,bo(a))}function so(e,t,n,r,a,s,o="channelsLast"){const[i,u]=co(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);l=[i,u,e[1],e[1]]}return io(e,l,n,r,a,s,!1,o)}function oo(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=po(t);let c,d;if("NDHWC"===o)d="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error(`Unknown dataFormat ${o}`);d="channelsFirst",c=[i,u,l,e[1],e[1]]}return uo(e,c,n,r,a,!1,d,s)}function io(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,d]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,d,l,c]=e}const[p,h,,f]=t,[m,g]=co(n),[y,b]=co(r),x=ho(p,y),v=ho(h,b),{padInfo:w,outHeight:k,outWidth:I}=function(e,t,n,r,a,s,o,i,u){let l,c,d;if("number"===typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=lo(e,t,n));const s=e[0],o=e[1],i=fo((s-t+2*r)/n+1,a),u=fo((o-t+2*r)/n+1,a);return[i,u]}([t,n],s,r,e,i);c=a[0],d=a[1]}else if("same"===e){c=Math.ceil(t/r),d=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(d-1)*a+o-n),u=Math.floor(e/2),p=e-u,h=Math.floor(i/2);l={top:u,bottom:p,left:h,right:i-h,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),d=Math.ceil((n-o+1)/a);else{if("object"!==typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===u?e[1][0]:e[2][0],h="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:p,bottom:h,left:f,right:m,type:0===p&&0===h&&0===f&&0===m?"VALID":"EXPLICIT"},c=fo((t-s+p+h)/r+1,i),d=fo((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:d}}(a,l,c,m,g,x,v,s,i),N=o?f*d:f;let S;return"channelsFirst"===i?S=[u,N,k,I]:"channelsLast"===i&&(S=[u,k,I,N]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:d,outHeight:k,outWidth:I,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function uo(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,d,p]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,d,p]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,p,l,c,d]=e}const[h,f,m,,g]=t,[y,b,x]=po(n),[v,w,k]=po(r),I=ho(h,v),N=ho(f,w),S=ho(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,r,a,s,o,i,u,l,c){let d,p,h,f;"valid"===e&&(e=0);if("number"===typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,a,s){null==a&&(a=lo(e,t[0],r[0]));const o=[0,0,0,n];for(let i=0;i<3;i++)e[i]+2*a>=t[i]&&(o[i]=fo((e[i]-t[i]+2*a)/r[i]+1,s));return o}([t,n,r,1],[i,u,l],1,[a,s,o],e,c);p=m[0],h=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{p=Math.ceil(t/a),h=Math.ceil(n/s),f=Math.ceil(r/o);const e=(p-1)*a+i-t,c=(h-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,v=Math.floor(m/2);d={top:b,bottom:x,left:v,right:m-v,front:g,back:y,type:"SAME"}}}return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}(a,l,c,d,y,b,x,I,N,S,i),R=s?g*p:g;let _;return"channelsFirst"===o?_=[u,R,C,$,E]:"channelsLast"===o&&(_=[u,C,$,E,R]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:d,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:R,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:v,dilationHeight:w,dilationWidth:k,inShape:e,outShape:_,filterShape:t}}function lo(e,t,n,r=1){const a=ho(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function co(e){return"number"===typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function po(e){return"number"===typeof e?[e,e,e]:e}function ho(e,t){return t<=1?e:e+(e-1)*(t-1)}function fo(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function mo(e){const[t,n,r]=co(e);return 1===t&&1===n&&1===r}function go(e,t){return mo(e)||mo(t)}function yo(e){return co(e).every(e=>e>0)}function bo(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function xo(e,t,n){if(null!=n){if("string"===typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"===typeof t)i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else{if("object"!==typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach(t=>{t.forEach(t=>{i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`)})})}}}const vo=Aa({reshape_:function(e,t){const n={x:Ea(e,"x","reshape","string_or_numeric")},r={shape:t};return wa.runKernel(nn,n,r)}});const wo=Aa({avgPool_:function(e,t,n,r,a){const s=Ea(e,"x","avgPool","float32");i(go(n,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),xo("avgPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let d=wa.runKernel(se,l,c);return d=Ls(d,s.dtype),u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const ko=Aa({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=Ea(e,"x","avgPool3d","float32");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),i("number"===typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`),xo("avgPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=wa.runKernel(ie,c,d);return p=Ls(p,u.dtype),l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Io=Aa({concat_:function(e,t=0){i(e.length>=1,()=>"Pass at least one tensor to concat");const n=Ra(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach(e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)}),1===n.length)return Bs(n[0]);const r=n,a={axis:t};return wa.runKernel(xe,r,a)}});const No=Aa({matMul_:function(e,t,n=!1,r=!1){let a=Ea(e,"a","matMul"),s=Ea(t,"b","matMul");[a,s]=fa(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return wa.runKernel(le,o,i)}});const So=Aa({sigmoid_:function(e){const t={x:Ea(e,"x","sigmoid","float32")};return wa.runKernel(wn,t)}});const To=Aa({slice_:function(e,t,n){const r=Ea(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},s={begin:t,size:n};return wa.runKernel(yn,a,s)}});const Co=Aa({tanh_:function(e){const t={x:Ea(e,"x","tanh","float32")};return wa.runKernel(zn,t)}});const $o=Aa({basicLSTMCell_:function(e,t,n,r,a,s){const o=Ea(e,"forgetBias","basicLSTMCell"),i=Ea(t,"lstmKernel","basicLSTMCell"),u=Ea(n,"lstmBias","basicLSTMCell"),l=Ea(r,"data","basicLSTMCell"),c=Ea(a,"c","basicLSTMCell"),d=Ea(s,"h","basicLSTMCell"),p=Io([l,d],1),h=No(p,i),f=Ws(h,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=To(f,[0,0],y),x=To(f,[0,g],y),v=To(f,[0,2*g],y),w=To(f,[0,3*g],y),k=Ws(Gs(So(b),Co(x)),Gs(c,So(Ws(o,v))));return[k,Gs(Co(k),So(w))]}});const Eo=Aa({batchToSpaceND_:function(e,t,n){const r=Ea(e,"x","batchToSpaceND"),a=t.reduce((e,t)=>e*t);i(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),i(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),i(r.shape[0]%a===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);const s={x:r},o={blockShape:t,crops:n};return wa.runKernel(ce,s,o)}});const Ro=Aa({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(u.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),i(null==d||u.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),i(null==c||u.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const p={x:function(e){let t;return t=0===e.rank||1===e.rank?vo(e,[1,1,1,e.size]):2===e.rank?vo(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),scale:c,offset:d,mean:u,variance:l},h={varianceEpsilon:s},f=wa.runKernel(tt,p,h);return vo(f,o.shape)}});const _o=Aa({batchNorm2d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(2===o.rank,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),i(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${u.rank}.`),i(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),null!=c&&i(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),null!=d&&i(2===d.rank||1===d.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Ao=Aa({batchNorm3d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(3===o.rank,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),i(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${u.rank}.`),i(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),null!=c&&i(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),null!=d&&i(3===d.rank||1===d.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Oo=Aa({batchNorm4d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(4===o.rank,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),i(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${u.rank}.`),i(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),null!=c&&i(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),null!=d&&i(4===d.rank||1===d.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Fo=Aa({bincount_:function(e,t,n){const r=Ea(e,"x","bincount"),a=Ea(t,"weights","bincount");i("int32"===r.dtype,()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(a.size===r.size||0===a.size,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`);const s={x:r,weights:a},o={size:n};return wa.runKernel(de,s,o)}});const Do=Aa({bitwiseAnd_:function(e,t){const n=Ea(e,"x","bitwiseAnd"),r=Ea(t,"y","bitwiseAnd");if(!d(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const a={a:n,b:r};return wa.runKernel(pe,a)}});const Mo=Aa({broadcastArgs_:function(e,t){const n=Ea(e,"s0","broadcastArgs","int32"),r=Ea(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return wa.runKernel(he,a)}});const Po=Aa({broadcastTo_:function(e,t){let n=Ea(e,"broadcastTo","x");const r=n.shape;if(O(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=vo(n,e)}const a=n.shape,s=Array.from(t);for(let u=t.length-1;u>=0;u--)if(a[u]===t[u])s[u]=1;else if(1!==n.shape[u])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===s.map((e,t)=>e>1?t:-1).filter(e=>e>=0).length)return Bs(n);const o={x:n},i={reps:s};return wa.runKernel(Un,o,i)}});const Lo=Aa({ceil_:function(e){const t={x:Ea(e,"x","ceil","float32")};return wa.runKernel(me,t)}});function Bo(e,t,n){O(e);const r={shape:e,value:t,dtype:n=n||N(t)};return wa.runKernel(Qe,{},r)}const Vo=Aa({clipByValue_:function(e,t,n){const r=Ea(e,"x","clipByValue");if(i(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return Bo(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return wa.runKernel(ge,a,s)}});const Wo=Aa({concat1d_:function(e){return Io(e,0)}});const zo=Aa({concat2d_:function(e,t){return Io(e,t)}});const Uo=Aa({concat3d_:function(e,t){return Io(e,t)}});const Go=Aa({concat4d_:function(e,t){return Io(e,t)}});const Ho=Aa({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","conv2d","float32"),l=Ea(t,"filter","conv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),xo("conv2d",r,o);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i(yo(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv2D: Strides should be larger than 0.");const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(ve,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const jo=Aa({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const u=Ea(e,"x","conv1d"),l=Ea(t,"filter","conv1d");let c=u,d=!1;2===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1]])),i(3===c.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),i(3===l.rank,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),xo("conv1d",r,o),i(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),i(go(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),i(yo(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv1D: Stride should be larger than 0."),i("NWC"===a,()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);const p=vo(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=vo(c,[c.shape[0],1,c.shape[1],c.shape[2]]),f=Ho(h,p,[1,n],r,"NHWC",[1,s],o);return vo(f,d?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const qo=Aa({conv2DBackpropInput_:function(e,t,n,r,a,s="NHWC",o){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let u=e,l=t,c=!1;3===t.rank&&(c=!0,l=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]),u=[1,e[0],e[1],e[2]]),i(4===u.length,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${u.length}.`),i(4===l.rank,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),i(4===n.rank,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const d="NHWC"===s?u[3]:u[1],p="NHWC"===s?l.shape[3]:l.shape[1];i(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),i(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),xo("conv2dDerInput",a,o);const h={dy:l,filter:n},f={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:u},m=wa.runKernel(ke,h,f);return c?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Ko=Aa({conv2dTranspose_:function(e,t,n,r,a,s){const o=Ea(e,"x","conv2dTranspose"),i=Ea(t,"filter","conv2dTranspose");return qo(n,o,i,r,a,"NHWC",s)}});const Xo=Aa({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=Ea(e,"x","conv3d"),u=Ea(t,"filter","conv3d");let l=o,c=!1;4===o.rank&&(c=!0,l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===l.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),i(5===u.rank,()=>`Error in conv3d: filter must be rank 5, but got rank ${u.rank}.`),i(l.shape[4]===u.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${u.shape[3]}.`),i(go(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i("NDHWC"===a,()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`),i(yo(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv3D: Strides should be larger than 0.");const d={x:l,filter:u},p={strides:n,pad:r,dataFormat:a,dilations:s},h=wa.runKernel(Ie,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Yo=Aa({conv3DBackpropInput_:function(e,t,n,r,a){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,o=t,u=!1;4===t.rank&&(u=!0,o=vo(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const l=s[4],c=o.shape[4];i(5===s.length,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),i(5===o.rank,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),i(5===n.rank,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),i(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),i(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);const d={dy:o,filter:n},p={pad:a,strides:r,inputShape:s},h=wa.runKernel(Se,d,p);return u?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Qo=Aa({conv3dTranspose_:function(e,t,n,r,a){const s=Ea(e,"x","conv3dTranspose"),o=Ea(t,"filter","conv3dTranspose");return Yo(n,s,o,r,a)}});const Zo=Aa({cos_:function(e){const t={x:Ea(e,"x","cos","float32")};return wa.runKernel(Te,t)}});const Jo=Aa({cosh_:function(e){const t={x:Ea(e,"x","cosh","float32")};return wa.runKernel(Ce,t)}});const ei=Aa({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel($e,a,s)}});const ti=Aa({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel(Ee,a,s)}});const ni=Aa({denseBincount_:function(e,t,n,r=!1){const a=Ea(e,"x","denseBincount"),s=Ea(t,"weights","denseBincount");i("int32"===a.dtype,()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),i(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(s.size===a.size||0===s.size,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);const o={x:a,weights:s},u={size:n,binaryOutput:r};return wa.runKernel(_e,o,u)}});const ri=Aa({depthToSpace_:function(e,t,n="NHWC"){const r=Ea(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],s="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];i(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),i(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);const u={x:r},l={blockSize:t,dataFormat:n};return wa.runKernel(Ae,u,l)}});const ai=Aa({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","depthwiseConv2d","float32"),l=Ea(t,"filter","depthwiseConv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`),xo("depthwiseConv2d",r,o);const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(Oe,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const si=Aa({diag_:function(e){const t={x:Ea(e,"x","diag")};return wa.runKernel(Me,t)}});const oi=Aa({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=Ea(e,"x","dilation2d"),u=Ea(t,"filter","dilation2d");i(3===o.rank||4===o.rank,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),i(3===u.rank,()=>`Error in dilation2d: filter must be rank 3, but got rank ${u.rank}.`),i("NHWC"===s,()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=o,c=!1;3===o.rank&&(l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0),i(l.shape[3]===u.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${u.shape[2]}`);const d={x:l,filter:u},p={strides:n,pad:r,dilations:a},h=wa.runKernel(Pe,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});function ii(e,t){const n=e.length,r=[];for(let a=0;a<n;a++){const s=n-1-a,o=e[s]||1;(t[t.length-1-a]||1)>1&&1===o&&r.unshift(s)}return r}function ui(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1],s=t.length-r-1,o=t[s];(null==a||1===a&&o>1)&&n.unshift(s)}return n}function li(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let a=0;a<n;a++){let s=e[e.length-a-1];null==s&&(s=1);let o=t[t.length-a-1];if(null==o&&(o=1),1===s)r[n-a-1]=o;else if(1===o)r[n-a-1]=s;else{if(s!==o){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}r[n-a-1]=s}}return r}const ci=Aa({equal_:function(e,t){let n=Ea(e,"a","equal","string_or_numeric"),r=Ea(t,"b","equal","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(je,a)}});const di=Aa({where_:function(e,t,n){const r=Ea(t,"a","where"),a=Ea(n,"b","where"),s=Ea(e,"condition","where","bool"),o=li(li(s.shape,r.shape),a.shape),i={condition:Po(s,o),t:Po(r,o),e:Po(a,o)};return wa.runKernel(mn,i)}});const pi=Aa({zerosLike_:function(e){const t={x:Ea(e,"x","zerosLike")};return wa.runKernel(Yn,t)}});const hi=Aa({divNoNan_:function(e,t){let n=Ea(e,"a","div"),r=Ea(t,"b","div");[n,r]=fa(n,r);const a=Us(n,r),s=pi(a),o=ci(r,s);return di(o,s,a)}});const fi=Aa({dot_:function(e,t){const n=Ea(e,"t1","dot"),r=Ea(t,"t2","dot");i((1===n.rank||2===n.rank)&&(1===r.rank||2===r.rank),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const a=1===n.rank?n.size:n.shape[1],s=1===r.rank?r.size:r.shape[0];if(i(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),1===n.rank&&1===r.rank){const e=vo(n,[1,-1]),t=vo(r,[-1,1]),a=No(e,t);return vo(a,[])}if(1===n.rank&&2===r.rank){const e=vo(n,[1,-1]),t=vo(r,[r.shape[0],r.shape[1]]),a=No(e,t);return vo(a,[a.size])}if(2===n.rank&&1===r.rank){const e=vo(r,[-1,1]),t=No(n,e);return vo(t,[t.size])}{const e=vo(r,[r.shape[0],r.shape[1]]);return No(n,e)}}});const mi=Aa({einsum_:function(e,...t){const n=t.map((e,t)=>Ea(e,`tensors${t}`,"einsum")),r={equation:e};return wa.runKernel(ze,n,r)}});const gi=Aa({elu_:function(e){const t={x:Ea(e,"x","elu","float32")};return wa.runKernel(Ue,t)}});const yi=Aa({ensureShape_:function(e,t){const n=Ea(e,"x","ensureShape","string_or_numeric");if(!function(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}});const bi=Aa({erf_:function(e){let t=Ea(e,"x","erf");i("int32"===t.dtype||"float32"===t.dtype,()=>"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=Ls(t,"float32"));const n={x:t};return wa.runKernel(He,n)}});function xi(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function vi(e,t,n){const r=e.length+t.length,a=[];let s=0,o=0;for(let i=0;i<r;i++)-1===n.indexOf(i)?a.push(e[s++]):a.push(t[o++]);return a}function wi(e,t){const n=[],r=e.length;for(let a=0;a<r;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map(t=>e[t])]}function ki(e,t){return vi(e,t.map(e=>1),t)}function Ii(e,t,n){i(xi(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ni(e,t){if(xi(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach(e=>n.push(e)),n}function Si(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function Ti(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const Ci=Aa({max_:function(e,t=null,n=!1){const r={x:Ea(e,"x","max")},a={reductionIndices:t,keepDims:n};return wa.runKernel(It,r,a)}});const $i=Aa({min_:function(e,t=null,n=!1){const r={x:Ea(e,"x","min")},a={axis:t,keepDims:n};return wa.runKernel(_t,r,a)}});const Ei=Aa({pow_:function(e,t){let n=Ea(e,"base","pow"),r=Ea(t,"exp","pow");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(jt,a)}});function Ri(e,t){if((Pr(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Pr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Fa(e,[],[],t)}const _i=Aa({sqrt_:function(e){const t={x:Ea(e,"x","sqrt","float32")};return wa.runKernel(In,t)}});const Ai=Aa({square_:function(e){const t=Ea(e,"x","square");return wa.runKernel("Square",{x:t},{})}});const Oi=Aa({sum_:function(e,t=null,n=!1){let r=Ea(e,"x","sum");"bool"===r.dtype&&(r=Ls(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return wa.runKernel(Nn,a,s)}});function Fi(e,t,n=null){if(0===e.rank)return Hs(e);if(1!==e.rank&&null===n)return Fi(vo(e,[-1]),t,n);if(1===e.rank||"number"===typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Oi(Hs(e),n);if(t===1/0)return Ci(Hs(e),n);if(t===-1/0)return $i(Hs(e),n);if("euclidean"===t||2===t)return _i(Oi(Ei(Hs(e),Ri(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Ci(Oi(Hs(e),n[0]),n[1]-1);if(t===1/0)return Ci(Oi(Hs(e),n[1]),n[0]);if(t===-1/0)return $i(Oi(Hs(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return _i(Oi(Ai(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Di=Aa({norm_:function(e,t="euclidean",n=null,r=!1){const a=Fi(e=Ea(e,"x","norm"),t,n);let s=a.shape;if(r){const t=y(n,e.shape);s=ki(a.shape,t)}return vo(a,s)}});const Mi=Aa({euclideanNorm_:function(e,t=null,n=!1){return Di(e,"euclidean",t,n)}});const Pi=Aa({exp_:function(e){const t={x:Ea(e,"x","exp")};return wa.runKernel(qe,t)}});const Li=Aa({expandDims_:function(e,t=0){const n=Ea(e,"x","expandDims","string_or_numeric");i(t<=n.rank,()=>"Axis must be <= rank of the tensor");const r={input:n},a={dim:t};return wa.runKernel(Ke,r,a)}});const Bi=Aa({expm1_:function(e){const t={x:Ea(e,"x","expm1")};return wa.runKernel(Xe,t)}});const Vi=Aa({tile_:function(e,t){const n=Ea(e,"x","tile","string_or_numeric");i(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const r={x:n},a={reps:t};return wa.runKernel(Un,r,a)}});const Wi=Aa({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=Ps([e,t],r),s=e<=t?e:t;for(let i=0;i<s;++i)a.set(1,i,i);const o=vo(a.toTensor(),[e,t]);if(null==n)return o;if(1===n.length)return Vi(Li(o,0),[n[0],1,1]);if(2===n.length)return Vi(Li(Li(o,0),0),[n[0],n[1],1,1]);if(3===n.length)return Vi(Li(Li(Li(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}});const zi=Aa({floor_:function(e){const t={x:Ea(e,"x","floor","float32")};return wa.runKernel(Je,t)}});const Ui=Aa({gather_:function(e,t,n=0,r=0){const a={x:Ea(e,"x","gather"),indices:Ea(t,"indices","gather","int32")},s={axis:n,batchDims:r};return wa.runKernel(nt,a,s)}});const Gi=Aa({greater_:function(e,t){let n=Ea(e,"a","greater","string_or_numeric"),r=Ea(t,"b","greater","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(at,a)}});const Hi=Aa({greaterEqual_:function(e,t){let n=Ea(e,"a","greaterEqual","string_or_numeric"),r=Ea(t,"b","greaterEqual","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(st,a)}});const ji=Aa({imag_:function(e){const t={input:Ea(e,"input","imag")};return wa.runKernel(ut,t)}});const qi=Aa({isFinite_:function(e){const t={x:Ea(e,"x","isFinite")};return wa.runKernel(lt,t)}});const Ki=Aa({isInf_:function(e){const t={x:Ea(e,"x","isInf")};return wa.runKernel(ct,t)}});const Xi=Aa({isNaN_:function(e){const t={x:Ea(e,"x","isNaN")};return wa.runKernel(dt,t)}});const Yi=Aa({leakyRelu_:function(e,t=.2){const n={x:Ea(e,"x","leakyRelu")},r={alpha:t};return wa.runKernel(pt,n,r)}});const Qi=Aa({less_:function(e,t){let n=Ea(e,"a","less","string_or_numeric"),r=Ea(t,"b","less","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(ht,a)}});const Zi=Aa({lessEqual_:function(e,t){let n=Ea(e,"a","lessEqual","string_or_numeric"),r=Ea(t,"b","lessEqual","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(ft,a)}});function Ji(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return wa.runKernel(mt,{},r)}const eu=Aa({localResponseNormalization_:function(e,t=5,n=1,r=1,a=.5){const s=Ea(e,"x","localResponseNormalization");i(4===s.rank||3===s.rank,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`),i(p(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={x:o},c={depthRadius:t,bias:n,alpha:r,beta:a},d=wa.runKernel(wt,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const tu=Aa({log_:function(e){const t={x:Ea(e,"x","log","float32")};return wa.runKernel(gt,t)}});const nu=Aa({log1p_:function(e){const t={x:Ea(e,"x","log1p")};return wa.runKernel(yt,t)}});function ru(e,t){i(S(e),()=>"The f passed in variableGrads(f) must be a function"),i(null==t||Array.isArray(t)&&t.every(e=>e instanceof Zr),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=null!=t;if(!n){t=[];for(const e in wa.registeredVariables)t.push(wa.registeredVariables[e])}const r=n?t.filter(e=>!e.trainable):null,a=t.length;i((t=t.filter(e=>e.trainable)).length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);const{value:s,grads:o}=wa.gradients(e,t,null,!0);i(o.some(e=>null!=e),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),i(0===s.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`);const u={};return t.forEach((e,t)=>{null!=o[t]&&(u[e.name]=o[t])}),null!=r&&r.forEach(e=>u[e.name]=null),{value:s,grads:u}}function au(e){return wa.customGrad(e)}const su=Aa({neg_:function(e){const t={x:Ea(e,"x","neg")};return wa.runKernel(Pt,t)}});const ou=Aa({softplus_:function(e){const t={x:Ea(e,"x","softplus")};return wa.runKernel(kn,t)}});const iu=Aa({logSigmoid_:function(e){const t=Ea(e,"x","logSigmoid");return au(e=>({value:su(ou(su(e))),gradFunc:t=>Gs(t,So(su(e)))}))(t)}});const uu=Aa({sub_:function(e,t){let n=Ea(e,"a","sub"),r=Ea(t,"b","sub");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Vn,a)}});const lu=Aa({logSoftmax_:function(e,t=-1){const n=Ea(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return au((e,n)=>{const r=Ci(e,t,!0),a=uu(e,r),s=uu(Ls(a,"float32"),tu(Oi(Pi(a),t,!0)));n([s]);return{value:s,gradFunc:(e,n)=>{const[r]=n,a=Pi(r);return uu(e,Gs(Oi(e,t,!0),a))}}})(n)}});const cu=Aa({logSumExp_:function(e,t=null,n=!1){const r=Ea(e,"x","logSumExp"),a=y(t,r.shape),s=Ci(r,a,!0),o=uu(r,s),i=Pi(o),u=Oi(i,a),l=tu(u),c=Ws(vo(s,l.shape),l);if(n){const e=ki(c.shape,a);return vo(c,e)}return c}});const du=Aa({logicalAnd_:function(e,t){const n=Ea(e,"a","logicalAnd","bool"),r=Ea(t,"b","logicalAnd","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(bt,a)}});const pu=Aa({logicalNot_:function(e){const t={x:Ea(e,"x","logicalNot","bool")};return wa.runKernel(xt,t)}});const hu=Aa({logicalOr_:function(e,t){const n=Ea(e,"a","logicalOr","bool"),r=Ea(t,"b","logicalOr","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(vt,a)}});const fu=Aa({logicalXor_:function(e,t){const n=Ea(e,"a","logicalXor","bool"),r=Ea(t,"b","logicalXor","bool");return li(n.shape,r.shape),du(hu(e,t),pu(du(e,t)))}}),mu=2147483648;const gu=Aa({searchSorted_:function(e,t,n="left"){const r=Ea(e,"sortedSequence","searchSorted"),a=Ea(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=vo(r,[-1,s]),u=vo(a,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(c(u.shape)>=mu)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=mu)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const l={sortedSequence:i,values:u},d={side:n};return wa.runKernel(fn,l,d)}});function yu(e,t){return gu(e,t,"left")}const bu=Aa({maxPool_:function(e,t,n,r,a){const s=Ea(e,"x","maxPool");let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),i(go(n,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`),xo("maxPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a},d=wa.runKernel(St,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const xu=Aa({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=Ea(e,"x","maxPool3d");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),xo("maxPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=wa.runKernel(Ct,c,d);return l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const vu=Aa({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:Ea(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=wa.runKernel(Et,s,o);return{result:i[0],indexes:i[1]}}});const wu=Aa({maximum_:function(e,t){let n=Ea(e,"a","maximum"),r=Ea(t,"b","maximum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Nt,a)}});const ku=Aa({mean_:function(e,t=null,n=!1){const r={x:Ea(e,"x","mean")},a={axis:t,keepDims:n};return wa.runKernel(Rt,r,a)}});function Iu(e,t="float32"){if(O(e),"complex64"===t){const t=Iu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=_(c(e),t);return wa.makeTensor(n,e,t)}function Nu(e,t="float32"){if(O(e),"complex64"===t){const t=Nu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=R(c(e),t);return wa.makeTensor(n,e,t)}function Su(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=Ea(e,"x","meshgrid",e instanceof Yr?e.dtype:"float32");if(void 0===t)return[r];let a=Ea(t,"y","meshgrid",t instanceof Yr?t.dtype:"float32");const s=c(r.shape),o=c(a.shape);return"xy"===n?(r=vo(r,[1,-1]),a=vo(a,[-1,1]),[No(Nu([o,1],r.dtype),r),No(a,Nu([1,s],a.dtype))]):(r=vo(r,[-1,1]),a=vo(a,[1,-1]),[No(r,Nu([1,o],r.dtype)),No(Nu([s,1],a.dtype),a)])}const Tu=Aa({minimum_:function(e,t){let n=Ea(e,"a","minimum"),r=Ea(t,"b","minimum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(At,a)}});const Cu=Aa({mirrorPad_:function(e,t,n){i("reflect"===n||"symmetric"===n,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const r=Ea(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");i(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);const a="reflect"===n?1:0;for(let u=0;u<r.rank;u++)i(2===t[u].length,()=>"Invalid number of paddings. Must be length of 2 each."),i(t[u][0]>=0&&t[u][0]<=r.shape[u]-a&&t[u][1]>=0&&t[u][1]<=r.shape[u]-a,()=>`Padding in dimension ${u} cannot be greater than or equal to ${r.shape[u]-a} or less than 0 for input of shape ${r.shape}`);const s={paddings:t,mode:n},o={x:r};return wa.runKernel(Ot,o,s)}});const $u=Aa({mod_:function(e,t){let n=Ea(e,"a","mod"),r=Ea(t,"b","mod");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Ft,a)}});const Eu=Aa({moments_:function(e,t=null,n=!1){const r=y(t,(e=Ea(e,"x","moments")).shape),a=ku(e,r,n);let s=a.shape;n||(s=ki(a.shape,r));const o=Ai(uu(Ls(e,"float32"),vo(a,s)));return{mean:a,variance:ku(o,r,n)}}});const Ru=Aa({multiRNNCell_:function(e,t,n,r){const a=Ea(t,"data","multiRNNCell"),s=Ra(n,"c","multiRNNCell"),o=Ra(r,"h","multiRNNCell");let i=a;const u=[];for(let d=0;d<e.length;d++){const t=e[d](i,s[d],o[d]);u.push(t[0]),u.push(t[1]),i=t[1]}const l=[],c=[];for(let d=0;d<u.length;d+=2)l.push(u[d]),c.push(u[d+1]);return[l,c]}});const _u=Aa({multinomial_:function(e,t,n,r=!1){const a=Ea(e,"logits","multinomial"),s=a.size,o=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?vo(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=wa.runKernel(Dt,i,u);return 1===o?vo(l,[l.size]):l}});const Au=Aa({notEqual_:function(e,t){let n=Ea(e,"a","notEqual","string_or_numeric"),r=Ea(t,"b","notEqual","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Lt,a)}});const Ou=Aa({oneHot_:function(e,t,n=1,r=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:Ea(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return wa.runKernel(Ut,s,o)}});const Fu=Aa({onesLike_:function(e){const t={x:Ea(e,"x","onesLike")};return wa.runKernel(zt,t)}});const Du=Aa({outerProduct_:function(e,t){const n=Ea(e,"v1","outerProduct"),r=Ea(t,"v2","outerProduct");i(1===n.rank&&1===r.rank,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const a=vo(n,[-1,1]),s=vo(r,[1,-1]);return No(a,s)}});const Mu=Aa({pad_:function(e,t,n=0){const r=Ea(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},s={x:r};return wa.runKernel(Ht,s,a)}});const Pu=Aa({pad1d_:function(e,t,n=0){return i(2===t.length,()=>"Invalid number of paddings. Must be length of 2."),Mu(e,[t],n)}});const Lu=Aa({pad2d_:function(e,t,n=0){return i(2===t.length&&2===t[0].length&&2===t[1].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Bu=Aa({pad3d_:function(e,t,n=0){return i(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Vu=Aa({pad4d_:function(e,t,n=0){return i(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Wu=Aa({spaceToBatchND_:function(e,t,n){const r=Ea(e,"x","spaceToBatchND");i(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),i(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),i(r.shape.reduce((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]===0:e,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const a={x:r},s={blockShape:t,paddings:n};return wa.runKernel(Sn,a,s)}});const zu=Aa({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const u=Ea(e,"x","maxPool");let l=u,c=!1;3===u.rank&&(c=!0,l=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(go(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);const d=so(l.shape,t,s,a,r),p=[d.dilationHeight,d.dilationWidth];let h;h="same"===r?function(e,t){const n=e.map((e,n)=>e+(e-1)*(t[n]-1)),r=n.map(e=>e-1),a=r.map(e=>Math.floor(e/2)),s=r.map((e,t)=>e-a[t]);return r.map((e,t)=>[a[t],s[t]])}([d.filterHeight,d.filterWidth],p):[[0,0],[0,0]];const f=1===p[0]&&1===p[1],[m,g]=function(e,t,n){const r=n.map(e=>e[0]),a=n.map(e=>e[1]),s=e.concat(r,a),o=t.map((e,t)=>(e-s[t]%e)%e),i=a.map((e,t)=>e+o[t]),u=t.map((e,t)=>[r[t],i[t]]),l=t.map((e,t)=>[0,o[t]]);return[u,l]}([d.inHeight,d.inWidth],p,h),y=f?r:"valid",b=f?l:Wu(l,p,m),x=("avg"===n?()=>wo(b,t,s,y,o):()=>bu(b,t,s,y,o))(),v=f?x:Eo(x,p,g);return c?vo(v,[v.shape[1],v.shape[2],v.shape[3]]):v}});const Uu=Aa({prelu_:function(e,t){const n={x:Ea(e,"x","prelu"),alpha:Ea(t,"alpha","prelu")};return wa.runKernel(qt,n)}});const Gu=Aa({prod_:function(e,t=null,n=!1){let r=Ea(e,"x","prod");"bool"===r.dtype&&(r=Ls(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return wa.runKernel(Kt,a,s)}});const Hu=Aa({raggedGather_:function(e,t,n,r){const a={paramsNestedSplits:e.map((e,t)=>Ea(e,`tensors${t}`,"raggedGather","int32")),paramsDenseValues:Ea(t,"paramsDenseValues","raggedGather"),indices:Ea(n,"indices","raggedGather","int32")},s={outputRaggedRank:r},o=wa.runKernel(Xt,a,s);return{outputNestedSplits:o.slice(0,o.length-1),outputDenseValues:o[o.length-1]}}});const ju=Aa({raggedRange_:function(e,t,n){const r=Ea(e,"starts","raggedRange"),a={starts:r,limits:Ea(t,"limits","raggedRange",r.dtype),deltas:Ea(n,"deltas","raggedRange",r.dtype)},s=wa.runKernel(Yt,a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}});const qu=Aa({raggedTensorToTensor_:function(e,t,n,r,a){const s=Ea(e,"shape","raggedTensorToTensor","int32"),o=Ea(t,"values","raggedTensorToTensor"),i={shape:s,values:o,defaultValue:Ea(n,"defaultValue","raggedTensorToTensor",o.dtype),rowPartitionTensors:r.map((e,t)=>Ea(e,`tensors${t}`,"raggedTensorToTensor","int32"))},u={rowPartitionTypes:a};return wa.runKernel(Qt,i,u)}});const Ku=Aa({rand_:function(e,t,n){O(e);const r=c(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let s=0;s<r;s++)a[s]=t();return wa.makeTensor(a,e,n)}});var Xu,Yu={exports:{}};function Qu(){return Xu||(Xu=1,function(e,t){function n(e){var t=this,n=function(){var e=4022871197,t=function(t){t=String(t);for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function r(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var a=new n(e),s=t&&t.state,o=a.next;return o.int32=function(){return 4294967296*a.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,Yu)),Yu.exports}var Zu,Ju={exports:{}};var el,tl={exports:{}};var nl,rl={exports:{}};var al,sl={exports:{}};var ol,il={exports:{}};var ul={exports:{}};const ll=gr(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var cl,dl,pl,hl=ul.exports;function fl(){return cl||(cl=1,e=ul,function(t,n,r){var a,s=256,o="random",i=r.pow(s,6),u=r.pow(2,52),l=2*u,c=255;function d(e,c,d){var y=[],b=m(f((c=1==c?{entropy:!0}:c||{}).entropy?[e,g(n)]:e??function(){try{var e;return a&&(e=a.randomBytes)?e=e(s):(e=new Uint8Array(s),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(i){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,g(n)]}}(),3),y),x=new p(y),v=function(){for(var e=x.g(6),t=i,n=0;e<u;)e=(e+n)*s,t*=s,n=x.g(1);for(;e>=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return v.int32=function(){return 0|x.g(4)},v.quick=function(){return x.g(4)/4294967296},v.double=v,m(g(x.S),n),(c.pass||d||function(e,t,n,a){return a&&(a.S&&h(a,x),e.state=function(){return h(x,{})}),n?(r[o]=e,t):e})(v,b,"global"in c?c.global:this==r,c.state)}function p(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a<s;)i[a]=a++;for(a=0;a<s;a++)i[a]=i[o=c&o+e[a%n]+(t=i[a])],i[o]=t;(r.g=function(e){for(var t,n=0,a=r.i,o=r.j,i=r.S;e--;)t=i[a=c&a+1],n=n*s+i[c&(i[a]=i[o=c&o+t])+(i[o]=t)];return r.i=a,r.j=o,n})(s)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){var n,r=[],a=typeof e;if(t&&"object"==a)for(n in e)try{r.push(f(e[n],t-1))}catch(s){}return r.length?r:"string"==a?e:e+"\0"}function m(e,t){for(var n,r=e+"",a=0;a<r.length;)t[c&a]=c&(n^=19*t[c&a])+r.charCodeAt(a++);return g(t)}function g(e){return String.fromCharCode.apply(0,e)}if(m(r.random(),n),e.exports){e.exports=d;try{a=ll}catch(y){}}else r["seed"+o]=d}("undefined"!==typeof self?self:hl,[],Math)),ul.exports;var e}var ml=function(){if(pl)return dl;pl=1;var e=Qu(),t=(Zu||(Zu=1,function(e,t){function n(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,Ju)),Ju.exports),n=(el||(el=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,tl)),tl.exports),r=(nl||(nl=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.x&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,rl)),rl.exports),a=(al||(al=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s<u;++s)t&&(r^=t.charCodeAt((s+32)%t.length)),0===s&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.X&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,sl)),sl.exports),s=(ol||(ol=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,il)),il.exports),o=fl();return o.alea=e,o.xor128=t,o.xorwow=n,o.xorshift7=r,o.xor4096=a,o.tychei=s,dl=o}();class gl{constructor(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const s=a||Math.random();this.random=ml.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,a,s;do{r=2*this.random()-1,a=2*this.random()-1,s=r*r+a*a}while(s>=1||0===s);const o=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*a*o,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class yl{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ml.alea(a.toString()),this.randn=new gl(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,a,s;for(;;){do{r=this.randn.nextValue(),s=1+this.c*r}while(s<=0);if(s*=s*s,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class bl{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"===typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ml.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const xl=Aa({randomGamma_:function(e,t,n=1,r="float32",a){if(O(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new yl(t,n,r,a),o=Ps(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=s.nextValue();return o.toTensor()}});const vl=Aa({randomNormal_:function(e,t=0,n=1,r,a){if(O(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new gl(t,n,r,!1,a),o=Ps(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=s.nextValue();return o.toTensor()}});const wl=Aa({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return vl(e,0,1,t,n)}});const kl=Aa({randomUniform_:function(e,t=0,n=1,r="float32",a){O(e);const s=Ps(e,r),o=new bl(t,n,null,a);for(let i=0;i<s.values.length;i++)s.values[i]=o.nextValue();return s.toTensor()}});const Il=Aa({randomUniformInt_:function(e,t,n,r){return kl(e,t,n,"int32",r)}});function Nl(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:r};return wa.runKernel(Zt,{},a)}const Sl=Aa({real_:function(e){const t={input:Ea(e,"input","real")};return wa.runKernel(Jt,t)}});const Tl=Aa({reciprocal_:function(e){const t={x:Ea(e,"x","reciprocal")};return wa.runKernel(en,t)}});const Cl=Aa({relu_:function(e){const t={x:Ea(e,"x","relu")};return wa.runKernel(tn,t)}});const $l=Aa({relu6_:function(e){const t={x:Ea(e,"x","relu6")};return wa.runKernel(un,t)}});const El=Aa({reverse_:function(e,t){const n={x:Ea(e,"x","reverse")},r={dims:t};return wa.runKernel(ln,n,r)}});const Rl=Aa({reverse1d_:function(e){const t=Ea(e,"x","reverse");return i(1===t.rank,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),El(t,0)}});const _l=Aa({reverse2d_:function(e,t){const n=Ea(e,"x","reverse");return i(2===n.rank,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),El(n,t)}});const Al=Aa({reverse3d_:function(e,t){const n=Ea(e,"x","reverse");return i(3===n.rank,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),El(n,t)}});const Ol=Aa({reverse4d_:function(e,t){const n=Ea(e,"x","reverse");return i(4===n.rank,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),El(n,t)}});const Fl=Aa({round_:function(e){const t={x:Ea(e,"x","round")};return wa.runKernel(cn,t)}});const Dl=Aa({rsqrt_:function(e){const t={x:Ea(e,"x","rsqrt","float32")};return wa.runKernel(dn,t)}});const Ml=Aa({selu_:function(e){const t={x:Ea(e,"x","selu")};return wa.runKernel(gn,t)}});const Pl=Aa({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const u=Ea(e,"x","separableConv2d"),l=Ea(t,"depthwiseFilter","separableConv2d"),c=Ea(n,"pointwiseFilter","separableConv2d");let d=u,p=!1;if(3===u.rank&&(p=!0,d=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");i(4===d.rank,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),i(4===l.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),i(4===c.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),i(1===c.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),i(1===c.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const h=l.shape[2],f=l.shape[3];i(c.shape[2]===h*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*f}, but got ${c.shape[2]}.`);const m=ai(d,l,r,a,o,s),g=Ho(m,c,1,"valid",o);return p?vo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Ll=async function(e,t){const n=Ea(e,"x","setdiff1d"),r=Ea(t,"y","setdiff1d");i(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),i(1===n.rank,()=>`x should be 1D tensor, but got x (${n.shape}).`),i(1===r.rank,()=>`y should be 1D tensor, but got y (${r.shape}).`);const a=await n.data(),s=await r.data(),o=new Set(s);let u=0;for(let i=0;i<a.length;i++)o.has(a[i])||u++;const l=new qr([u],n.dtype),c=new qr([u],"int32");for(let i=0,d=0;i<a.length;i++)o.has(a[i])||(l.values[d]=a[i],c.values[d]=i,d++);return[l.toTensor(),c.toTensor()]};const Bl=Aa({sign_:function(e){const t={x:Ea(e,"x","sign")};return wa.runKernel(vn,t)}});const Vl=Aa({sin_:function(e){const t={x:Ea(e,"x","sin","float32")};return wa.runKernel(bn,t)}});const Wl=Aa({sinh_:function(e){const t={x:Ea(e,"x","sinh")};return wa.runKernel(xn,t)}});const zl=Aa({slice1d_:function(e,t,n){const r=Ea(e,"x","slice1d");return i(1===r.rank,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),To(r,[t],[n])}});const Ul=Aa({slice2d_:function(e,t,n){const r=Ea(e,"x","slice2d");return i(2===r.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Gl=Aa({slice3d_:function(e,t,n){const r=Ea(e,"x","slice3d");return i(3===r.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Hl=Aa({slice4d_:function(e,t,n){const r=Ea(e,"x","slice4d");return i(4===r.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const jl=Aa({softmax_:function(e,t=-1){const n=Ea(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},a={dim:t};return wa.runKernel(Cn,r,a)}});const ql=Aa({fft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(Ye,t)}});const Kl=Aa({ifft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(it,t)}});const Xl=Aa({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=vo(e,[n,t]);r=Kl(a)}else{const a=[n,2*(t-1)],s=vo(Sl(e),[n,t]),o=vo(ji(e),[n,t]),i=El(To(s,[0,1],[n,t-2]),1),u=Gs(El(To(o,[0,1],[n,t-2]),1),Ri(-1)),l=Io([s,i],1),c=Io([o,u],1),d=vo(Oa(l,c),[a[0],a[1]]);r=Kl(d)}if(r=Sl(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=vo(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const Yl=Aa({split_:function(e,t,n=0){const r={x:Ea(e,"x","split")},a={numOrSizeSplits:t,axis:n};return wa.runKernel(Tn,r,a)}});const Ql=Aa({rfft_:function(e,t){i("float32"===e.dtype,()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t<n){const r=e.shape.map(e=>0),s=e.shape.map(e=>e);s[e.shape.length-1]=t,a=To(e,r,s),n=t}else if(null!=t&&t>n){const r=e.shape.map(e=>e);r[e.shape.length-1]=t-n,a=Io([e,Iu(r)],e.shape.length-1),n=t}else a=e;const s=pi(a),o=vo(Oa(a,s),[r,n]),u=ql(o),l=Math.floor(n/2)+1,c=Sl(u),d=ji(u),p=Yl(c,[l,n-l],c.shape.length-1),h=Yl(d,[l,n-l],d.shape.length-1),f=a.shape.slice();return f[a.shape.length-1]=l,vo(Oa(p[0],h[0]),f)}});const Zl=Aa({squaredDifference_:function(e,t){let n=Ea(e,"a","squaredDifference"),r=Ea(t,"b","squaredDifference");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(On,a,{})}});const Jl=Aa({squeeze_:function(e,t){const n=Ea(e,"x","squeeze","string_or_numeric");return vo(n,b(n.shape,t).newShape)}});const ec=Aa({stack_:function(e,t=0){const n=Ra(e,"tensors","stack","string_or_numeric");i(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&i(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");const r=n,a={axis:t};return wa.runKernel(Gt,r,a)}});const tc=Aa({step_:function(e,t=0){const n={x:Ea(e,"x","step")},r={alpha:t};return wa.runKernel(Qn,n,r)}});const nc=Aa({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:Ea(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return wa.runKernel(Mn,l,c)}});const rc=Aa({tan_:function(e){const t={x:Ea(e,"x","tan","float32")};return wa.runKernel(Wn,t)}});function ac(e,t){l(e);const n=Ta(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Fa(e,null,n,t)}function sc(e,t,n){if(l(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Ta(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Fa(e,t,r,n)}function oc(e,t,n){if(l(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Ta(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function ic(e,t,n){if(l(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Ta(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function uc(e,t,n){if(l(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Ta(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function lc(e,t,n){if(l(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Ta(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Fa(e,t=t||r,r,n)}function cc(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<r+(n.rank-a))throw new Error(s+` Output shape length < ${r+(n.rank-a)}`);if(n.rank!==a+e.length-r)throw new Error(s+" update.rank != "+(a+e.length-r));for(let o=0;o<a;++o)if(n.shape[o]!==t.shape[o])throw new Error(s+` updates.shape[${o}] (${n.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<n.rank-a;++o)if(n.shape[o+a]!==e[o+r])throw new Error(s+` updates.shape[${o+a}] (${n.shape[o+a]}) != shape[${o+a}] (${e[o+a]})`)}function dc(e,t,n){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(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}cc(n,t,e)}function pc(e,t,n){const r=t.shape.length,a=r>1?t.shape[r-1]:1,s=n.length;let o=1;for(let u=a;u<s;++u)o*=n[u];const i=a<1?1:a;return{sliceRank:a,numUpdates:c(t.shape)/i,sliceSize:o,strides:[...C(n.slice(0,a)),1],outputSize:c(n)}}const hc=Aa({tensorScatterUpdate_:function(e,t,n){const r=Ea(e,"tensor","tensorScatterupdate"),a=Ea(t,"indices","tensorScatterupdate","int32"),s=Ea(n,"updates","tensorScatterupdate");if(dc(s,a,r.shape),r.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${r.dtype} and ${s.dtype}.`);const o={tensor:r,indices:a,updates:s};return wa.runKernel(hn,o,{})}});const fc=Aa({topk_:function(e,t=1,n=!0){const r=Ea(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const a=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const s={x:r},o={k:t,sorted:n},[i,u]=wa.runKernel(Gn,s,o);return{values:i,indices:u}}});const mc=Aa({truncatedNormal_:function(e,t=0,n=1,r,a){if(O(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new gl(t,n,r,!0,a),o=Ps(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=s.nextValue();return o.toTensor()}});const gc=Aa({unique_:function(e,t=0){const n=Ea(e,"x","unique","string_or_numeric");i(n.rank>0,()=>"The input tensor must be at least 1D");const r={x:n},a={axis:t},[s,o]=wa.runKernel(qn,r,a);return{values:s,indices:o}}});const yc=Aa({unsortedSegmentSum_:function(e,t,n){const r=Ea(e,"x","unsortedSegmentSum"),a=Ea(t,"segmentIds","unsortedSegmentSum","int32");i(p(n),()=>"numSegments must be of dtype int");const s={x:r,segmentIds:a},o={numSegments:n};return wa.runKernel(Xn,s,o)}});const bc=Aa({unstack_:function(e,t=0){const n=Ea(e,"x","unstack","string_or_numeric");i(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);const r={value:n},a={axis:t};return wa.runKernel(Kn,r,a)}});function xc(e,t){return gu(e,t,"right")}function vc(e,t=!0,n,r){return wa.makeVariable(e,t,n,r)}function wc(e,t){const n=[];for(let s=0;s<t.length;s++)t[s]&&n.push(s);const r=Ps(e,"int32"),a=Ps([n.length,e.length],"int32");for(let s=0;s<n.length;s++){const t=r.indexToLoc(n[s]),o=s*e.length;a.values.set(t,o)}return a.toTensor()}const kc=async function(e){const t=Ea(e,"condition","whereAsync","bool"),n=await t.data(),r=wc(t.shape,n);return e!==t&&t.dispose(),r};const Ic=async function(e,t,n){const r=Ea(e,"tensor","boolMask"),a=Ea(t,"mask","boolMask","bool"),s=n??0,o=a.rank,l=r.shape;i(o>0,()=>"mask cannot be scalar"),u(l.slice(s,s+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let i=s;i<s+o;i++)c*=l[i];const d=l.slice(0,s).concat([c],l.slice(s+o)),p=vo(r,d),h=vo(a,[-1]),f=await kc(h),m=Jl(f,[1]),g=Ui(p,m,s);return e!==r&&r.dispose(),t!==a&&a.dispose(),m.dispose(),p.dispose(),h.dispose(),f.dispose(),g};const Nc=Aa({transpose_:function(e,t,n){const r=Ea(e,"x","transpose");if(null==t&&(t=r.shape.map((e,t)=>t).reverse()),i(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`),t.forEach(e=>{i(e>=0&&e<r.rank,()=>`All entries in 'perm' must be between 0 and ${r.rank-1} but got ${t}`)}),r.rank<=1)return r.clone();const a={x:r},s={perm:t};return"complex64"===r.dtype?Ba(()=>{let e=Sl(r),t=ji(r);return e=wa.runKernel(jn,{x:e},s),t=wa.runKernel(jn,{x:t},s),n&&(t=su(t)),Oa(e,t)}):wa.runKernel(jn,a,s)}});const Sc=Aa({movingAverage_:function(e,t,n,r,a=!0){const s=Ea(e,"v","movingAverage"),o=Ea(t,"x","movingAverage"),u=Ea(n,"decay","movingAverage");var l,c;c=o,i((l=s).dtype===c.dtype,()=>`The dtypes of the first(${l.dtype}) and second(${c.dtype}) input must match`),i(d(s.shape,o.shape),()=>"Shape mismatch in v and x");const p=Ri(1),h=uu(p,u);let f=Gs(uu(o,s),h);if(a){i(null!=r,()=>"When using zeroDebias: true, step is required.");const e=Ea(r,"step","movingAverage");f=Us(f,uu(p,Ei(u,e)))}return Ws(s,f)}});const Tc=Aa({scatterND_:function(e,t,n){O(n);const r=Ea(e,"indices","scatterND","int32"),a=Ea(t,"updates","scatterND");dc(a,r,n);const s={indices:r,updates:a},o={shape:n};return wa.runKernel(pn,s,o)}});const Cc=Aa({sparseToDense_:function(e,t,n,r=0){O(n);const a=Ea(e,"sparseIndices","sparseToDense","int32"),s=Ea(t,"sparseValues","sparseToDense","string_or_numeric"),o=Ea(r,"defaultValue","sparseToDense",s.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);const o=t.size;if(0!==t.rank&&(1!==t.rank||o!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,s,n,o);const i={sparseIndices:a,sparseValues:s,defaultValue:o},u={outputShape:n};return wa.runKernel(An,i,u)}});const $c=Aa({gatherND_:function(e,t){const n=Ea(t,"indices","gatherND","int32"),r={params:Ea(e,"x","gatherND","string_or_numeric"),indices:n};return wa.runKernel(rt,r)}});const Ec=Aa({dropout_:function(e,t,n,r){const a=Ea(e,"x","dropout");if(i("float32"===a.dtype,()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`),i(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return e instanceof Yr?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(d(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(a,n),o=1-t,u=Us(zi(Ws(kl(s,0,1,"float32",r),o)),o);return Gs(a,u)}});function Rc(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function _c(e,t,n){const r=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){const o=2*Math.PI*s/(e+r-1);a[s]=t-n*Math.cos(o)}return ac(a,"float32")}const Ac=async function(e,t,n=1){const r=Ea(e,"predictions","inTopK"),a=Ea(t,"targets","inTopK");i(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),i(r.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`),u(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const s=r.shape[r.shape.length-1];i(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);const o=await r.data(),l=await a.data(),[c,d]=[o.length/s,s],p=x("bool",c);for(let i=0;i<c;i++){const e=i*d,t=o.subarray(e,e+d),r=[];for(let n=0;n<t.length;n++)r.push({value:t[n],index:n});r.sort((e,t)=>t.value-e.value),p[i]=0;for(let a=0;a<n;a++)if(r[a].index===l[i]){p[i]=1;break}}return e!==r&&r.dispose(),t!==a&&a.dispose(),Da(p,a.shape,"bool")};const Oc=Aa({conv2DBackpropFilter_:function(e,t,n,r,a,s="NHWC",o){let u=e;3===e.rank&&(u=vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]])),i(4===u.rank,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${u.shape}.`),i(4===l.rank,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),i(4===n.length,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const c="NHWC"===s?u.shape[3]:u.shape[1],d="NHWC"===s?l.shape[3]:l.shape[1];i(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),i(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),xo("conv2dDerFilter",a,o);const p={x:u,dy:l},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return wa.runKernel(we,p,h)}});function Fc(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Gs(e,tc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Dc(e,t){let n=t;const r=ui(e.shape,t.shape);return r.length>0&&(n=Oi(n,r)),vo(n,e.shape)}function Mc(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Cl(e);if("elu"===t)return gi(e);if("relu6"===t)return $l(e);if("prelu"===t)return Uu(e,n);if("leakyrelu"===t)return Yi(e,r);if("sigmoid"===t)return So(e);throw new Error(`Unknown fused activation ${t}.`)}const Pc=(e,t)=>!(e>0)||"linear"===t;const Lc=Aa({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(l=l||"linear",!1===Pc(wa.state.gradientDepth,l)){i("NHWC"===a,()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let p=Ho(e,t,n,r,a,s,o);return null!=u&&(p=Ws(p,u)),Mc(p,l,c,d)}const p=Ea(e,"x","conv2d","float32"),h=Ea(t,"filter","conv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),xo("fused conv2d",r,o);const g="NHWC"===a?f.shape[3]:f.shape[1];i(h.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${h.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);const y=io(f.shape,h.shape,n,s,r,o);let b,x;if(null!=u&&(b=Ea(u,"bias","fused conv2d"),[b]=fa(b,p),"NHWC"===a?li(y.outShape,b.shape):(i(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),i(0===b.shape.length||b.shape[0]===y.outChannels||1===b.shape[0],()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${y.outChannels})`))),null!=c){const e=c.shape;if(i(e.length<=1||3===e.length,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`),1===e.length)i(1===e[0]||e[0]===y.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${y.outChannels}).`);else if(3===e.length)try{li(e,y.outShape)}catch(I){const t=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${y.outShape}).`;throw Error(t)}x=Ea(c,"prelu weights","fused conv2d")}const v=(e,t)=>{i("NHWC"===a,()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`);const[o,u,c,d]=t,p=Fc(e,c,l);i(mo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const h=[qo(u.shape,p,o,n,r),Oc(u,p,o.shape,n,r)];if(null!=d){const e=Dc(d,p);h.push(e)}return h},w={x:f,filter:h,bias:b,preluActivationWeights:x},k={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(tr,w,k);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:v}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(tr,w,k);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:v}})(f,h,b)}});const Bc=Aa({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:i,dy:u},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return wa.runKernel(Fe,l,c)}});const Vc=Aa({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:i,filter:n},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e},d=wa.runKernel(De,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Wc=Aa({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(!1===Pc(wa.state.gradientDepth,l)){let i=ai(e,t,n,r,a,s,o);return null!=u&&(i=Ws(i,u)),Mc(i,l,c,d)}const p=Ea(e,"x","depthwiseConv2d","float32"),h=Ea(t,"filter","depthwiseConv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),i(f.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),null==s&&(s=[1,1]),i(go(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),xo("fused depthwiseConv2d",r,o);const g=io(f.shape,h.shape,n,s,r,o,!0);let y,b;null!=u&&(y=Ea(u,"bias","fused conv2d"),[y]=fa(y,p),li(g.outShape,y.shape)),null!=c&&(b=Ea(c,"prelu weights","fused depthwiseConv2d"));const x=(e,t)=>{i(mo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[a,u,c,d]=t,p=Fc(e,c,l),h=Vc(u.shape,p,a,n,r,s,o),f=Bc(u,p,a.shape,n,r,s,o);if(null!=d){return[h,f,Dc(y,p)]}return[h,f]},v={x:f,filter:h,bias:y,preluActivationWeights:b},w={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(nr,v,w);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(nr,v,w);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:x}})(f,h,y)}});const zc=Aa({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:u=.2}){if(!1===Pc(wa.state.gradientDepth,s)){let i=No(e,t,n,r);return null!=a&&(i=Ws(i,a)),Mc(i,s,o,u)}let l=Ea(e,"a","fused matMul"),d=Ea(t,"b","fused matMul");[l,d]=fa(l,d);const p=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=r?d.shape[d.rank-1]:d.shape[d.rank-2],f=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=r?d.shape[d.rank-2]:d.shape[d.rank-1],g=l.shape.slice(0,-2),y=d.shape.slice(0,-2),b=c(g),x=c(y);i(p===h,()=>`Error in fused matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${l.shape} and ${d.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=li(l.shape.slice(0,-2),d.shape.slice(0,-2)).concat([f,m]),w=vo(l,n?[b,p,f]:[b,f,p]),k=vo(d,r?[x,m,h]:[x,h,m]);let I,N;null!=a&&(I=Ea(a,"bias","fused matMul"),[I]=fa(I,l),li(v,I.shape)),null!=o&&(N=Ea(o,"prelu weights","fused matMul"));const S=(e,t)=>{const[o,i,u,l]=t,c=Fc(vo(e,u.shape),u,s);let d,p;if(n||r?!n&&r?(d=No(c,i,!1,!1),p=No(c,o,!0,!1)):n&&!r?(d=No(i,c,!1,!0),p=No(o,c,!1,!1)):(d=No(i,c,!0,!0),p=No(c,o,!0,!0)):(d=No(c,i,!1,!0),p=No(o,c,!0,!1)),null!=a){return[d,p,Dc(l,c)]}return[d,p]},T={a:w,b:k,bias:I,preluActivationWeights:N},C={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:u};if(null==a){return au((e,t,n)=>{const r=wa.runKernel(er,T,C);return n([e,t,r]),{value:vo(r,v),gradFunc:S}})(w,k)}return au((e,t,n,r)=>{const a=wa.runKernel(er,T,C);return r([e,t,a,n]),{value:vo(a,v),gradFunc:S}})(w,k,I)}}),Uc=Object.freeze(Object.defineProperty({__proto__:null,conv2d:Lc,depthwiseConv2d:Wc,matMul:zc},Symbol.toStringTag,{value:"Module"}));const Gc=Aa({hammingWindow_:function(e){return _c(e,.54,.46)}});const Hc=Aa({hannWindow_:function(e){return _c(e,.5,.5)}});const jc=Aa({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(To(e,s,t)),s+=n;if(r)for(;s<e.size;){const r=s+t-e.size,i=Io([To(e,s,t-r),Bo([r],a)]);o.push(i),s+=n}return 0===o.length?sc([],[0,t]):vo(Io(o),[o.length,t])}});const qc=Aa({stft_:function(e,t,n,r,a=Hc){null==r&&(r=Rc(t));const s=jc(e,t,n),o=Gs(s,a(t));return Ql(o,r)}});const Kc=Aa({cropAndResize_:function(e,t,n,r,a="bilinear",s=0){const o=Ea(e,"image","cropAndResize"),u=Ea(t,"boxes","cropAndResize","float32"),l=Ea(n,"boxInd","cropAndResize","int32"),c=u.shape[0];i(4===o.rank,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&4===u.shape[1],()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${u.shape}.`),i(1===l.rank&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${u.shape}.`),i(2===r.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),i(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),i("bilinear"===a||"nearest"===a,()=>`method must be bilinear or nearest, but was ${a}`);const d={image:o,boxes:u,boxInd:l},p={method:a,extrapolationValue:s,cropSize:r};return wa.runKernel(Re,d,p)}});const Xc=Aa({flipLeftRight_:function(e){const t=Ea(e,"image","flipLeftRight","float32");i(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t};return wa.runKernel(Ze,n,{})}});const Yc=Aa({grayscaleToRGB_:function(e){const t=Ea(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),i(1===r,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Vi(t,a)}});const Qc=Aa({rgbToGrayscale_:function(e){const t=Ea(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),i(3===r,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const a=t.dtype,s=Ls(t,"float32"),o=ac([.2989,.587,.114]);let u;switch(t.rank){case 2:u=mi("ij,j->i",s,o);break;case 3:u=mi("ijk,k->ij",s,o);break;case 4:u=mi("ijkl,l->ijk",s,o);break;case 5:u=mi("ijklm,m->ijkl",s,o);break;case 6:u=mi("ijklmn,n->ijklm",s,o);break;default:throw new Error("Not a valid tensor rank.")}return u=Li(u,-1),Ls(u,a)}});const Zc=Aa({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Ea(e,"image","rotateWithOffset","float32");i(4===a.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);const s={image:a},o={radians:t,fillValue:n,center:r};return wa.runKernel(Jn,s,o)}});function Jc(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const o=e.shape[0];return n=Math.min(n,o),i(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),i(2===e.rank,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),i(4===e.shape[1],()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),i(1===t.rank,()=>"scores must be a 1D tensor"),i(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),i(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const ed=Aa({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppression","float32"),o=Ea(t,"scores","nonMaxSuppression","float32"),i=Jc(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return wa.runKernel(Bt,{boxes:s,scores:o},u)}});function td(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r<a;){s=r+(a-r>>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||nd)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function nd(e,t){return e>t?1:e<t?-1:0}function rd(e,t,n,r,a){return od(e,t,n,r,a,0)}function ad(e,t,n,r,a,s){return od(e,t,n,r,a,0,!1,s,!0)}function sd(e,t,n,r,a,s){return od(e,t,n,r,a,s,!0)}function od(e,t,n,r,a,s,o=!1,i=!1,u=!1){const l=[];for(let g=0;g<t.length;g++)t[g]>a&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(ld);const c=s>0?-.5/s:0,d=[],p=[];for(;d.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n<a)break;let i=!1;for(let u=d.length-1;u>=o;--u){const n=id(e,s,d[u]);if(n>=r){i=!0;break}if(t.score=t.score*ud(r,c,n),t.score<=a)break}t.suppressBeginIndex=d.length,i||(t.score===n?(d.push(s),p.push(t.score)):t.score>a&&td(l,t,ld))}const h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:d};return o&&(m.selectedScores=p),u&&(m.validOutputs=h),m}function id(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(i-s)*(u-o),f=(d-l)*(p-c);if(h<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,d),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(h+f-x)}function ud(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function ld(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const cd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppressionAsync"),o=Ea(t,"scores","nonMaxSuppressionAsync"),i=Jc(s,o,n,r,a);n=i.maxOutputSize,r=i.iouThreshold,a=i.scoreThreshold;const u=await Promise.all([s.data(),o.data()]),l=u[0],c=u[1],{selectedIndices:d}=rd(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),ac(d,"int32")};const dd=Aa({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,s),l={boxes:o,scores:i},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:s=u.softNmsSigma},d=wa.runKernel(Wt,l,c);return{selectedIndices:d[0],selectedScores:d[1]}}});const pd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([o.data(),i.data()]),c=l[0],d=l[1],{selectedIndices:p,selectedScores:h}=sd(c,d,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(p,"int32"),selectedScores:ac(h)}};const hd=Aa({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},d=wa.runKernel(Vt,l,c);return{selectedIndices:d[0],validOutputs:d[1]}}});const fd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,null),l=u.maxOutputSize,c=u.iouThreshold,d=u.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=ad(p,h,l,c,d,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(f,"int32"),validOutputs:Ri(m,"int32")}};const md=Aa({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeBilinear");i(3===a.rank||4===a.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),i(!1===r||!1===n,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(sn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const gd=Aa({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeNearestNeighbor");i(3===a.rank||4===a.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),i("float32"===a.dtype||"int32"===a.dtype,()=>"`images` must have `int32` or `float32` as dtype"),i(!1===r||!1===n,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(rn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const yd=Aa({threshold_:function(e,t="binary",n=!1,r=.5){const a=Ea(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,u,l,c,d=Gs(ac([r]),255);if(i(3===a.rank,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),i(3===a.shape[2]||1===a.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),i("int32"===a.dtype||"float32"===a.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),i("otsu"===t||"binary"===t,()=>`Method must be binary or otsu, but was ${t}`),3===a.shape[2]){[o,u,l]=Yl(a,[1,1,1],-1);const e=Gs(o,.2989),t=Gs(u,.587),n=Gs(l,.114);c=Ws(Ws(e,t),n)}else c=e;if("otsu"===t){d=function(e,t){let n,r,a,s,o,i,u=ac([-1]),l=ac([0]),c=ac([0]);for(let d=0;d<e.size-1;d++){n=To(e,0,d+1),r=To(e,d+1),o=Us(Oi(n),t),i=Us(Oi(r),t);const p=Oi(Gs(n,Nl(0,n.size)));a=Us(p,Oi(n));const h=Bo(r.shape,n.size),f=Ws(Nl(0,r.size),h),m=Gs(r,f);s=Us(Oi(m),Oi(r));const g=uu(a,s),y=uu(a,s),b=Gs(o,i);c=Gs(Gs(b,g),y);const x=Gi(c,l);l=di(x,c,l),u=di(x,ac([d]),u)}return u}(Fo(Ls(Fl(c),"int32"),Da([]),256),s)}const p=n?Zi(c,d):Gi(c,d);return Ls(Gs(p,255),"int32")}});const bd=Aa({transform_:function(e,t,n="nearest",r="constant",a=0,s){const o=Ea(e,"image","transform","float32"),u=Ea(t,"transforms","transform","float32");i(4===o.rank,()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&(u.shape[0]===o.shape[0]||1===u.shape[0])&&8===u.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),i(null==s||2===s.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);const l={image:o,transforms:u},c={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return wa.runKernel(Hn,l,c)}});const xd=Aa({bandPart_:function(e,t,n){const r=Ea(e,"a","bandPart");i(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const a=r.shape,[s,o]=r.shape.slice(-2);let u,l;"number"===typeof t?(i(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),i(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),u=Ea(t<0?s:t,"numLower","bandPart")):(i("int32"===t.dtype,()=>"bandPart(): numLower's dtype must be an int32."),u=di(Qi(t,0),s,Tu(t,s))),"number"===typeof n?(i(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),i(n<=o,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`),l=Ea(n<0?o:n,"numUpper","bandPart")):(i("int32"===n.dtype,()=>"bandPart(): numUpper's dtype must be an int32."),l=di(Qi(n,0),o,Tu(n,o)));const c=vo(Nl(0,s,1,"int32"),[-1,1]),d=Nl(0,o,1,"int32"),p=uu(c,d),h=du(Zi(p,u),Hi(p,su(l))),f=Iu([s,o],r.dtype);return vo(ec(bc(vo(r,[-1,s,o])).map(e=>di(h,e,f))),a)}});const vd=Aa({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,i(null!=e&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const n=e[0].shape[0];for(let t=1;t<e.length;++t)i(e[t].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`)}else t=!0,e=Yl(e,e.shape[0],0).map(e=>Jl(e,[0]));i(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let a=0;a<e.length;++a)n.push(wa.tidy(()=>{let e=r[a];if(a>0)for(let t=0;t<a;++t){const r=Gs(Oi(Gs(n[t],e)),n[t]);e=uu(e,r)}return Us(e,Di(e,"euclidean"))}));return t?ec(n,0):n}});function wd(e,t=!1){return wa.tidy(()=>{i(2===e.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let a=Wi(n),s=Bs(e);const o=sc([[1]],[1,1]);let u=Bs(o);const l=n>=r?r:n;for(let e=0;e<l;++e){const t=s,i=u,l=a;[u,s,a]=wa.tidy(()=>{const t=To(s,[e,e],[n-e,1]),i=Di(t),l=To(s,[e,e],[1,1]),c=di(Gi(l,0),sc([[-1]]),sc([[1]])),d=uu(l,Gs(c,i)),p=Us(t,d);u=1===p.shape[0]?Bs(o):Io([o,To(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const h=su(Us(No(c,d),i)),f=To(s,[e,0],[n-e,r]),m=Gs(h,u),g=Nc(u);if(0===e)s=uu(f,No(m,No(g,f)));else{const t=uu(f,No(m,No(g,f)));s=Io([To(s,[0,0],[e,r]),t],0)}const y=Nc(m),b=To(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=uu(b,No(No(b,u),y));else{const t=uu(b,No(No(b,u),y));a=Io([To(a,[0,0],[n,e]),t],1)}return[u,s,a]}),Va([t,i,l])}return!t&&n>r&&(a=To(a,[0,0],[n,r]),s=To(s,[0,0],[r,r])),[a,s]})}const kd=Aa({qr_:function(e,t=!1){if(i(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),2===e.rank)return wd(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((e,t)=>e*t),r=bc(vo(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];r.forEach(e=>{const[n,r]=wd(e,t);a.push(n),s.push(r)});return[vo(ec(a,0),e.shape),vo(ec(s,0),e.shape)]}}});var Id,Nd;(Nd=Id||(Id={}))[Nd.NONE=0]="NONE",Nd[Nd.MEAN=1]="MEAN",Nd[Nd.SUM=2]="SUM",Nd[Nd.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Sd=Aa({computeWeightedLoss_:function(e,t,n=Id.SUM_BY_NONZERO_WEIGHTS){const r=Ea(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=Ea(t,"weights","computeWeightedLoss"));const s=null==a?r:Gs(r,a);if(n===Id.NONE)return s;if(n===Id.SUM)return Oi(s);if(n===Id.MEAN){if(null==a)return ku(s);{const e=r.size/a.size,t=Us(Oi(s),Oi(a));return e>1?Us(t,Ri(e)):t}}if(n===Id.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Us(Oi(s),Ri(r.size));{const e=Gs(a,Nu(r.shape)),t=Ls(Oi(Au(e,Ri(0))),"float32");return Us(Oi(s),t)}}throw Error(`Unknown reduction: ${n}`)}});const Td=Aa({absoluteDifference_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","absoluteDifference"),s=Ea(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=Ea(n,"weights","absoluteDifference")),u(a.shape,s.shape,"Error in absoluteDifference: ");const i=Hs(uu(a,s));return Sd(i,o,r)}});const Cd=Aa({cosineDistance_:function(e,t,n,r,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","cosineDistance"),o=Ea(t,"predictions","cosineDistance");let i=null;null!=r&&(i=Ea(r,"weights","cosineDistance")),u(s.shape,o.shape,"Error in cosineDistance: ");const l=Ri(1),c=uu(l,Oi(Gs(s,o),n,!0));return Sd(c,i,a)}});const $d=Aa({hingeLoss_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){let a=Ea(e,"labels","hingeLoss");const s=Ea(t,"predictions","hingeLoss");let o=null;null!=n&&(o=Ea(n,"weights","hingeLoss")),u(a.shape,s.shape,"Error in hingeLoss: ");const i=Ri(1);a=uu(Gs(Ri(2),a),i);const l=Cl(uu(i,Gs(a,s)));return Sd(l,o,r)}});const Ed=Aa({huberLoss_:function(e,t,n,r=1,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","huberLoss"),o=Ea(t,"predictions","huberLoss");let i=null;null!=n&&(i=Ea(n,"weights","huberLoss")),u(s.shape,o.shape,"Error in huberLoss: ");const l=Ri(r),c=Hs(uu(o,s)),d=Tu(c,l),p=uu(c,d),h=Ws(Gs(Ri(.5),Ai(d)),Gs(l,p));return Sd(h,i,a)}});const Rd=Aa({logLoss_:function(e,t,n,r=1e-7,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","logLoss"),o=Ea(t,"predictions","logLoss");let i=null;null!=n&&(i=Ea(n,"weights","logLoss")),u(s.shape,o.shape,"Error in logLoss: ");const l=Ri(1),c=Ri(r),d=su(Gs(s,tu(Ws(o,c)))),p=Gs(uu(l,s),tu(Ws(uu(l,o),c))),h=uu(d,p);return Sd(h,i,a)}});const _d=Aa({meanSquaredError_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","meanSquaredError"),s=Ea(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=Ea(n,"weights","meanSquaredError")),u(a.shape,s.shape,"Error in meanSquaredError: ");const i=Zl(a,s);return Sd(i,o,r)}});const Ad=Aa({sigmoidCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"multiClassLabels","sigmoidCrossEntropy");const o=Ea(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","sigmoidCrossEntropy")),u(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(.5);s=Ws(Gs(s,uu(t,e)),Gs(n,e))}const l=function(e,t){const n=Ea(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ea(t,"logits","sigmoidCrossEntropyWithLogits");u(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=Cl(r),s=Gs(r,n),o=nu(Pi(su(Hs(r))));return Ws(uu(a,s),o)}(s,o);return Sd(l,i,a)}});const Od=Aa({softmaxCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"onehotLabels","softmaxCrossEntropy");const o=Ea(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","softmaxCrossEntropy")),u(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(s.shape[1]);s=Ws(Gs(s,uu(t,e)),Us(e,n))}const l=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return au((e,t,r)=>{const a=cu(t,[n],!0),s=uu(Ls(t,"float32"),a);r([e,s]);const o=su(Gs(s,e));return{value:Oi(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=ki(e.shape,[n]);return[Gs(vo(e,s),uu(Ls(r,"float32"),Pi(a))),Gs(vo(e,s),uu(Pi(a),Ls(r,"float32")))]}}})(e,t)}(s,o);return Sd(l,i,a)}});const Fd={fft:ql,ifft:Kl,rfft:Ql,irfft:Xl},Dd={hammingWindow:Gc,hannWindow:Hc,frame:jc,stft:qc},Md={flipLeftRight:Xc,grayscaleToRGB:Yc,resizeNearestNeighbor:gd,resizeBilinear:md,rgbToGrayscale:Qc,rotateWithOffset:Zc,cropAndResize:Kc,nonMaxSuppression:ed,nonMaxSuppressionAsync:cd,nonMaxSuppressionWithScore:dd,nonMaxSuppressionWithScoreAsync:pd,nonMaxSuppressionPadded:hd,nonMaxSuppressionPaddedAsync:fd,threshold:yd,transform:bd},Pd={bandPart:xd,gramSchmidt:vd,qr:kd},Ld={absoluteDifference:Td,computeWeightedLoss:Sd,cosineDistance:Cd,hingeLoss:$d,huberLoss:Ed,logLoss:Rd,meanSquaredError:_d,sigmoidCrossEntropy:Ad,softmaxCrossEntropy:Od},Bd={sparseFillEmptyRows:Aa({sparseFillEmptyRows_:function(e,t,n,r){const a=Ea(e,"indices","sparseFillEmptyRows","int32"),s=Ea(t,"values","sparseFillEmptyRows"),o=Ea(n,"denseShape","sparseFillEmptyRows","int32"),i=Ea(r,"defaultValue","sparseFillEmptyRows",s.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:a,values:s,denseShape:o,defaultValue:i},l=wa.runKernel($n,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),sparseReshape:Aa({sparseReshape_:function(e,t,n){const r=Ea(e,"inputIndices","sparseReshape","int32"),a=Ea(t,"inputShape","sparseReshape","int32"),s=Ea(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==s.rank)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);const o={inputIndices:r,inputShape:a,newShape:s},i=wa.runKernel(En,o);return{outputIndices:i[0],outputShape:i[1]}}}),sparseSegmentMean:Aa({sparseSegmentMean_:function(e,t,n){const r=Ea(e,"data","sparseSegmentMean"),a=Ea(t,"indices","sparseSegmentMean","int32"),s=Ea(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(Rn,o)}}),sparseSegmentSum:Aa({sparseSegmentSum_:function(e,t,n){const r=Ea(e,"data","sparseSegmentSum"),a=Ea(t,"indices","sparseSegmentSum","int32"),s=Ea(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(_n,o)}})},Vd={stringNGrams:Aa({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=Ea(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=Ea(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:o,preserveShortSequences:i},d={data:u,dataSplits:l},p=wa.runKernel(Pn,d,c);return{nGrams:p[0],nGramsSplits:p[1]}}}),stringSplit:Aa({stringSplit_:function(e,t,n=!0){const r=Ea(e,"input","stringSplit","string"),a=Ea(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const s={skipEmpty:n},o={input:r,delimiter:a},i=wa.runKernel(Ln,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:Aa({stringToHashBucketFast_:function(e,t){const n=Ea(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return wa.runKernel(Bn,a,r)}}),staticRegexReplace:Aa({staticRegexReplace_:function(e,t,n,r=!0){const a=Ea(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:r};return wa.runKernel(Dn,{x:a},s)}})},Wd=new Map,zd=new Map;class Ud{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Gd{constructor(){this.classNameMap={}}static getMap(){return null==Gd.instance&&(Gd.instance=new Gd),Gd.instance}static register(e){Gd.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Hd(e,t,n){i(null!=e.className,()=>"Class being registered does not have the static className property defined."),i("string"===typeof e.className,()=>"className is required to be a string, but got type "+typeof e.className),i(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),"undefined"===typeof t&&(t="Custom"),"undefined"===typeof n&&(n=e.className);const r=t+">"+n;return Gd.register(e),Wd.set(r,e),zd.set(e,r),e}class jd extends Ud{minimize(e,t=!1,n){const{value:r,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map(e=>({name:e.name,tensor:a[e.name]}));this.applyGradients(e)}else this.applyGradients(a);return Va(a),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ru(e,t)}dispose(){null!=this.iterations_&&Va(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Ri(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(jd,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class qd extends jd{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Ba(()=>{const e=Ws(Gs(o,this.rho),Gs(Ai(s),1-this.rho)),t=Gs(Us(_i(Ws(i,this.epsilon)),_i(Ws(o,this.epsilon))),s),n=Ws(Gs(i,this.rho),Gs(Ai(t),1-this.rho));o.assign(e),i.assign(n);const a=Ws(Gs(t,-this.learningRate),r);r.assign(a)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Va(this.accumulatedGrads.map(e=>e.variable)),Va(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}class Kd extends jd{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Ba(()=>Bo(r.shape,this.initialAccumulatorValue).variable(e))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable;Ba(()=>{const e=Ws(s,Ai(a));s.assign(e);const t=Ws(Gs(Us(a,_i(Ws(e,wa.backend.epsilon()))),-this.learningRate),r);r.assign(t)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Va(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}class Xd extends jd{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ba(()=>{this.accBeta1=Ri(t).variable(),this.accBeta2=Ri(n).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=uu(1,this.accBeta2);t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Ba(()=>pi(s).variable(o))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Ba(()=>pi(s).variable(o))});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Ws(Gs(l,this.beta2),Gs(Ai(i),1-this.beta2)),p=Us(c,n),h=Us(d,r);u.assign(c),l.assign(d);const f=Ws(Gs(Us(p,Ws(_i(h),this.epsilon)),-this.learningRate),s);s.assign(f)}),this.accBeta1.assign(Gs(this.accBeta1,this.beta1)),this.accBeta2.assign(Gs(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedSecondMoment&&Va(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e),Ba(()=>{this.accBeta1.assign(Ei(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ei(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}class Yd extends jd{static get className(){return"Adamax"}constructor(e,t,n,r=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Ba(()=>{this.iteration=Ri(0).variable(),this.accBeta1=Ri(t).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=Us(-this.learningRate,Ws(Gs(this.iteration,this.decay),1));t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:pi(s).variable(o)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:pi(s).variable(o)});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Gs(l,this.beta2),p=Hs(i),h=wu(d,p);u.assign(c),l.assign(h);const f=Ws(Gs(Us(r,n),Us(c,Ws(h,this.epsilon))),s);s.assign(f)}),this.iteration.assign(Ws(this.iteration,1)),this.accBeta1.assign(Gs(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedWeightedInfNorm&&Va(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class Qd extends jd{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=wa.registeredVariables[t];Ba(()=>{const e=Ws(Gs(this.c,r),a);a.assign(e)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Wa(Ri(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class Zd extends Qd{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ri(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(e))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&Ba(()=>{let e;const t=Ws(Gs(this.m,a),s);e=this.useNesterov?Ws(Gs(this.c,Ws(s,Gs(t,this.m))),r):Ws(Gs(this.c,t),r),a.assign(t),r.assign(e)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Va(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class Jd extends jd{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==r&&(this.epsilon=wa.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedMeanSquares[n].variable,i=this.accumulatedMoments[n].variable;Ba(()=>{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=Ws(Gs(t,this.decay),Gs(s,1-this.decay)),u=Us(Gs(s,this.learningRate),_i(uu(e,Ws(Ai(a),this.epsilon)))),l=Ws(Gs(i,this.momentum),u);o.assign(e),t.assign(a),i.assign(l);const c=uu(r,l);r.assign(c)}else{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay)),t=Ws(Gs(i,this.momentum),Us(Gs(s,this.learningRate),_i(Ws(e,this.epsilon))));o.assign(e),i.assign(t);const n=uu(r,t);r.assign(n)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Va(this.accumulatedMeanSquares.map(e=>e.variable)),null!=this.accumulatedMeanGrads&&this.centered&&Va(this.accumulatedMeanGrads.map(e=>e.variable)),null!=this.accumulatedMoments&&Va(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const ep=[qd,Kd,Xd,Yd,Zd,Jd,Qd];function tp(e){return new Promise(e=>setTimeout(e)).then(e)}class np{constructor(e){if(!V().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(np.URL_SCHEME)&&(e=e.slice(np.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"===typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Pa.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=ns(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await tp(()=>a.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await tp(()=>e.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ss(e)}}}}np.URL_SCHEME="downloads://";class rp{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const s=as(r,e=>this.loadWeights(e));e(s)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){const t=[],n=[];for(const s of e)t.push(...s.weights),n.push(...s.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map(e=>this.loadWeightsFile(e,r[e]));return Promise.all(a).then(e=>[t,e])}loadWeightsFile(e,t){return new Promise((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map(e=>ts(e.name)),r={};for(const a of e)a.paths.forEach(e=>{const a=ts(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function ap(e,t,n,r){var a,s,o;i(null!=(a=e)&&Array.isArray(a)&&a.length>0,()=>"promises must be a none empty array"),o=r=r??1,i((s=n=n??0)>=0&&s<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${s}`),i(o>=0&&o<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${o}`),i(o>=s,()=>`startFraction must be no more than endFraction, but got startFraction ${s} and endFraction ${o}`);let u=0;return Promise.all(e.map(a=>(a.then(a=>{const s=n+ ++u/e.length*(r-n);return t(s),a}),a)))}async function sp(e,t){null==t&&(t={});const n=null==t.fetchFunc?V().platform.fetch:t.fetchFunc,r=e.map(e=>n(e,t.requestInit,{isBinary:!0})),a=(null==t.onProgress?await Promise.all(r):await ap(r,t.onProgress,0,.5)).map(e=>e.arrayBuffer());return null==t.onProgress?await Promise.all(a):await ap(a,t.onProgress,.5,1)}function op(e){return async(t,n="",r)=>{const a=t.map(()=>!1),s={},o=null!=r?r.map(()=>!1):[],i=[];if(t.forEach((e,t)=>{let n=0;e.weights.forEach(e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=Ma[u]*c(e.shape),d=()=>{a[t]=!0,null==s[t]&&(s[t]=[]),s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach((t,n)=>{t===e.name&&(d(),o[n]=!0)}):d(),i.push(e.name),n+=l})}),!o.every(e=>e)){const e=r.filter((e,t)=>!o[t]);throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const u=a.reduce((e,t,n)=>(t&&e.push(n),e),[]),l=[];u.forEach(e=>{t[e].paths.forEach(e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)})});const d=await e(l),p={};let h=0;return u.forEach(e=>{const n=t[e].paths.length,r=new Pa(d.slice(h,h+n));s[e].forEach(e=>{const t=ja(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const n in t)p[n]=t[n]}),h+=n}),p}}is.registerSaveRouter(e=>V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(np.URL_SCHEME)?function(e="model"){return new np(e)}(e.slice(np.URL_SCHEME.length)):null);class ip{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(i("function"===typeof t.fetchFunc,()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=V().platform.fetch,i(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&i(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=ns(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=Pa.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ss(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(a){let e=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?e+=" 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.":e+=" Please make sure the server is serving valid JSON for this request.",new Error(e)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();return as(await this.loadModelJSON(),e=>this.loadWeights(e))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=os(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?V().platform.fetch:t.fetchFunc;let a,s=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var o;s<e.length;){if(!a){const n=(await r(e[s],t.requestInit,{isBinary:!0})).body;a=n.getReader()}const{done:i,value:u}=await a.read();if(!i)return void n.enqueue(u);s++,a=void 0,null===(o=t.onProgress)||void 0===o||o.call(t,s/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),a=n>t?e.substring(n):"";return[r+"/",a]}(t),a=this.weightPathPrefix||n,s=[],o=[];for(const i of e)for(const e of i.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):s.push(a+e+r);return this.weightUrlConverter&&s.push(...await Promise.all(o)),s}async loadWeights(e){const t=await this.getWeightUrls(e);return[os(e),await sp(t,this.loadOptions)]}}function up(e){return null!=e.match(ip.URL_SCHEME_REGEX)}ip.URL_SCHEME_REGEX=/^https?:\/\//;const lp=(e,t)=>{if("undefined"===typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every(e=>up(e)):up(e),n)return cp(e,t)}return null};function cp(e,t){return new ip(e,t)}is.registerSaveRouter(lp),is.registerLoadRouter(lp);class dp{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class pp{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class hp{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function fp(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new dp(e):(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 dp({modelTopology:e}))}return 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 dp({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}const mp=Object.freeze(Object.defineProperty({__proto__:null,CompositeArrayBuffer:Pa,browserFiles:function(e){return new rp(e)},browserHTTPRequest:function(e,t){return cp(e,t)},concatenateArrayBuffers:function(e){return Pa.join(e)},copyModel:async function(e,t){return As(e,t,!1)},decodeWeights:ja,decodeWeightsStream:Qa,encodeWeights:async function(e,t){const n=[],r=[],a=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);for(let s=0;s<a.length;++s){const o=a[s],i=Array.isArray(e)?e[s].tensor:e[o];if("float32"!==i.dtype&&"int32"!==i.dtype&&"bool"!==i.dtype&&"string"!==i.dtype&&"complex64"!==i.dtype)throw new Error(`Unsupported dtype in weight '${o}': ${i.dtype}`);const u={name:o,shape:i.shape,dtype:i.dtype};if("string"===i.dtype){const e=new Promise(async e=>{const t=await i.bytes(),n=t.reduce((e,t)=>e+t.length,0)+4*t.length,r=new Uint8Array(n);let a=0;for(let s=0;s<t.length;s++){const e=t[s],n=new Uint8Array(new Uint32Array([e.length]).buffer);r.set(n,a),a+=4,r.set(e,a),a+=e.length}e(r)});r.push(e)}else r.push(i.data());null!=t&&(u.group=t),n.push(u)}return{data:Za(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){return new hp(fp(...arguments))},fromMemorySync:fp,getLoadHandlers:(e,t)=>is.getLoadHandlers(e,t),getModelArtifactsForJSON:as,getModelArtifactsForJSONSync:rs,getModelArtifactsInfoForJSON:ss,getSaveHandlers:e=>is.getSaveHandlers(e),getWeightSpecs:os,http:cp,isHTTPScheme:up,listModels:async function(){const e=Rs.getSchemes(),t={};for(const n of e){const e=await Rs.getManager(n).listModels();for(const r in e){t[n+Es+r]=e[r]}}return t},loadWeights:async function(e,t="",n,r){return op(e=>sp(e,{requestInit:r}))(e,t,n)},moveModel:async function(e,t){return As(e,t,!0)},registerLoadRouter:e=>is.registerLoadRouter(e),registerSaveRouter:e=>is.registerSaveRouter(e),removeModel:async function(e){const t=_s(e);return Rs.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:op,withSaveHandler:function(e){return new pp(e)},withSaveHandlerSync:function(e){return new pp(e)}},Symbol.toStringTag,{value:"Module"}));let gp,yp=!1;async function bp(e,t){let n=Ea(e,"img","toPixels");if(!(e instanceof Yr)){const e=n;n=Ls(e,"int32"),e.dispose()}!function(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}(n);const[r,a]=n.shape.slice(0,2),s=2===n.rank?1:n.shape[2],o=await n.data(),i="float32"===n.dtype?255:1,u=new Uint8ClampedArray(a*r*4);for(let l=0;l<r*a;++l){const e=[0,0,0,255];for(let r=0;r<s;r++){const t=o[l*s+r];if("float32"===n.dtype){if(t<0||t>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${t}.`)}else if("int32"===n.dtype&&(t<0||t>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${t}.`);1===s?(e[0]=t*i,e[1]=t*i,e[2]=t*i):e[r]=t*i}const t=4*l;u[t+0]=Math.round(e[0]),u[t+1]=Math.round(e[1]),u[t+2]=Math.round(e[2]),u[t+3]=Math.round(e[3])}if(null!=t){if(!yp){null!=or(Ve,wa.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),yp=!0)}t.width=a,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,a,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}const xp=Aa({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,a=!1,s=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!==typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement)s=!0;else if(null!=e.getContext)o=!0;else{if(!("undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=or(Zn,wa.backendName)){const n={pixels:e},r={numChannels:t};return wa.runKernel(Zn,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,d;if(o)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||i){if(null==gp)if("undefined"===typeof document){if("undefined"===typeof OffscreenCanvas||"undefined"===typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");gp=new OffscreenCanvas(1,1).getContext("2d")}else gp=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});gp.canvas.width=u,gp.canvas.height=l,gp.drawImage(e,0,0,u,l),c=gp.getImageData(0,0,u,l).data}if(4===t)d=new Int32Array(c);else{const e=u*l;d=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)d[n*t+e]=c[4*n+e]}return oc(d,[l,u,t],"int32")}});function vp(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===c(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let c=0;c<a.length-1;++c)o*=a[c];const i=e.shape,u=a.slice();u.pop();let l=1;for(let c=s;c<n;++c)l*=i[c],u.push(i[c]);const d=[...C(e.shape).map(e=>e/l),1].slice(0,s);return[u,o,l,d]}function wp(e,t,n){const r=e.shape.length;i(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),i(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let a=0;a<r;++a)i(t[a]+n[a]<=e.shape[a],()=>`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function kp(e,t,n){const r=[];for(let a=0;a<e.length;a++)r[a]=Math.ceil((t[a]-e[a])/n[a]);return r}function Ip(e,t,n){let r=n.length;for(let a=0;a<n.length;a++)if(n[a]>1){r=a;break}for(let a=r+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}function Np(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function Sp(e,t,n){let r;const a=e.shape.length;let s;return r="number"===typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),r.forEach(e=>{i(-1!==e,()=>"slice() does not support negative begin indexing.")}),s=null==n?new Array(a).fill(-1):"number"===typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map((t,n)=>t>=0?t:(i(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,s]}function Tp(e,t,n,r,a,s,o,i,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=o&&0!==(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const d={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let b=0;b<d.dims;b++)c&&0!==(1<<b&i)&&d.numAddAxisAfterEllipsis++,1<<b&o&&(c=!0);c||(d.ellipsisMask|=1<<d.dims,d.dims++);const p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const a=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<a;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(-2),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(-1),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(d,p);let h=!0,f=!0,m=!0;const g=[],y=[];for(let b=0;b<e.length;++b){if(0===p.strides[b])throw Error(`strides[${b}] must be non-zero`);const t=!!(p.shrinkAxisMask&1<<b),n=e[b];if(-1===n){g.push(t?1:-1);continue}const r=[p.beginMask&1<<b,p.endMask&1<<b],a=[p.strides[b]>0?0:-1,p.strides[b]>0?n:n-1];if(t&&p.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[b];const s=!!(p.beginMask&1<<b&&p.endMask&1<<b);if(p.beginValid&&p.endValid){if(t){const e=p.begin[b]<0?n+p.begin[b]:p.begin[b];if(p.begin[b]=e,p.end[b]=p.begin[b]+1,e<0||e>=n)throw Error(`slice index ${p.begin[b]} of dimension ${b} out of bounds.`)}else p.begin[b]=Cp(p.begin[b],0,p.strides[b],n,r,a),p.end[b]=Cp(p.end[b],1,p.strides[b],n,r,a);const e=1===p.strides[b]&&0===p.begin[b]&&p.end[b]===n;h=h&&e,f=f&&(0===b&&1===p.strides[b]||e)}else h=h&&1===p.strides[b]&&s,f=f&&(0===b&&1===p.strides[b]||s);let o,i=!1;if(p.beginValid&&p.endValid?(o=p.end[b]-p.begin[b],i=!0):t?(o=1,i=!0):s&&n>=0&&(o=p.strides[b]<0?-n:n,i=!0),i){let e;e=0===o||o<0!==p.strides[b]<0?0:Math.trunc(o/p.strides[b])+(o%p.strides[b]!==0?1:0),g.push(e)}else g.push(-1)}for(let b=0;b<p.finalShapeGatherIndices.length;++b){const e=p.finalShapeGatherIndices[b];e>=0?y.push(g[e]):-2===e&&y.push(1)}return{finalShapeSparse:y.filter((e,t)=>-2!==p.finalShapeGatherIndices[t]),finalShape:y,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Cp(e,t,n,r,a,s){if(a[t])return n>0?s[t]:s[t+1&1];{const t=e<0?r+e:e;return t<s[0]?s[0]:t>s[1]?s[1]:t}}const $p="undefined"!==typeof requestAnimationFrame?requestAnimationFrame:"undefined"!==typeof setImmediate?setImmediate:e=>e();function Ep(){return new Promise(e=>$p(()=>e()))}function Rp(e,t){const n=e[0].length;e.forEach((e,t)=>{i(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),i(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,a)=>{for(let s=0;s<n;s++)i(s===t||e[s]===r[s],()=>`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function _p(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var Ap,Op;function Fp(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length<e+n.length;)r.push(-1);else r=t.slice();if(null==n)return r;if(e+n.length!==r.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${r.length}`);for(let a=1;a<n.length;++a){const s=n[a],o=r[r.length-n.length+a],i=r[o];if(s>=0)if(i>=0){if(i!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${i}`)}else r[o]=s}return r}function Dp(e){const t={FIRST_DIM_SIZE:Ap.FIRST_DIM_SIZE,VALUE_ROWIDS:Ap.VALUE_ROWIDS,ROW_LENGTHS:Ap.ROW_LENGTHS,ROW_SPLITS:Ap.ROW_SPLITS,ROW_LIMITS:Ap.ROW_LIMITS,ROW_STARTS:Ap.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function Mp(e){return 0===e.length?0:e[0]===Ap.FIRST_DIM_SIZE?e.length-1:e.length}function Pp(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let a=0;a<Math.min(n,r-1);++a){const n=e[a],r=t[a+1];if(n>=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${n} but ragged tensor input.flatValues.shape[${a-e.length}] = ${r}`)}}(Op=Ap||(Ap={}))[Op.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",Op[Op.VALUE_ROWIDS=1]="VALUE_ROWIDS",Op[Op.ROW_LENGTHS=2]="ROW_LENGTHS",Op[Op.ROW_SPLITS=3]="ROW_SPLITS",Op[Op.ROW_LIMITS=4]="ROW_LIMITS",Op[Op.ROW_STARTS=5]="ROW_STARTS";function Lp(e){return e<=30?e:T(e,Math.floor(Math.sqrt(e)))}function Bp(e,t,n){return[n*("number"===typeof e?e:e[0]),t*("number"===typeof e?e:e[1])]}function Vp(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)a=a.concat([e[r+1]/t[r],t[r]]);a=a.concat(e.slice(n+1))}return a}function Wp(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],a=[];for(let r=1;r<e;++r)r>=2*t+1||r%2===1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function zp(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let s=1;s<e.length;++s)s<=t.length?r?a.push(t[s-1]*e[s]):a.push(e[s]/t[s-1]):a.push(e[s]);return a}function Up(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Gp(e,t,n){const r=e.slice(0,1);for(let a=0;a<n;++a)r.push(e[a+1]-t[a][0]-t[a][1]);return r}const Hp=1.7580993408473768,jp=1.0507009873554805,qp=.3275911,Kp=.254829592,Xp=-.284496736,Yp=1.421413741,Qp=-1.453152027,Zp=1.061405429;function Jp(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function eh(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function th(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let a=0;a<e.length;a+=4)n[Math.floor(a/4)]=e[a],r[Math.floor(a/4)]=e[a+1];return{real:n,imag:r}}function nh(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let a=2;a<e.length;a+=4)n[Math.floor(a/4)]=e[a],r[Math.floor(a/4)]=e[a+1];return{real:n,imag:r}}function rh(e,t){return{real:e[2*t],imag:e[2*t+1]}}function ah(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function sh(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){const s=(t?2:-2)*Math.PI*(a/e);n[a]=Math.cos(s),r[a]=Math.sin(s)}return{real:n,imag:r}}function oh(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}const ih="->",uh=/->/g;function lh(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(uh,"").length)/2;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${ih}").`);const[r,a]=e.split(ih);i(-1===r.indexOf("..."),()=>'The ellipsis notation ("...") is not supported yet.');const s=r.split(","),o=s.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const u=[];for(let i=0;i<a.length;++i){const e=a[i];if(!s.some(t=>-1!==t.indexOf(e)))throw new Error(`Output subscripts contain the label ${e} not present in the input subscripts.`);-1===u.indexOf(e)&&u.push(e)}for(let i=0;i<r.length;++i){const e=r[i];-1===u.indexOf(e)&&","!==e&&u.push(e)}const l=new Array(s.length);for(let i=0;i<o;++i){if(new Set(s[i].split("")).size!==s[i].length)throw new Error(`Found duplicate axes in input component ${s[i]}. Support for duplicate axes in input is not implemented yet.`);l[i]=[];for(let e=0;e<s[i].length;++e)l[i].push(u.indexOf(s[i][e]))}const c=u.length,d=[];for(let i=a.length;i<c;++i)d.push(i);return{allDims:u,summedDims:d,idDims:l}}function ch(e,t){let n=new Array(e);n.fill(-1);for(let a=0;a<t.length;++a)n[t[a]]=a;const r=[];for(let a=0;a<e;++a)-1===n[a]&&r.push(a);return n=n.filter(e=>-1!==e),{permutationIndices:n,expandDims:r}}function dh(e,t,n){const r=new Array(e);for(let a=0;a<n.length;++a){const e=n[a].shape;for(let n=0;n<t[a].length;++n)void 0===r[t[a][n]]?r[t[a][n]]=e[n]:i(r[t[a][n]]===e[n],()=>`Expected dimension ${r[t[a][n]]} at axis ${n} of input shaped ${JSON.stringify(e)}, but got dimension ${e[n]}`)}}function ph(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let o=0;o<a;++o)r.push([]);const s=[];for(let o=0;o<n.length;++o){const e=fh(t,n[o]);for(const t of e)-1===s.indexOf(t)&&(r[o].push(t),s.push(t))}return{path:n,steps:r}}function hh(e){return e.every((e,t)=>e===t)}function fh(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}function mh(e,t,n=0){let r=[];if("number"===typeof t)i(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{i(t.reduce((e,t)=>(-1===t&&(e+=1),e),0)<=1,()=>"There should be only one negative value in split array.");const a=t.indexOf(-1);if(-1!==a){const r=t.reduce((e,t)=>t>0?e+t:e);t[a]=e.shape[n]-r}i(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function gh(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function yh(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function bh(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function xh(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function vh(e,t){return`size ${e} must be non-negative, not ${t}`}function wh(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function kh(e,t){return`Input to reshape is a SparseTensor with ${c(e)}\n dense values, but the requested shape requires a multiple of ${c(t)}. inputShape=${e} outputShape= ${t}`}function Ih(e,t){return`Input to reshape is a tensor with ${c(e)} dense values, but the requested shape has ${c(t)}. inputShape=${e} outputShape=${t}`}function Nh(){return"segment ids must be >= 0"}function Sh(){return"segment ids are not increasing"}function Th(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Ch(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function $h(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${s}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);const o=e.shape[n],i=[];let u=1,l=1,c=1;for(let d=0;d<r;++d)i.push(e.shape[d]),u*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<a;d++)i.push(t.shape[d]);for(let d=n+1;d<s;d++)i.push(e.shape[d]),c*=e.shape[d];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:o,outputShape:i}}function Eh(e){try{return e.map(e=>Mr(e))}catch(hO){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${hO}`)}}function Rh(e){return e.map(e=>Dr(e))}const _h=Object.freeze(Object.defineProperty({__proto__:null,ERF_A1:Kp,ERF_A2:Xp,ERF_A3:Yp,ERF_A4:Qp,ERF_A5:Zp,ERF_P:qp,PARALLELIZE_THRESHOLD:30,get RowPartitionType(){return Ap},SELU_SCALE:jp,SELU_SCALEALPHA:Hp,applyActivation:Mc,assertAndGetBroadcastShape:li,assertAxesAreInnerMostDims:Ii,assertParamsConsistent:Rp,assignToTypedArray:ah,axesAreInnerMostDims:xi,calculateShapes:pc,checkEinsumDimSizes:dh,checkPadOnDimRoundingMode:xo,combineLocations:vi,combineRaggedTensorToTensorShapes:Fp,complexWithEvenIndex:th,complexWithOddIndex:nh,computeConv2DInfo:io,computeConv3DInfo:uo,computeDefaultPad:lo,computeDilation2DInfo:ao,computeOptimalWindowSize:Lp,computeOutAndReduceShapes:wi,computeOutShape:_p,computePool2DInfo:so,computePool3DInfo:oo,convertConv2DDataFormat:bo,decodeEinsumEquation:lh,eitherStridesOrDilationsAreOne:go,expandShapeToKeepDim:ki,exponent:oh,exponents:sh,fromStringArrayToUint8:Rh,fromUint8ToStringArray:Eh,getAxesPermutation:Ni,getBroadcastDims:ii,getComplexWithIndex:rh,getEinsumComputePath:ph,getEinsumPermutation:ch,getFusedBiasGradient:Dc,getFusedDyActivation:Fc,getImageCenter:Bp,getInnerMostAxes:Ti,getPermuted:Wp,getRaggedRank:Mp,getReductionAxes:ui,getReshaped:Vp,getReshapedPermuted:zp,getRowPartitionTypesHelper:Dp,getSliceBeginCoords:Up,getSliceSize:Gp,getSparseFillEmptyRowsIndicesDenseShapeMismatch:gh,getSparseFillEmptyRowsNegativeIndexErrorMessage:yh,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:bh,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:wh,getSparseReshapeInputOutputMismatchErrorMessage:Ih,getSparseReshapeInputOutputMultipleErrorMessage:kh,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:xh,getSparseReshapeNegativeOutputDimErrorMessage:vh,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Ch,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:Nh,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Sh,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Th,getUndoAxesPermutation:Si,isIdentityPermutation:hh,mergeRealAndImagArrays:Jp,prepareAndValidate:vp,prepareSplitSize:mh,shouldFuse:Pc,splitRealAndImagArrays:eh,stridesOrDilationsArePositive:yo,tupleValuesAreOne:mo,upcastType:ca,validateDefaultValueShape:Pp,validateInput:dc,validateUpdateShape:cc,warn:rr},Symbol.toStringTag,{value:"Module"}));!function(){for(const e of ep)Hd(e)}();const Ah=Object.freeze(Object.defineProperty({__proto__:null,Abs:H,Acos:j,Acosh:q,AdadeltaOptimizer:qd,AdagradOptimizer:Kd,AdamOptimizer:Xd,AdamaxOptimizer:Yd,Add:K,AddN:X,All:Y,Any:Q,ArgMax:Z,ArgMin:J,Asin:ee,Asinh:te,Atan:ne,Atan2:ae,Atanh:re,AvgPool:se,AvgPool3D:ie,AvgPool3DGrad:ue,AvgPoolGrad:oe,BatchMatMul:le,BatchToSpaceND:ce,Bincount:de,BitwiseAnd:pe,BroadcastArgs:he,Cast:fe,Ceil:me,ClipByValue:ge,Complex:ye,ComplexAbs:be,Concat:xe,Conv2D:ve,Conv2DBackpropFilter:we,Conv2DBackpropInput:ke,Conv3D:Ie,Conv3DBackpropFilterV2:Ne,Conv3DBackpropInputV2:Se,Cos:Te,Cosh:Ce,CropAndResize:Re,Cumprod:$e,Cumsum:Ee,DataStorage:t,DenseBincount:_e,DepthToSpace:Ae,DepthwiseConv2dNative:Oe,DepthwiseConv2dNativeBackpropFilter:Fe,DepthwiseConv2dNativeBackpropInput:De,Diag:Me,Dilation2D:Pe,Dilation2DBackpropFilter:Be,Dilation2DBackpropInput:Le,Draw:Ve,get ENV(){return z},Einsum:ze,Elu:Ue,EluGrad:Ge,Environment:L,Equal:je,Erf:He,Exp:qe,ExpandDims:Ke,Expm1:Xe,FFT:Ye,Fill:Qe,FlipLeftRight:Ze,Floor:Je,FloorDiv:et,FromPixels:Zn,FusedBatchNorm:tt,FusedConv2D:tr,FusedDepthwiseConv2D:nr,GatherNd:rt,GatherV2:nt,Greater:at,GreaterEqual:st,IFFT:it,Identity:ot,Imag:ut,IsFinite:lt,IsInf:ct,IsNan:dt,KernelBackend:n,LRN:wt,LRNGrad:kt,LeakyRelu:pt,Less:ht,LessEqual:ft,LinSpace:mt,Log:gt,Log1p:yt,LogicalAnd:bt,LogicalNot:xt,LogicalOr:vt,Max:It,MaxPool:St,MaxPool3D:Ct,MaxPool3DGrad:$t,MaxPoolGrad:Tt,MaxPoolWithArgmax:Et,Maximum:Nt,Mean:Rt,Min:_t,Minimum:At,MirrorPad:Ot,Mod:Ft,MomentumOptimizer:Zd,Multinomial:Dt,Multiply:Mt,Neg:Pt,NonMaxSuppressionV3:Bt,NonMaxSuppressionV4:Vt,NonMaxSuppressionV5:Wt,NotEqual:Lt,OP_SCOPE_SUFFIX:_a,OneHot:Ut,OnesLike:zt,Optimizer:jd,Pack:Gt,PadV2:Ht,Pow:jt,Prelu:qt,Prod:Kt,RMSPropOptimizer:Jd,RaggedGather:Xt,RaggedRange:Yt,RaggedTensorToTensor:Qt,Range:Zt,get Rank(){return Jr},Real:Jt,RealDiv:We,Reciprocal:en,get Reduction(){return Id},Relu:tn,Relu6:un,Reshape:nn,ResizeBilinear:sn,ResizeBilinearGrad:on,ResizeNearestNeighbor:rn,ResizeNearestNeighborGrad:an,Reverse:ln,RotateWithOffset:Jn,Round:cn,Rsqrt:dn,SGDOptimizer:Qd,ScatterNd:pn,SearchSorted:fn,Select:mn,Selu:gn,Sigmoid:wn,Sign:vn,Sin:bn,Sinh:xn,Slice:yn,Softmax:Cn,Softplus:kn,SpaceToBatchND:Sn,SparseFillEmptyRows:$n,SparseReshape:En,SparseSegmentMean:Rn,SparseSegmentSum:_n,SparseToDense:An,SplitV:Tn,Sqrt:In,Square:Fn,SquaredDifference:On,StaticRegexReplace:Dn,Step:Qn,StridedSlice:Mn,StringNGrams:Pn,StringSplit:Ln,StringToHashBucketFast:Bn,Sub:Vn,Sum:Nn,Tan:Wn,Tanh:zn,Tensor:Yr,TensorBuffer:qr,TensorScatterUpdate:hn,Tile:Un,TopK:Gn,Transform:Hn,Transpose:jn,Unique:qn,Unpack:Kn,UnsortedSegmentSum:Xn,Variable:Zr,ZerosLike:Yn,_FusedMatMul:er,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,backend:Ha,backend_util:_h,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,customGrad:au,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,dispose:Va,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,engine:La,ensureShape:yi,env:V,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,getBackend:Ua,getGradient:ir,getKernel:or,getKernelsForBackend:ur,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,io:mp,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,keep:Wa,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,nextFrame:Ep,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,registerBackend:Ga,registerKernel:lr,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setBackend:za,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,sumOutType:da,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tidy:Ba,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upcastType:ca,upperBound:xc,variable:vc,variableGrads:ru,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));var Oh,Fh,Dh;V().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")}),(Fh=Oh||(Oh={}))[Fh.DT_INVALID=0]="DT_INVALID",Fh[Fh.DT_FLOAT=1]="DT_FLOAT",Fh[Fh.DT_DOUBLE=2]="DT_DOUBLE",Fh[Fh.DT_INT32=3]="DT_INT32",Fh[Fh.DT_UINT8=4]="DT_UINT8",Fh[Fh.DT_INT16=5]="DT_INT16",Fh[Fh.DT_INT8=6]="DT_INT8",Fh[Fh.DT_STRING=7]="DT_STRING",Fh[Fh.DT_COMPLEX64=8]="DT_COMPLEX64",Fh[Fh.DT_INT64=9]="DT_INT64",Fh[Fh.DT_BOOL=10]="DT_BOOL",Fh[Fh.DT_QINT8=11]="DT_QINT8",Fh[Fh.DT_QUINT8=12]="DT_QUINT8",Fh[Fh.DT_QINT32=13]="DT_QINT32",Fh[Fh.DT_BFLOAT16=14]="DT_BFLOAT16",Fh[Fh.DT_QINT16=15]="DT_QINT16",Fh[Fh.DT_QUINT16=16]="DT_QUINT16",Fh[Fh.DT_UINT16=17]="DT_UINT16",Fh[Fh.DT_COMPLEX128=18]="DT_COMPLEX128",Fh[Fh.DT_HALF=19]="DT_HALF",Fh[Fh.DT_RESOURCE=20]="DT_RESOURCE",Fh[Fh.DT_VARIANT=21]="DT_VARIANT",Fh[Fh.DT_UINT32=22]="DT_UINT32",Fh[Fh.DT_UINT64=23]="DT_UINT64",Fh[Fh.DT_FLOAT_REF=101]="DT_FLOAT_REF",Fh[Fh.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",Fh[Fh.DT_INT32_REF=103]="DT_INT32_REF",Fh[Fh.DT_UINT8_REF=104]="DT_UINT8_REF",Fh[Fh.DT_INT16_REF=105]="DT_INT16_REF",Fh[Fh.DT_INT8_REF=106]="DT_INT8_REF",Fh[Fh.DT_STRING_REF=107]="DT_STRING_REF",Fh[Fh.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",Fh[Fh.DT_INT64_REF=109]="DT_INT64_REF",Fh[Fh.DT_BOOL_REF=110]="DT_BOOL_REF",Fh[Fh.DT_QINT8_REF=111]="DT_QINT8_REF",Fh[Fh.DT_QUINT8_REF=112]="DT_QUINT8_REF",Fh[Fh.DT_QINT32_REF=113]="DT_QINT32_REF",Fh[Fh.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",Fh[Fh.DT_QINT16_REF=115]="DT_QINT16_REF",Fh[Fh.DT_QUINT16_REF=116]="DT_QUINT16_REF",Fh[Fh.DT_UINT16_REF=117]="DT_UINT16_REF",Fh[Fh.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",Fh[Fh.DT_HALF_REF=119]="DT_HALF_REF",Fh[Fh.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",Fh[Fh.DT_VARIANT_REF=121]="DT_VARIANT_REF",Fh[Fh.DT_UINT32_REF=122]="DT_UINT32_REF",Fh[Fh.DT_UINT64_REF=123]="DT_UINT64_REF",function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Dh||(Dh={}));const Mh={};function Ph(e){return Mh[e]}function Lh(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,o=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd,i=e<0?t.inputNames.length+e:e;if("tensor"===s.type)return Bh(t.inputNames[i],n,r,a);if("tensors"===s.type){const s=t.inputs.slice(e,o);return t.inputNames.slice(e,o).filter((e,t)=>{var n;return"NoOp"!==(null===(n=s[t])||void 0===n?void 0:n.op)}).map(e=>Bh(e,n,r,a))}const u=Bh(t.inputNames[i],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:E(u.shape,l)}const o=t.attrParams[e];return o&&o.value}function Bh(e,t,n,r){const[a,s]=Uh(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find(e=>!!t[zh(a,e)]);return void 0!==o?t[zh(a,o)][s]:void 0}function Vh(e,t,n){return t[zh(e,n.currentContextId)]}function Wh(e,t){const[n,r,a]=Uh(e,t);return[zh(n,t&&t.currentContextId),r,a]}function zh(e,t){return t?`${e}-${t}`:e}function Uh(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let a;if(1===r.length)a=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;a=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,a),a}function Gh(e,t,n){let r=Lh("pad",e,t,n);if("explicit"===r){r=Lh("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=r[2*e],a[e][1]=r[2*e+1];return a}return r}function Hh(e){return e.kept?e:Bs(e)}const jh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),qh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Kh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Xh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),Yh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]},Symbol.toStringTag,{value:"Module"})),Qh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Zh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Jh=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),ef=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),tf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),nf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),rf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),af=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),sf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]},Symbol.toStringTag,{value:"Module"})),of=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),uf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),lf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),cf=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),df=Object.freeze(Object.defineProperty({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]},Symbol.toStringTag,{value:"Module"}));class pf{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[jh,qh,Kh,Xh,Yh,Qh,Zh,Jh,ef,tf,nf,rf,af,sf,of,uf,lf,cf,df].map(e=>e.json));this.opMappers=e.reduce((e,t)=>(e[t.tfOpName]=t,e),{})}transformGraph(e,t={}){const n=e.node,r=[],a=[],s=[],o=n.reduce((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||s.push(e[t.name]),e),{});let i=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const d=Object.keys(o);d.forEach(e=>{const t=o[e];t.inputNames.forEach((e,n)=>{const[r,,a]=Wh(e),s=o[r];if(null!=s.outputs){const e=s.outputs.indexOf(a);if(-1!==e){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s),s.children.push(t)})}),0===Object.keys(c).length?d.forEach(e=>{const t=o[e];0===t.children.length&&u.push(t)}):Object.keys(c).forEach(e=>{const[t]=Wh(e),n=o[t];null!=n&&(n.signatureKey=c[e],u.push(n))}),Object.keys(l).length>0?Object.keys(l).forEach(e=>{const[t]=Wh(e),n=o[t];n&&(n.signatureKey=l[e],i.push(n))}):i=r;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce((e,t)=>(e[t.signature.name]=this.mapFunction(t),e),{}));const h={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:p};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=Ph(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(e=>e.startsWith("^")?e.slice(1):e),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce((t,n)=>{const r=n.type;let a;switch(n.type){case"string":a=ff(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=ff(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Nf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Nf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=gf(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=gf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=If(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=If(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=mf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=mf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Tf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Tf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=kf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=kf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Sf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=xf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=xf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=vf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=vf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=bf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=bf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:r},t},{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e),{}));const a=[],s=[];e.signature.inputArg.forEach(e=>{const[t]=Wh(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:yf(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),r[t]=n});Object.keys(r).forEach(e=>{const t=r[e];t.inputNames.forEach((e,n)=>{const[a,,s]=Wh(e),o=r[a];if(null!=o.outputs){const e=o.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)})});const o=e.ret;e.signature.outputArg.forEach(e=>{const[t,n]=Wh(o[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))});const i=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:i}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function hf(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=V().global;if("undefined"!==typeof t.atob)return t.atob(e);if("undefined"!==typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function ff(e,t,n,r=!1){const a=e[t];return null!=a?hf(a.s,r):n}function mf(e,t,n){const r=e[t];return r?r.b:n}function gf(e,t,n){const r=e[t]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"===typeof a?a:parseInt(a,10)}function yf(e){switch("string"===typeof e&&(e=Oh[e]),e){case Oh.DT_FLOAT:case Oh.DT_HALF:return"float32";case Oh.DT_INT32:case Oh.DT_INT64:case Oh.DT_INT8:case Oh.DT_UINT8:return"int32";case Oh.DT_BOOL:return"bool";case Oh.DT_DOUBLE:return"float32";case Oh.DT_STRING:return"string";case Oh.DT_COMPLEX64:case Oh.DT_COMPLEX128:return"complex64";default:return null}}function bf(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function xf(e,t,n){const r=e[t];return r&&r.type?yf(r.type):n}function vf(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map(e=>yf(e)):n}function wf(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(e=>"number"===typeof e.size?e.size:parseInt(e.size,10)):[]}function kf(e,t,n){const r=e[t];return r&&r.shape?wf(r.shape):n}function If(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(e=>"number"===typeof e?e:parseInt(e,10)):n}function Nf(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map(e=>hf(e,r)):n}function Sf(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(e=>wf(e)):n}function Tf(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Cf{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(e=>this.getInput(e)),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce((e,t)=>(e[t]=this.getAttr(t),e),{}))}getInput(e){return Bh(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Bh(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return gf(this.node.rawAttrs,e,t);if(null!=n.s)return ff(this.node.rawAttrs,e,t);if(null!=n.b)return mf(this.node.rawAttrs,e,t);if(null!=n.shape)return kf(this.node.rawAttrs,e,t);if(null!=n.type)return xf(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return If(this.node.rawAttrs,e,t);if(null!=n.list.s)return Nf(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Sf(this.node.rawAttrs,e,t);if(null!=n.list.b)return Tf(this.node.rawAttrs,e,t);if(null!=n.list.type)return vf(this.node.rawAttrs,e,t)}return t}}const $f=Object.freeze(Object.defineProperty({__proto__:null,OP_SCOPE_SUFFIX:_a,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,ensureShape:yi,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upperBound:xc,variable:vc,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));function Ef(e,t,n=""){if("number"!==typeof e&&"number"!==typeof t){i(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;r<e.length;r++){const a=e[r],s=t[r];i(a<0||s<0||a===s,()=>n+` Shapes ${e} and ${t} must match`)}}}function Rf(e){return"number"!==typeof e&&!e.some(e=>e<0)}function _f(e,t,n){let r=Af(e,n);const a=!Rf(r);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(a&&t.forEach(e=>{r=Af(e.shape,r)}),!Rf(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Af(e,t){if("number"===typeof e)return t;if("number"===typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r<e.length;++r){const a=e[r],s=t[r];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=a>=0?a:s}return n}class Of{constructor(e,t,n,r,a,s,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ri(0),Wa(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(e=>this.read(e))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),Ef(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Wa(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((e,n)=>this.write(e,t[n]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t<this.size();t++)e.push(t)}if(0===e.length)return Da([],[0].concat(this.elementShape));const n=this.readMany(e);return Ef(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ec(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return Da([],[0].concat(this.elementShape));const t=[];for(let r=0;r<this.size();r++)t.push(r);const n=this.readMany(t);return Ef(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Io(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,bc(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map(e=>(n+=e,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,s=[];Ba(()=>{t=vo(t,[1,n,a]);for(let n=0;n<e.length;++n){const o=[0,0===n?0:r[n-1],0],i=[1,e[n],a];s[n]=vo(To(t,o,i),this.elementShape)}return s});const o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,s)}}class Ff{get id(){return this.idTensor.id}constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach(e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);Ef(t,e.shape,"TensorList shape mismatch: "),Wa(e)}),this.idTensor=Ri(0),this.maxNumElements=r,Wa(this.idTensor)}copy(){return new Ff([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.id)||t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Ef(e,this.elementShape,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,e);return Ba(()=>{const e=this.tensors.map(e=>vo(e,r));return ec(e,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=_f(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Ef(r.shape,e,"TensorList shape mismatch: "),vo(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ef(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Wa(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Ff([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);Ef(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,t);return vo(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ef(this.elementShape,t.shape,"TensorList shape mismatch: "),Wa(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ef(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=_f(this.elementShape,this.tensors,n);return 0===e.length?Da([],[0].concat(r)):Ba(()=>{const t=e.map(e=>vo(this.tensors[e],r));return ec(t,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ef(this.elementShape,t,"TensorList shape mismatch: ");const n=_f(this.elementShape,this.tensors,t);return 0===this.size()?Da([],[0].concat(n)):Ba(()=>{const e=this.tensors.map(e=>vo(e,n));return Io(e,0)})}}const Df=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=Lh("thenBranch",e,t,n),a=Lh("elseBranch",e,t,n),s=Lh("cond",e,t,n),o=Lh("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=Lh("body",e,t,n),a=Lh("cond",e,t,n),s=Lh("args",e,t,n),o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),i=s.map(e=>e.id);let u=await o[0].data();o.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()});let l=s;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map(e=>e.id);e.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()});const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data(),s.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()})}return l}case"LoopCond":return[Hh(Lh("pred",e,t,n))];case"Switch":{const r=Lh("pred",e,t,n);let a=Lh("data",e,t,n);return a.kept||(a=Hh(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find(e=>void 0!==Bh(e,t,n));if(r){return[Hh(Bh(r,t,n))]}return}case"Enter":{const r=Lh("frameName",e,t,n),a=Lh("tensor",e,t,n);return n.enterFrame(r),[Hh(a)]}case"Exit":{const r=Lh("tensor",e,t,n);return n.exitFrame(),[Hh(r)]}case"NextIteration":{const r=Lh("tensor",e,t,n);return n.nextIteration(),[Hh(r)]}case"TensorArrayV3":{const r=Lh("size",e,t,n),a=Lh("dtype",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("dynamicSize",e,t,n),i=Lh("clearAfterRead",e,t,n),u=Lh("identicalElementShapes",e,t,n),l=Lh("name",e,t,n),c=new Of(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Ri(1)]}case"TensorArrayWriteV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=Lh("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("tensor",e,t,n),s=Lh("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=Lh("tensorArrayId",e,t,n);return[Ri(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=Lh("indices",e,t,n),a=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=r&&-1!==r&&a>=r)throw new Error(`Max index must be < array size (${a} vs. ${r})`);const s=new Ff([],n,e.dtype,r),o=bc(e,0);return t.forEach((e,t)=>{s.setItem(e,o[t])}),s}(Lh("tensor",e,t,n),r,Lh("elementShape",e,t,n),Lh("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=Lh("elementShape",e,t,n),a=Lh("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=Lh(s,e,t,n),i=function(e,t,n,r){return new Ff([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=Lh("tensorListId",e,t,n),a=Lh("indices",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n),o=Lh("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,o)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);Ef(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=bc(e);return new Ff(a,t,r)}(Lh("tensor",e,t,n),Lh("elementShape",e,t,n),Lh("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=Lh("tensorListId",e,t,n),a=n.getTensorList(r.id),s=Lh("dtype",e,t,n),o=Lh("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=Lh("tensorListId",e,t,n),a=Lh("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=Lh("tensor",e,t,n),a=Lh("elementShape",e,t,n),s=function(e,t,n){let r=0;const a=t.map(e=>(r+=e,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const s=Af(e.shape.slice(1),n),o=0===r?0:e.size/r,i=Ba(()=>{const n=[];e=vo(e,[1,r,o]);for(let r=0;r<t.length;++r){const i=[0,0===r?0:a[r-1],0],u=[1,t[r],o];n[r]=vo(To(e,i,u),s)}return e.dispose(),n}),u=new Ff([],n,e.dtype,t.length);for(let l=0;l<i.length;l++)u.setItem(l,i[l]);return u}(r,Lh("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=Lh("tensorListId",e,t,n);return[Ri(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=Lh("tensorListId",e,t,n),a=Lh("size",e,t,n),s=n.getTensorList(r.id).resize(a);return n.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Mf(e,t,n){const[r,a]=Lh("fusedOps",e,t,n),s="biasadd"===r,o=!s,i="prelu"===a,u="fusedbatchnorm"===r,l=Lh("numArgs",e,t,n);if(s){if(i&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&s&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=Lh("strides",e,t,n),d=Gh(e,t,n),p=Lh("dataFormat",e,t,n).toUpperCase(),h=Lh("dilations",e,t,n);let[f,m]=Lh("args",e,t,n);o&&(m=f,f=void 0);return{stride:c,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:Lh("leakyreluAlpha",e,t,n)}}function Pf(e,t,n){return{boxes:Lh("boxes",e,t,n),scores:Lh("scores",e,t,n),maxOutputSize:Lh("maxOutputSize",e,t,n),iouThreshold:Lh("iouThreshold",e,t,n),scoreThreshold:Lh("scoreThreshold",e,t,n),softNmsSigma:Lh("softNmsSigma",e,t,n)}}class Lf{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ri(0),this.tensorMap=new Map,Wa(this.handle)}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ri(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),Ba(()=>{const e=bc(t),r=n.length,a=e.length;i(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let t=0;t<r;t++){const r=n[t],a=e[t];Wa(a),this.tensorMap.set(r,a)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return Ba(()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r],s=this.findWithDefault(a,t);e.push(s)}return ec(e)})}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function Bf(e,t,n,r,a=Ba){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(Lh("a",e,t,n),Lh("b",e,t,n))];case"AddN":return[r.addN(Lh("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(Lh("a",e,t,n),Lh("b",e,t,n))];case"Mul":return[r.mul(Lh("a",e,t,n),Lh("b",e,t,n))];case"RealDiv":case"Div":return[r.div(Lh("a",e,t,n),Lh("b",e,t,n))];case"DivNoNan":return[r.divNoNan(Lh("a",e,t,n),Lh("b",e,t,n))];case"FloorDiv":return[r.floorDiv(Lh("a",e,t,n),Lh("b",e,t,n))];case"Sub":return[r.sub(Lh("a",e,t,n),Lh("b",e,t,n))];case"Minimum":return[r.minimum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Maximum":return[r.maximum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Pow":return[r.pow(Lh("a",e,t,n),Lh("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"basic_math":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(Lh("x",e,t,n))];case"Acos":return[r.acos(Lh("x",e,t,n))];case"Acosh":return[r.acosh(Lh("x",e,t,n))];case"Asin":return[r.asin(Lh("x",e,t,n))];case"Asinh":return[r.asinh(Lh("x",e,t,n))];case"Atan":return[r.atan(Lh("x",e,t,n))];case"Atan2":return[r.atan2(Lh("x",e,t,n),Lh("y",e,t,n))];case"Atanh":return[r.atanh(Lh("x",e,t,n))];case"Ceil":return[r.ceil(Lh("x",e,t,n))];case"Complex":return[r.complex(Lh("real",e,t,n),Lh("imag",e,t,n))];case"Cos":return[r.cos(Lh("x",e,t,n))];case"Cosh":return[r.cosh(Lh("x",e,t,n))];case"Elu":return[r.elu(Lh("x",e,t,n))];case"Erf":return[r.erf(Lh("x",e,t,n))];case"Exp":return[r.exp(Lh("x",e,t,n))];case"Expm1":return[r.expm1(Lh("x",e,t,n))];case"Floor":return[r.floor(Lh("x",e,t,n))];case"Log":return[r.log(Lh("x",e,t,n))];case"Log1p":return[r.log1p(Lh("x",e,t,n))];case"Imag":return[r.imag(Lh("x",e,t,n))];case"Neg":return[r.neg(Lh("x",e,t,n))];case"Reciprocal":return[r.reciprocal(Lh("x",e,t,n))];case"Real":return[r.real(Lh("x",e,t,n))];case"Relu":return[r.relu(Lh("x",e,t,n))];case"Round":return[r.round(Lh("x",e,t,n))];case"Selu":return[r.selu(Lh("x",e,t,n))];case"Sigmoid":return[r.sigmoid(Lh("x",e,t,n))];case"Sin":return[r.sin(Lh("x",e,t,n))];case"Sign":return[r.sign(Lh("x",e,t,n))];case"Sinh":return[r.sinh(Lh("x",e,t,n))];case"Softplus":return[r.softplus(Lh("x",e,t,n))];case"Sqrt":return[r.sqrt(Lh("x",e,t,n))];case"Square":return[r.square(Lh("x",e,t,n))];case"Tanh":return[r.tanh(Lh("x",e,t,n))];case"Tan":return[r.tan(Lh("x",e,t,n))];case"ClipByValue":return[r.clipByValue(Lh("x",e,t,n),Lh("clipValueMin",e,t,n),Lh("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(Lh("x",e,t,n))];case"Rsqrt":return[r.rsqrt(Bh(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"Prelu":return[r.prelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"IsNan":return[r.isNaN(Bh(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(Bh(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(Bh(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"control":return Df(e,t,n);case"convolution":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Conv1D":{const a=Lh("stride",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilation",e,t,n);return[r.conv1d(Lh("x",e,t,n),Lh("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv2d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.conv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.depthwiseConv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=Lh("outputShape",e,t,n),s=Lh("strides",e,t,n),o=Gh(e,t,n);return[r.conv2dTranspose(Lh("x",e,t,n),Lh("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dilations",e,t,n),i=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(Lh("input",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv3d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n),i=Lh("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(Lh("x",e,t,n),Lh("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"creation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Fill":{const a=Lh("shape",e,t,n),s=Lh("dtype",e,t,n),o=Lh("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=Lh("logits",e,t,n),s=Lh("numSamples",e,t,n),o=Lh("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=Lh("indices",e,t,n),s=Lh("depth",e,t,n),o=Lh("onValue",e,t,n),i=Lh("offValue",e,t,n),u=Lh("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"OnesLike":return[r.onesLike(Lh("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(Lh("shape",e,t,n),Lh("dtype",e,t,n),Lh("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("seed",e,t,n))];case"Range":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("step",e,t,n);return[r.range(a,s,o,Lh("dtype",e,t,n))]}case"TruncatedNormal":{const a=Lh("shape",e,t,n),s=Lh("mean",e,t,n),o=Lh("stdDev",e,t,n),i=Lh("seed",e,t,n);return[r.truncatedNormal(a,s,o,Lh("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"dynamic":return(async(e,t,n,r,a=$f)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Pf(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n),l=Lh("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(Lh("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(Lh("x",e,t,n),Lh("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"LowerBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=Lh("x",e,t,n),s=Lh("k",e,t,n),o=Lh("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=Lh("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=Lh("x",e,t,n),s=Lh("axis",e,t,n),o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"image":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ResizeBilinear":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=Lh("image",e,t,n),s=Lh("boxes",e,t,n),o=Lh("boxInd",e,t,n),i=Lh("cropSize",e,t,n),u=Lh("method",e,t,n),l=Lh("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=Lh("images",e,t,n),s=Lh("transforms",e,t,n),o=Lh("outputShape",e,t,n),i=Lh("fillValue",e,t,n),u=Lh("interpolation",e,t,n),l=Lh("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"graph":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=Lh("default",e,t,n);return[Bh(e.name,t,n)||a];case"Placeholder":return[Bh(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[Hh(Lh("x",e,t,n))];case"IdentityN":return Lh("x",e,t,n).map(e=>Hh(e));case"Shape":return[r.tensor1d(Lh("x",e,t,n).shape,"int32")];case"ShapeN":return Lh("x",e,t,n).map(e=>r.tensor1d(e.shape));case"Size":return[r.scalar(Lh("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(Lh("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=Lh("x",e,t,n),o=Lh("data",e,t,n),i=Lh("message",e,t,n),u=Lh("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e<o.length;e++)console.log(Array.prototype.slice.call(o[e].dataSync()).slice(0,u));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"logical":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Equal":return[r.equal(Lh("a",e,t,n),Lh("b",e,t,n))];case"NotEqual":return[r.notEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Greater":return[r.greater(Lh("a",e,t,n),Lh("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Less":return[r.less(Lh("a",e,t,n),Lh("b",e,t,n))];case"LessEqual":return[r.lessEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalNot":return[r.logicalNot(Lh("a",e,t,n))];case"LogicalOr":return[r.logicalOr(Lh("a",e,t,n),Lh("b",e,t,n))];case"Select":case"SelectV2":return[r.where(Lh("condition",e,t,n),Lh("a",e,t,n),Lh("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"matrices":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(Lh("a",e,t,n),Lh("b",e,t,n),Lh("transposeA",e,t,n),Lh("transposeB",e,t,n))];case"Einsum":return[r.einsum(Lh("equation",e,t,n),...Lh("tensors",e,t,n))];case"Transpose":return[r.transpose(Lh("x",e,t,n),Lh("perm",e,t,n))];case"_FusedMatMul":const[a,s]=Lh("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=Lh("numArgs",e,t,n),l=Lh("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,d]=Lh("args",e,t,n);return[r.fused.matMul({a:Lh("a",e,t,n),b:Lh("b",e,t,n),transposeA:Lh("transposeA",e,t,n),transposeB:Lh("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:d,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(Lh("a",e,t,n),Lh("numLower",e,t,n),Lh("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"normalization":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(Lh("x",e,t,n),Lh("axis",e,t,n),Lh("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(Lh("x",e,t,n),Lh("mean",e,t,n),Lh("variance",e,t,n),Lh("offset",e,t,n),Lh("scale",e,t,n),Lh("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(Lh("x",e,t,n),Lh("radius",e,t,n),Lh("bias",e,t,n),Lh("alpha",e,t,n),Lh("beta",e,t,n))];case"Softmax":return[r.softmax(Lh("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"ragged":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(Lh("paramsNestedSplits",e,t,n),Lh("paramsDenseValues",e,t,n),Lh("indices",e,t,n),Lh("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(Lh("starts",e,t,n),Lh("limits",e,t,n),Lh("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(Lh("shape",e,t,n),Lh("values",e,t,n),Lh("defaultValue",e,t,n),Lh("rowPartitionTensors",e,t,n),Lh("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"reduction":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Max":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.max(Lh("x",e,t,n),a,s)]}case"Mean":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.mean(Lh("x",e,t,n),a,s)]}case"Min":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.min(Lh("x",e,t,n),a,s)]}case"Sum":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.sum(Lh("x",e,t,n),a,s)]}case"All":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.all(Lh("x",e,t,n),a,s)]}case"Any":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.any(Lh("x",e,t,n),a,s)]}case"ArgMax":{const a=Lh("axis",e,t,n);return[r.argMax(Lh("x",e,t,n),a)]}case"ArgMin":{const a=Lh("axis",e,t,n);return[r.argMin(Lh("x",e,t,n),a)]}case"Prod":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.prod(Lh("x",e,t,n),a,s)]}case"Cumprod":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumprod(Lh("x",e,t,n),a,s,o)]}case"Cumsum":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumsum(Lh("x",e,t,n),a,s,o)]}case"Bincount":const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n),i=Lh("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"slice_join":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=Lh("n",e,t,n),s=Lh("axis",e,t,n);let o=Lh("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=Lh("axis",e,t,n),s=Lh("batchDims",e,t,n),o=Lh("x",e,t,n),i=Lh("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=Lh("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const o=Lh("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=Lh("axis",e,t,n),s=Lh("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=Lh("begin",e,t,n),s=Lh("size",e,t,n);return[r.slice(Lh("x",e,t,n),a,s)]}case"StridedSlice":{const a=Lh("begin",e,t,n),s=Lh("end",e,t,n),o=Lh("strides",e,t,n),i=Lh("beginMask",e,t,n),u=Lh("endMask",e,t,n),l=Lh("ellipsisMask",e,t,n),c=Lh("newAxisMask",e,t,n),d=Lh("shrinkAxisMask",e,t,n),p=Lh("x",e,t,n);return[r.stridedSlice(p,a,s,o,i,u,l,c,d)]}case"Pack":return Ba(()=>{const a=Lh("axis",e,t,n),s=Lh("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map(e=>{const t=d(e.shape,o);if(!t&&!d(r.squeeze(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,o)});return[r.stack(u,a)]});case"Unpack":{const a=Lh("axis",e,t,n),s=Lh("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=Lh("reps",e,t,n);return[r.tile(Lh("x",e,t,n),a)]}case"Split":case"SplitV":{const a=Lh("axis",e,t,n),s=Lh("numOrSizeSplits",e,t,n),o=Lh("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=Lh("sparseIndices",e,t,n),s=Lh("outputShape",e,t,n),o=Lh("sparseValues",e,t,n),i=Lh("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("tensor",e,t,n);return[r.tensorScatterUpdate(o,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"sparse":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(Lh("indices",e,t,n),Lh("values",e,t,n),Lh("denseShape",e,t,n),Lh("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(Lh("inputIndices",e,t,n),Lh("inputShape",e,t,n),Lh("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"spectral":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"FFT":return[r.fft(Lh("x",e,t,n))];case"IFFT":return[r.ifft(Lh("x",e,t,n))];case"RFFT":return[r.rfft(Lh("x",e,t,n))];case"IRFFT":return[r.irfft(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"string":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(Lh("input",e,t,n),Lh("pattern",e,t,n),Lh("rewrite",e,t,n),Lh("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(Lh("data",e,t,n),Lh("dataSplits",e,t,n),Lh("separator",e,t,n),Lh("nGramWidths",e,t,n),Lh("leftPad",e,t,n),Lh("rightPad",e,t,n),Lh("padWidth",e,t,n),Lh("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(Lh("input",e,t,n),Lh("delimiter",e,t,n),Lh("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(Lh("input",e,t,n),Lh("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"transformation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Cast":return[r.cast(Lh("x",e,t,n),Lh("dtype",e,t,n))];case"ExpandDims":{const a=Lh("axis",e,t,n);return[r.expandDims(Lh("x",e,t,n),a)]}case"Squeeze":{const a=Lh("axis",e,t,n);return[r.squeeze(Lh("x",e,t,n),a)]}case"Reshape":return[r.reshape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("constantValue",e,t,n))];case"SpaceToBatchND":{const a=Lh("blockShape",e,t,n),s=Lh("paddings",e,t,n);return[r.spaceToBatchND(Lh("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=Lh("blockShape",e,t,n),s=Lh("crops",e,t,n);return[r.batchToSpaceND(Lh("x",e,t,n),a,s)]}case"DepthToSpace":{const a=Lh("blockSize",e,t,n),s=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(Lh("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(Lh("x",e,t,n),Lh("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(Lh("s0",e,t,n),Lh("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=r.getHashTableHandleByName(e.name);if(null!=a)return[a];{const a=Lh("keyDType",e,t,n),s=Lh("valueDType",e,t,n),o=new Lf(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Lh("tableHandle",e,t,n,r);return[r.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=Ph(e.op);if(s&&s.customExecutor)return s.customExecutor(new Cf(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return M(s)?s.then(e=>[].concat(e)):[].concat(s)}class Vf{constructor(e={},t={},n={},r={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=a,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function Wf(e,t,n,r){const a=new Set,s=[];let o=null,i=null;const u=new Set,l=new Set(Object.keys(e).map(e=>Uh(e)[0]));r=r||[];const c=new Set(r.map(e=>Uh(e.name)[0])),d=[...t];for(;d.length>0;){const e=d.pop();(qf(e)||Kf(e)||Xf(e))&&null==o&&(o=e,i=o.children.map(e=>e.name).filter(e=>a.has(e))),a.add(e.name),null==n[e.name]&&(l.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach(e=>{u.has(e.name)||(u.add(e.name),d.push(e))}):s.push(e.name)))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}function zf(e,t){const{usedNodes:n,inputs:r}=t,a=Object.keys(r).map(e=>Uh(e)[0]).map(t=>e.nodes[t]),s=e.initNodes||[],o=e=>n.has("string"===typeof e?e:e.name);function i(e){return[...new Map(e.map(e=>[e.name,e])).values()]}const u=i([...a,...e.weights,...s]).filter(o),l=i([...u,...Object.values(e.nodes)]).filter(o),c=new Map(l.map(e=>[e.name,e])),d={};for(const m of l){d[m.name]=d[m.name]||0;for(const e of m.children)o(e)||(d[e.name]=Number.POSITIVE_INFINITY),d[e.name]=(d[e.name]||0)+1}const p=Object.entries(d).filter(([,e])=>0===e).map(([e])=>e),h=[...p];for(;p.length>0;){const e=p.pop(),t=c.get(e);for(const n of t.children.filter(o))0===--d[n.name]&&(h.push(n.name),p.push(n.name))}const f=function(e,t){const n=new Map(e.map(e=>[e.name,e])),r=t.map(e=>e.name),a=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const s of t.children)n.has(s.name)&&!a.has(s.name)&&(a.add(s.name),r.push(s.name))}const s=e.filter(e=>a.has(e.name));return s}(h.map(e=>c.get(e)),u);return function(e,t){const n=new Map(e.map((e,t)=>[e.name,t])),r=new Set(t.map(e=>e.name)),a=e=>r.has("string"===typeof e?e:e.name),s=new Set(e.map(e=>e.name)),o=e=>s.has("string"===typeof e?e:e.name);for(const i of e){for(const e of i.children.filter(o)){if(!n.has(e.name))throw new Uf(`Child ${e.name} of node ${i.name} is unreachable.`);if(n.get(i.name)>n.get(e.name))throw new Uf(`Node ${i.name} is scheduled to run after its child ${e.name}.`)}if(!a(i))for(const e of i.inputs){if(!n.has(e.name))throw new Uf(`Input ${e.name} of node ${i.name} is unreachable.`);if(n.get(e.name)>n.get(i.name))throw new Uf(`Node ${i.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}class Uf extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const Gf=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Hf=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),jf=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function qf(e){return Gf.has(e.op)}function Kf(e){return Hf.has(e.op)}function Xf(e){return jf.has(e.op)}class Yf{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(t=>e[t].map(e=>e.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach(t=>{this._functionExecutorMap[t]=new Yf(e.functions[t],this)})}getCompilationKey(e,t){const n=e.map(e=>e.name).sort(),r=t.map(e=>e.name).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=Wf(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(r.length>0){const n=t.map(e=>e.name),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${r}]`)}const o=zf(this.graph,n),i=function(e){const t=new Map(e.map((e,t)=>[e.name,t])),n=Number.MAX_SAFE_INTEGER,r=e.map((e,t)=>qf(e)?n:t),a=e=>r[t.get(e.name)]??-1,s=e.map((e,t)=>e.children.map(a).reduce((e,t)=>Math.max(e,t),r[t])),o=new Map;for(let i=0;i<e.length;++i){const t=s[i];if(t===n)continue;const r=e[i],a=e[t];o.has(a.name)||o.set(a.name,[]),o.get(a.name).push(r)}return o}(o);return{orderedNodes:o,nodeLiveUntilMap:i}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return Wa(t),t}cloneTensorList(e){if(!e)return null;return e.map(e=>this.cloneAndKeepTensor(e))}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,this.cloneTensorList(t)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map(e=>this.graph.nodes[Uh(e)[0]]),a=t.map(e=>Uh(e)[0]),s=new Set(a);let o=a.map(e=>this.graph.nodes[e]);0===o.length&&(o=this._outputs);const i=this.getCompilationKey(r,o);let u=this.compiledMap.get(i);null==u&&(u=this.compile(e,o),this.compiledMap.set(i,u));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const l={},c={};return Ba(()=>{const n=new Vf(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(t=>{const[a,s]=Uh(t,n),o=[];o[s]=e[t],r[a]=o,this.keepIntermediateTensors&&(this.clonedTensorsMap[a]=this.cloneTensorList(o))});const a=this.getFrozenTensorIds(r),{orderedNodes:o,nodeLiveUntilMap:i}=u;for(const e of o){if(r[e.name])continue;const t=Bf(e,r,n,this._resourceManager);if(M(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,a,s,i.get(e.name))}return null==this.parent&&n.dispose(a),t.map(e=>Bh(e,r,n))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(t=>e[t]).map(e=>e.map(e=>e.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){if(!qf(t)&&!s.has(e)){for(const r of n[e])null!=r&&(o[r.id]=(o[r.id]||0)+t.children.length);for(const e of t.inputs){if(qf(e))continue;const t=Vh(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||a.has(e.id))continue;const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,a,s){function o(e){return qf(e)||a.has(e.name)}if(!qf(e)&&null!=s)for(const i of s){if(o(i))continue;const e=Vh(i.name,t,n);for(const t of e)!t||t.kept||r.has(t.id)||t.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},a={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const s=new Vf(this.weightMap,r,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map(e=>Bh(e,o,s)),u=i.map(e=>e.id),l=Object.keys(e).map(t=>e[t].id),c=new Set([...u,...l,...this.weightIds]);return Object.values(o).forEach(e=>{e.forEach(e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()})}),null==this.parent&&s.dispose(c),i}async executeFunctionAsync(e,t,n){const r=e.reduce((e,t,n)=>(e[this.inputs[n].name]=t,e),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e),s=a.map(e=>this.graph.nodes[Uh(e)[0]]),o=n.map(e=>Uh(e)[0]),i=new Set(o);let u=o.map(e=>this.graph.nodes[e]);0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:d,syncInputs:p}=Wf(e,u,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map(e=>({node:e,contexts:t.currentContext})),f=Object.assign({},this.weightMap);Object.keys(e).forEach(t=>{const[n,r]=Uh(t),a=[];a[r]=e[t],f[n]=a});const m={},g=this.getFrozenTensorIds(f),y={};for(;h.length>0;){const e=this.processStack(s,h,t,f,y,g,i,m,l);await Promise.all(e)}null!=d||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=u.filter(e=>!qf(e)&&!Bh(e.name,f,t)).map(e=>e.name);if(b.length>0){let e="";throw null!=d&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${a}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,r,a,s,o,i,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Lh("isConstant",e.node,r,n)&&([c]=Wh(e.node.name,n)),null==r[e.node.name]){const d=Bf(e.node,r,n,this._resourceManager);c||([c]=Wh(e.node.name,n));const p=n.currentContext;M(d)?l.push(d.then(l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=p,this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u),l))):(r[c]=d,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(d)),this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u))}else this.processChildNodes(e.node,t,n,r,a,u)}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach(e=>{const[o]=Wh(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(e=>e.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[r]=Uh(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;i(e.length===n.shape.length&&n.shape.every((t,n)=>-1===e[n]||e[n]===t),()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&i(n.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){var t,n;const r={};for(const a in e){const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[a];null!=s?r[s.name]=e[a]:r[a]=e[a]}return r}checkInputs(e){const t=Object.keys(e).filter(e=>{const[t]=Uh(e);return null==this.graph.nodes[t]});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e},{})}checkOutputs(e){e.forEach(e=>{const[t]=Uh(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)})}}class Qf{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const Zf="?tfjs-format=file",Jf="model.json";class em{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=mp){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new Qf}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return M(e)?e.then(e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Qa(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new Yf(pf.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=pf.Instance.transformGraph(e.modelInitializer);this.initializer=new Yf(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"===typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof Yr?[e]:e).forEach((e,n)=>t[this.structuredOutputKeys[n]]=e),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Yr)&&!Array.isArray(e)){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce((t,n)=>{var a,s,o;const i=null===(o=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[r++],t},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r<n.length;r++){const a=t[n[r]];this.resourceIdToCapturedInput[a.resourceId]=e[r]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Va(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function tm(e,t={},n=mp){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"===typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}${Jf}${Zf}`}(e));const r=new em(e,t,n);return await r.load(),r}var nm,rm={};function am(){return nm||(nm=1,function(){var e;function t(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var r=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof fr&&fr];for(var t=0;t<e.length;++t){var n=e[t];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);function a(e,t){if(t)e:{var a=r;e=e.split(".");for(var s=0;s<e.length-1;s++){var o=e[s];if(!(o in a))break e;a=a[o]}(t=t(s=a[e=e[e.length-1]]))!=s&&null!=t&&n(a,e,{configurable:!0,writable:!0,value:t})}}function s(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function o(e){var n="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return n?n.call(e):{next:t(e)}}function i(e){if(!(e instanceof Array)){e=o(e);for(var t,n=[];!(t=e.next()).done;)n.push(t.value);e=n}return e}a("Symbol",function(e){function t(e,t){this.h=e,n(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.h};var r="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",a=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(r+(n||"")+"_"+a++,n)}}),a("Symbol.iterator",function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var a="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),o=0;o<a.length;o++){var i=r[a[o]];"function"===typeof i&&"function"!=typeof i.prototype[e]&&n(i.prototype,e,{configurable:!0,writable:!0,value:function(){return s(t(this))}})}return e});var u="function"==typeof Object.assign?Object.assign:function(e,t){for(var n=1;n<arguments.length;n++){var r=arguments[n];if(r)for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a])}return e};a("Object.assign",function(e){return e||u});var l,c="function"==typeof Object.create?Object.create:function(e){function t(){}return t.prototype=e,new t};if("function"==typeof Object.setPrototypeOf)l=Object.setPrototypeOf;else{var d;e:{var p={};try{p.__proto__={a:!0},d=p.a;break e}catch(bn){}d=!1}l=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var h=l;function f(e,t){if(e.prototype=c(t.prototype),e.prototype.constructor=e,h)h(e,t);else for(var n in t)if("prototype"!=n)if(Object.defineProperties){var r=Object.getOwnPropertyDescriptor(t,n);r&&Object.defineProperty(e,n,r)}else e[n]=t[n];e.za=t.prototype}function m(){this.m=!1,this.j=null,this.i=void 0,this.h=1,this.v=this.s=0,this.l=null}function g(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function y(e,t){e.l={ma:t,na:!0},e.h=e.s||e.v}function b(e,t,n){return e.h=n,{value:t}}function x(e){this.h=new m,this.i=e}function v(e,t,n,r){try{var a=t.call(e.h.j,n);if(!(a instanceof Object))throw new TypeError("Iterator result "+a+" is not an object");if(!a.done)return e.h.m=!1,a;var s=a.value}catch(o){return e.h.j=null,y(e.h,o),w(e)}return e.h.j=null,r.call(e.h,s),w(e)}function w(e){for(;e.h.h;)try{var t=e.i(e.h);if(t)return e.h.m=!1,{value:t.value,done:!1}}catch(n){e.h.i=void 0,y(e.h,n)}if(e.h.m=!1,e.h.l){if(t=e.h.l,e.h.l=null,t.na)throw t.ma;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function k(e){this.next=function(t){return g(e.h),e.h.j?t=v(e,e.h.j.next,t,e.h.u):(e.h.u(t),t=w(e)),t},this.throw=function(t){return g(e.h),e.h.j?t=v(e,e.h.j.throw,t,e.h.u):(y(e.h,t),t=w(e)),t},this.return=function(t){return function(e,t){g(e.h);var n=e.h.j;return n?v(e,"return"in n?n.return:function(e){return{value:e,done:!0}},t,e.h.return):(e.h.return(t),w(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function I(e){return function(e){function t(t){return e.next(t)}function n(t){return e.throw(t)}return new Promise(function(r,a){!function e(s){s.done?r(s.value):Promise.resolve(s.value).then(t,n).then(e,a)}(e.next())})}(new k(new x(e)))}function N(e){return e||Array.prototype.fill}m.prototype.u=function(e){this.i=e},m.prototype.return=function(e){this.l={return:e},this.h=this.v},a("Promise",function(e){function t(e){this.i=0,this.j=void 0,this.h=[],this.u=!1;var t=this.l();try{e(t.resolve,t.reject)}catch(n){t.reject(n)}}function n(){this.h=null}function a(e){return e instanceof t?e:new t(function(t){t(e)})}if(e)return e;n.prototype.i=function(e){if(null==this.h){this.h=[];var t=this;this.j(function(){t.m()})}this.h.push(e)};var s=r.setTimeout;n.prototype.j=function(e){s(e,0)},n.prototype.m=function(){for(;this.h&&this.h.length;){var e=this.h;this.h=[];for(var t=0;t<e.length;++t){var n=e[t];e[t]=null;try{n()}catch(r){this.l(r)}}}this.h=null},n.prototype.l=function(e){this.j(function(){throw e})},t.prototype.l=function(){function e(e){return function(r){n||(n=!0,e.call(t,r))}}var t=this,n=!1;return{resolve:e(this.I),reject:e(this.m)}},t.prototype.I=function(e){if(e===this)this.m(new TypeError("A Promise cannot resolve to itself"));else if(e instanceof t)this.L(e);else{e:switch(typeof e){case"object":var n=null!=e;break e;case"function":n=!0;break e;default:n=!1}n?this.F(e):this.s(e)}},t.prototype.F=function(e){var t=void 0;try{t=e.then}catch(n){return void this.m(n)}"function"==typeof t?this.M(t,e):this.s(e)},t.prototype.m=function(e){this.v(2,e)},t.prototype.s=function(e){this.v(1,e)},t.prototype.v=function(e,t){if(0!=this.i)throw Error("Cannot settle("+e+", "+t+"): Promise already settled in state"+this.i);this.i=e,this.j=t,2===this.i&&this.K(),this.H()},t.prototype.K=function(){var e=this;s(function(){if(e.D()){var t=r.console;"undefined"!==typeof t&&t.error(e.j)}},1)},t.prototype.D=function(){if(this.u)return!1;var e=r.CustomEvent,t=r.Event,n=r.dispatchEvent;return"undefined"===typeof n||("function"===typeof e?e=new e("unhandledrejection",{cancelable:!0}):"function"===typeof t?e=new t("unhandledrejection",{cancelable:!0}):(e=r.document.createEvent("CustomEvent")).initCustomEvent("unhandledrejection",!1,!0,e),e.promise=this,e.reason=this.j,n(e))},t.prototype.H=function(){if(null!=this.h){for(var e=0;e<this.h.length;++e)i.i(this.h[e]);this.h=null}};var i=new n;return t.prototype.L=function(e){var t=this.l();e.T(t.resolve,t.reject)},t.prototype.M=function(e,t){var n=this.l();try{e.call(t,n.resolve,n.reject)}catch(r){n.reject(r)}},t.prototype.then=function(e,n){function r(e,t){return"function"==typeof e?function(t){try{a(e(t))}catch(Ug){s(Ug)}}:t}var a,s,o=new t(function(e,t){a=e,s=t});return this.T(r(e,a),r(n,s)),o},t.prototype.catch=function(e){return this.then(void 0,e)},t.prototype.T=function(e,t){function n(){switch(r.i){case 1:e(r.j);break;case 2:t(r.j);break;default:throw Error("Unexpected state: "+r.i)}}var r=this;null==this.h?i.i(n):this.h.push(n),this.u=!0},t.resolve=a,t.reject=function(e){return new t(function(t,n){n(e)})},t.race=function(e){return new t(function(t,n){for(var r=o(e),s=r.next();!s.done;s=r.next())a(s.value).T(t,n)})},t.all=function(e){var n=o(e),r=n.next();return r.done?a([]):new t(function(e,t){function s(t){return function(n){o[t]=n,0==--i&&e(o)}}var o=[],i=0;do{o.push(void 0),i++,a(r.value).T(s(o.length-1),t),r=n.next()}while(!r.done)})},t}),a("Array.prototype.keys",function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var n=0,r=!1,a={next:function(){if(!r&&n<e.length){var a=n++;return{value:t(a,e[a]),done:!1}}return r=!0,{done:!0,value:void 0}}};return a[Symbol.iterator]=function(){return a},a}(this,function(e){return e})}}),a("Array.prototype.fill",function(e){return e||function(e,t,n){var r=this.length||0;for(0>t&&(t=Math.max(0,r+t)),(null==n||n>r)&&(n=r),0>(n=Number(n))&&(n=Math.max(0,r+n)),t=Number(t||0);t<n;t++)this[t]=e;return this}}),a("Int8Array.prototype.fill",N),a("Uint8Array.prototype.fill",N),a("Uint8ClampedArray.prototype.fill",N),a("Int16Array.prototype.fill",N),a("Uint16Array.prototype.fill",N),a("Int32Array.prototype.fill",N),a("Uint32Array.prototype.fill",N),a("Float32Array.prototype.fill",N),a("Float64Array.prototype.fill",N),a("Object.is",function(e){return e||function(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}}),a("Array.prototype.includes",function(e){return e||function(e,t){var n=this;n instanceof String&&(n=String(n));var r=n.length;for(0>(t=t||0)&&(t=Math.max(t+r,0));t<r;t++){var a=n[t];if(a===e||Object.is(a,e))return!0}return!1}}),a("String.prototype.includes",function(e){return e||function(e,t){if(null==this)throw new TypeError("The 'this' value for String.prototype.includes must not be null or undefined");if(e instanceof RegExp)throw new TypeError("First argument to String.prototype.includes must not be a regular expression");return-1!==this.indexOf(e,t||0)}});var S=this||self;function T(e,t){e=e.split(".");var n,r=S;e[0]in r||"undefined"==typeof r.execScript||r.execScript("var "+e[0]);for(;e.length&&(n=e.shift());)e.length||void 0===t?r=r[n]&&r[n]!==Object.prototype[n]?r[n]:r[n]={}:r[n]=t}function C(e){var t;return(t=S.navigator)&&(t=t.userAgent)||(t=""),-1!=t.indexOf(e)}var $=Array.prototype.map?function(e,t){return Array.prototype.map.call(e,t,void 0)}:function(e,t){for(var n=e.length,r=Array(n),a="string"===typeof e?e.split(""):e,s=0;s<n;s++)s in a&&(r[s]=t.call(void 0,a[s],s,e));return r},E={},R=null;function _(e){var t=e.length,n=3*t/4;n%3?n=Math.floor(n):-1!="=.".indexOf(e[t-1])&&(n=-1!="=.".indexOf(e[t-2])?n-2:n-1);var r=new Uint8Array(n),a=0;return function(e,t){function n(t){for(;r<e.length;){var n=e.charAt(r++),a=R[n];if(null!=a)return a;if(!/^[\s\xa0]*$/.test(n))throw Error("Unknown base64 encoding at char: "+n)}return t}A();for(var r=0;;){var a=n(-1),s=n(0),o=n(64),i=n(64);if(64===i&&-1===a)break;t(a<<2|s>>4),64!=o&&(t(s<<4&240|o>>2),64!=i&&t(o<<6&192|i))}}(e,function(e){r[a++]=e}),a!==n?r.subarray(0,a):r}function A(){if(!R){R={};for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"],n=0;5>n;n++){var r=e.concat(t[n].split(""));E[n]=r;for(var a=0;a<r.length;a++){var s=r[a];void 0===R[s]&&(R[s]=a)}}}}var O="undefined"!==typeof Uint8Array,F=!(C("Trident")||C("MSIE"))&&"function"===typeof S.btoa;function D(e){if(!F){var t;void 0===t&&(t=0),A(),t=E[t];for(var n=Array(Math.floor(e.length/3)),r=t[64]||"",a=0,s=0;a<e.length-2;a+=3){var o=e[a],i=e[a+1],u=e[a+2],l=t[o>>2];o=t[(3&o)<<4|i>>4],i=t[(15&i)<<2|u>>6],u=t[63&u],n[s++]=l+o+i+u}switch(l=0,u=r,e.length-a){case 2:u=t[(15&(l=e[a+1]))<<2]||r;case 1:e=e[a],n[s]=t[e>>2]+t[(3&e)<<4|l>>4]+u+r}return n.join("")}for(t="";10240<e.length;)t+=String.fromCharCode.apply(null,e.subarray(0,10240)),e=e.subarray(10240);return t+=String.fromCharCode.apply(null,e),btoa(t)}var M,P=RegExp("[-_.]","g");function L(e){switch(e){case"-":return"+";case"_":return"/";case".":return"=";default:return""}}function B(e){if(!F)return _(e);P.test(e)&&(e=e.replace(P,L)),e=atob(e);for(var t=new Uint8Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function V(){return M||(M=new Uint8Array(0))}var W={},z="function"===typeof Uint8Array.prototype.slice,U=0,G=0;function H(e){var t=0>e,n=(e=Math.abs(e))>>>0;e=Math.floor((e-n)/4294967296),t&&(t=(n=o(K(n,e))).next().value,e=n.next().value,n=t),U=n>>>0,G=e>>>0}var j,q="function"===typeof BigInt;function K(e,t){return t=~t,e?e=1+~e:t+=1,[e,t]}function X(e,t){this.i=e>>>0,this.h=t>>>0}function Y(e){if(!e)return j||(j=new X(0,0));if(!/^-?\d+$/.test(e))return null;if(16>e.length)H(Number(e));else if(q)e=BigInt(e),U=Number(e&BigInt(4294967295))>>>0,G=Number(e>>BigInt(32)&BigInt(4294967295));else{var t=+("-"===e[0]);G=U=0;for(var n=e.length,r=t,a=(n-t)%6+t;a<=n;r=a,a+=6)r=Number(e.slice(r,a)),G*=1e6,4294967296<=(U=1e6*U+r)&&(G+=U/4294967296|0,U%=4294967296);t&&(e=(t=o(K(U,G))).next().value,t=t.next().value,U=e,G=t)}return new X(U,G)}function Q(e,t){return Error("Invalid wire type: "+e+" (at position "+t+")")}function Z(){return Error("Failed to read varint, encoding is invalid.")}function J(e,t){return Error("Tried to read past the end of the data "+t+" > "+e)}function ee(){throw Error("Invalid UTF8")}function te(e,t){return t=String.fromCharCode.apply(null,t),null==e?t:e+t}var ne,re,ae,se=void 0,oe="undefined"!==typeof TextDecoder,ie="undefined"!==typeof TextEncoder;function ue(e){if(e!==W)throw Error("illegal external caller")}function le(e,t){if(ue(t),this.V=e,null!=e&&0===e.length)throw Error("ByteString should be constructed with non-empty values")}function ce(){return ae||(ae=new le(null,W))}function de(e){ue(W);var t=e.V;return null==(t=null==t||O&&null!=t&&t instanceof Uint8Array?t:"string"===typeof t?B(t):null)?t:e.V=t}function pe(e,t){this.i=null,this.m=!1,this.h=this.j=this.l=0,he(this,e,t)}function he(e,t,n){n=void 0===n?{}:n,e.S=void 0!==n.S&&n.S,t&&(t=function(e){if("string"===typeof e)return{buffer:B(e),C:!1};if(Array.isArray(e))return{buffer:new Uint8Array(e),C:!1};if(e.constructor===Uint8Array)return{buffer:e,C:!1};if(e.constructor===ArrayBuffer)return{buffer:new Uint8Array(e),C:!1};if(e.constructor===le)return{buffer:de(e)||V(),C:!0};if(e instanceof Uint8Array)return{buffer:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),C:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}(t),e.i=t.buffer,e.m=t.C,e.l=0,e.j=e.i.length,e.h=e.l)}function fe(e,t){if(e.h=t,t>e.j)throw J(e.j,t)}function me(e){var t=e.i,n=e.h,r=t[n++],a=127&r;if(128&r&&(a|=(127&(r=t[n++]))<<7,128&r&&(a|=(127&(r=t[n++]))<<14,128&r&&(a|=(127&(r=t[n++]))<<21,128&r&&(a|=(r=t[n++])<<28,128&r&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++])))))throw Z();return fe(e,n),a}function ge(e,t){if(0>t)throw Error("Tried to read a negative byte length: "+t);var n=e.h,r=n+t;if(r>e.j)throw J(t,e.j-n);return e.h=r,n}pe.prototype.reset=function(){this.h=this.l};var ye=[];function be(){this.h=[]}function xe(e,t,n){for(;0<n||127<t;)e.h.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;e.h.push(t)}function ve(e,t){for(;127<t;)e.h.push(127&t|128),t>>>=7;e.h.push(t)}function we(e,t){if(ye.length){var n=ye.pop();he(n,e,t),e=n}else e=new pe(e,t);this.h=e,this.j=this.h.h,this.i=this.l=-1,this.setOptions(t)}function ke(e){var t=e.h;if(t.h==t.j)return!1;e.j=e.h.h;var n=me(e.h)>>>0;if(t=n>>>3,!(0<=(n&=7)&&5>=n))throw Q(n,e.j);if(1>t)throw Error("Invalid field number: "+t+" (at position "+e.j+")");return e.l=t,e.i=n,!0}function Ie(e){switch(e.i){case 0:if(0!=e.i)Ie(e);else e:{for(var t=(e=e.h).h,n=t+10,r=e.i;t<n;)if(0===(128&r[t++])){fe(e,t);break e}throw Z()}break;case 1:fe(e=e.h,e.h+8);break;case 2:2!=e.i?Ie(e):(t=me(e.h)>>>0,fe(e=e.h,e.h+t));break;case 5:fe(e=e.h,e.h+4);break;case 3:for(t=e.l;;){if(!ke(e))throw Error("Unmatched start-group tag: stream EOF");if(4==e.i){if(e.l!=t)throw Error("Unmatched end-group tag");break}Ie(e)}break;default:throw Q(e.i,e.j)}}be.prototype.length=function(){return this.h.length},be.prototype.end=function(){var e=this.h;return this.h=[],e},we.prototype.setOptions=function(e){e=void 0===e?{}:e,this.ca=void 0!==e.ca&&e.ca},we.prototype.reset=function(){this.h.reset(),this.j=this.h.h,this.i=this.l=-1};var Ne=[];function Se(){this.j=[],this.i=0,this.h=new be}function Te(e,t){0!==t.length&&(e.j.push(t),e.i+=t.length)}var Ce="function"===typeof Symbol&&"symbol"===typeof Symbol()?Symbol():void 0;function $e(e,t){return Ce?e[Ce]|=t:void 0!==e.A?e.A|=t:(Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}}),t)}function Ee(e,t){Ce?e[Ce]&&(e[Ce]&=~t):void 0!==e.A&&(e.A&=~t)}function Re(e){return(Ce?e[Ce]:e.A)??0}function _e(e,t){Ce?e[Ce]=t:void 0!==e.A?e.A=t:Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}})}function Ae(e){return $e(e,1),e}function Oe(e,t){_e(t,-51&e)}function Fe(e,t){_e(t,-41&e|18)}var De={};function Me(e){return null!==e&&"object"===typeof e&&!Array.isArray(e)&&e.constructor===Object}var Pe,Le,Be=[];function Ve(e){if(2&Re(e.o))throw Error("Cannot mutate an immutable Message")}function We(e){var t=e.length;(t=t?e[t-1]:void 0)&&Me(t)?t.g=1:(t={},e.push((t.g=1,t)))}function ze(e){var t=e.i+e.G;return e.B||(e.B=e.o[t]={})}function Ue(e,t){return-1===t?null:t>=e.i?e.B?e.B[t]:void 0:e.o[t+e.G]}function Ge(e,t,n,r){Ve(e),He(e,t,n,r)}function He(e,t,n,r){e.j&&(e.j=void 0),t>=e.i||r?ze(e)[t]=n:(e.o[t+e.G]=n,(e=e.B)&&t in e&&delete e[t])}function je(e,t,n,r){var a=Ue(e,t);Array.isArray(a)||(a=Pe);var s=Re(a);if(1&s||Ae(a),r)2&s||$e(a,2),1&n||Object.freeze(a);else{r=!(2&n);var o=2&s;1&n||!o?r&&16&s&&!o&&Ee(a,16):He(e,t,a=Ae(Array.prototype.slice.call(a)))}return a}function qe(e,t){var n=Ue(e,t),r=null==n?n:"number"===typeof n||"NaN"===n||"Infinity"===n||"-Infinity"===n?Number(n):void 0;return null!=r&&r!==n&&He(e,t,r),r}function Ke(e,t,n,r,a){e.h||(e.h={});var s=e.h[n],o=je(e,n,3,a);if(!s){var i=o;s=[];var u=!!(16&Re(e.o));o=!!(2&Re(i));var l=i;!a&&o&&(i=Array.prototype.slice.call(i));for(var c=o,d=0;d<i.length;d++){var p=i[d],h=t,f=!1;if(f=void 0!==f&&f,void 0!==(p=Array.isArray(p)?new h(p):f?new h:void 0)){var m=f=Re(h=p.o);o&&(m|=2),u&&(m|=16),m!=f&&_e(h,m),h=m,c=c||!!(2&h),s.push(p)}}return e.h[n]=s,t=33|(u=Re(i)),u!=(t=c?-9&t:8|t)&&(c=i,Object.isFrozen(c)&&(c=Array.prototype.slice.call(c)),_e(c,t),i=c),l!==i&&He(e,n,i),(a||r&&o)&&$e(s,2),r&&Object.freeze(s),s}return a||(a=Object.isFrozen(s),r&&!a?Object.freeze(s):!r&&a&&(s=Array.prototype.slice.call(s),e.h[n]=s)),s}function Xe(e,t,n){var r=!!(2&Re(e.o));if(t=Ke(e,t,n,r,r),e=je(e,n,3,r),!(r||8&Re(e))){for(r=0;r<t.length;r++){if(2&Re((n=t[r]).o)){var a=it(n,!1);a.j=n}else a=n;n!==a&&(t[r]=a,e[r]=a.o)}$e(e,8)}return t}function Ye(e,t,n){if(null!=n&&"number"!==typeof n)throw Error("Value of float/double field must be a number|null|undefined, found "+typeof n+": "+n);Ge(e,t,n)}function Qe(e,t,n,r,a){Ve(e);var s=Ke(e,n,t,!1,!1);return n=null!=r?r:new n,e=je(e,t,2,!1),void 0!=a?(s.splice(a,0,n),e.splice(a,0,n.o)):(s.push(n),e.push(n.o)),n.C()&&Ee(e,8),n}function Ze(e,t){return e??t}function Je(e,t,n){return n=void 0===n?0:n,Ze(qe(e,t),n)}function et(e,t,n,r){if(null!=e){if(Array.isArray(e))e=tt(e,t,n,void 0!==r);else if(Me(e)){var a,s={};for(a in e)s[a]=et(e[a],t,n,r);e=s}else e=t(e,r);return e}}function tt(e,t,n,r){var a=Re(e);r=r?!!(16&a):void 0,e=Array.prototype.slice.call(e);for(var s=0;s<e.length;s++)e[s]=et(e[s],t,n,r);return n(a,e),e}function nt(e){return e.ja===De?e.toJSON():function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"object":if(e)if(Array.isArray(e)){if(0!==(128&Re(e)))return We(e=Array.prototype.slice.call(e)),e}else{if(O&&null!=e&&e instanceof Uint8Array)return D(e);if(e instanceof le){var t=e.V;return null==t?"":"string"===typeof t?t:e.V=D(t)}}}return e}(e)}function rt(e,t){128&e&&We(t)}function at(e,t,n){if(n=void 0===n?Fe:n,null!=e){if(O&&e instanceof Uint8Array)return e.length?new le(new Uint8Array(e),W):ce();if(Array.isArray(e)){var r=Re(e);return 2&r?e:!t||32&r||!(16&r||0===r)?(4&(t=Re(e=tt(e,at,4&r?Fe:n,!0)))&&2&t&&Object.freeze(e),e):(_e(e,2|r),e)}return e.ja===De?ot(e):e}}function st(e,t,n,r,a,s,o){if(e=e.h&&e.h[n]){if(2&(r=Re(e))?r=e:(Fe(r,s=$(e,ot)),Object.freeze(s),r=s),Ve(t),o=null==r?Pe:Ae([]),null!=r){for(s=!!r.length,e=0;e<r.length;e++){var i=r[e];s=s&&!(2&Re(i.o)),o[e]=i.o}s=1|(s?8:0),((e=Re(o))&s)!==s&&(Object.isFrozen(o)&&(o=Array.prototype.slice.call(o)),_e(o,e|s)),t.h||(t.h={}),t.h[n]=r}else t.h&&(t.h[n]=void 0);He(t,n,o,a)}else Ge(t,n,at(r,s,o),a)}function ot(e){return 2&Re(e.o)||$e((e=it(e,!0)).o,2),e}function it(e,t){var n=e.o,r=[];$e(r,16);var a=e.constructor.h;if(a&&r.push(a),a=e.B){r.length=n.length,r.fill(void 0,r.length,n.length);var s={};r[r.length-1]=s}0!==(128&Re(n))&&We(r),t=t||e.C()?Fe:Oe,s=e.constructor,Le=r,r=new s(r),Le=void 0,e.R&&(r.R=e.R.slice()),s=!!(16&Re(n));for(var o=a?n.length-1:n.length,i=0;i<o;i++)st(e,r,i-e.G,n[i],!1,s,t);if(a)for(var u in a)st(e,r,+u,a[u],!0,s,t);return r}function ut(e,t,n){null==e&&(e=Le),Le=void 0;var r,a=this.constructor.i||0,s=0<a,o=this.constructor.h,i=!1;if(null==e){var u=48,l=!0;s&&(a=0,u|=128),_e(e=o?[o]:[],u)}else{if(!Array.isArray(e))throw Error();if(o&&o!==e[0])throw Error();var c=u=$e(e,0);if((l=0!==(16&c))&&((i=0!==(32&c))||(c|=32)),s){if(128&c)a=0;else if(0<e.length){var d=e[e.length-1];if(Me(d)&&"g"in d){a=0,c|=128,delete d.g;var p,h=!0;for(p in d){h=!1;break}h&&e.pop()}}}else if(128&c)throw Error();u!==c&&_e(e,c)}if(this.G=(o?0:-1)-a,this.h=void 0,this.o=e,a=(o=this.o.length)-1,o&&Me(o=this.o[a])?(this.B=o,this.i=a-this.G):void 0!==t&&-1<t?(this.i=Math.max(t,a+1-this.G),this.B=void 0):this.i=Number.MAX_VALUE,!s&&this.B&&"g"in this.B)throw Error('Unexpected "g" flag in sparse object of message that is not a group type.');if(n)for(t=l&&!i&&!0,s=this.i,l=0;l<n.length;l++)(i=n[l])<s?(a=e[i+=this.G])?lt(a,t):e[i]=Pe:(r||(r=ze(this)),(a=r[i])?lt(a,t):r[i]=Pe)}function lt(e,t){if(Array.isArray(e)){var n=Re(e),r=1;!t||2&n||(r|=16),(n&r)!==r&&_e(e,n|r)}}function ct(e,t,n){if(n){var r,a={};for(r in n){var s=n[r],o=s.ra;o||(a.J=s.xa||s.oa.W,s.ia?(a.aa=bt(s.ia),o=function(e){return function(t,n,r){return e.J(t,n,r,e.aa)}}(a)):s.ka?(a.Z=xt(s.da.P,s.ka),o=function(e){return function(t,n,r){return e.J(t,n,r,e.Z)}}(a)):o=a.J,s.ra=o),o(t,e,s.da),a={J:a.J,aa:a.aa,Z:a.Z}}}!function(e,t){if(t=t.R){Te(e,e.h.end());for(var n=0;n<t.length;n++)Te(e,de(t[n])||V())}}(t,e)}_e(Be,23),Pe=Object.freeze(Be),ut.prototype.toJSON=function(){return tt(this.o,nt,rt)},ut.prototype.C=function(){return!!(2&Re(this.o))},ut.prototype.ja=De,ut.prototype.toString=function(){return this.o.toString()};var dt=Symbol();function pt(e,t,n){return e[dt]||(e[dt]=function(e,r){return t(e,r,n)})}function ht(e){var t=e[dt];if(!t){var n=_t(e);t=function(e,t){return At(e,t,n)},e[dt]=t}return t}function ft(e){var t=function(e){var t=e.ia;return t?ht(t):(t=e.wa)?pt(e.da.P,t,e.ka):void 0}(e),n=e.da,r=e.oa.U;return t?function(e,a){return r(e,a,n,t)}:function(e,t){return r(e,t,n)}}function mt(e,t){var n=e[t];return"function"==typeof n&&0===n.length&&(n=n(),e[t]=n),Array.isArray(n)&&(Tt in n||vt in n||0<n.length&&"function"==typeof n[0])?n:void 0}function gt(e,t,n,r,a,s){t.P=e[0];var o=1;if(e.length>o&&"number"!==typeof e[o]){var i=e[o++];n(t,i)}for(;o<e.length;){n=e[o++];for(var u=o+1;u<e.length&&"number"!==typeof e[u];)u++;switch(i=e[o++],u-=o){case 0:r(t,n,i);break;case 1:(u=mt(e,o))?(o++,a(t,n,i,u)):r(t,n,i,e[o++]);break;case 2:a(t,n,i,u=mt(e,u=o++),e[o++]);break;case 3:s(t,n,i,e[o++],e[o++],e[o++]);break;case 4:s(t,n,i,e[o++],e[o++],e[o++],e[o++]);break;default:throw Error("unexpected number of binary field arguments: "+u)}}return t}var yt=Symbol();function bt(e){var t=e[yt];if(!t){var n=St(e);t=function(e,t){return Ot(e,t,n)},e[yt]=t}return t}function xt(e,t){var n=e[yt];return n||(n=function(e,n){return ct(e,n,t)},e[yt]=n),n}var vt=Symbol();function wt(e,t){e.push(t)}function kt(e,t,n){e.push(t,n.W)}function It(e,t,n,r){var a=bt(r),s=St(r).P,o=n.W;e.push(t,function(e,t,n){return o(e,t,n,s,a)})}function Nt(e,t,n,r,a,s){var o=xt(r,s),i=n.W;e.push(t,function(e,t,n){return i(e,t,n,r,o)})}function St(e){var t=e[vt];return t||(t=gt(e,e[vt]=[],wt,kt,It,Nt),Tt in e&&vt in e&&(e.length=0),t)}var Tt=Symbol();function Ct(e,t){e[0]=t}function $t(e,t,n,r){var a=n.U;e[t]=r?function(e,t,n){return a(e,t,n,r)}:a}function Et(e,t,n,r,a){var s=n.U,o=ht(r),i=_t(r).P;e[t]=function(e,t,n){return s(e,t,n,i,o,a)}}function Rt(e,t,n,r,a,s,o){var i=n.U,u=pt(r,a,s);e[t]=function(e,t,n){return i(e,t,n,r,u,o)}}function _t(e){var t=e[Tt];return t||(t=gt(e,e[Tt]={},Ct,$t,Et,Rt),Tt in e&&vt in e&&(e.length=0),t)}function At(e,t,n){for(;ke(t)&&4!=t.i;){var r=t.l,a=n[r];if(!a){var s=n[0];s&&(s=s[r])&&(a=n[r]=ft(s))}if(!a||!a(t,e,r)){r=e,s=(a=t).j,Ie(a);var o=a;if(!o.ca){if(a=o.h.h-s,o.h.h=s,o=o.h,0==a)a=ce();else{if(s=ge(o,a),o.S&&o.m)a=o.i.subarray(s,s+a);else{o=o.i;var i=s;a=i===(a=s+a)?V():z?o.slice(i,a):new Uint8Array(o.subarray(i,a))}a=0==a.length?ce():new le(a,W)}(s=r.R)?s.push(a):r.R=[a]}}}return e}function Ot(e,t,n){for(var r=n.length,a=1==r%2,s=a?1:0;s<r;s+=2)(0,n[s+1])(t,e,n[s]);ct(e,t,a?n[0]:void 0)}function Ft(e,t){return{U:e,W:t}}var Dt=Ft(function(e,t,n){if(5!==e.i)return!1;var r=(e=e.h).i,a=e.h,s=r[a],o=r[a+1],i=r[a+2];return r=r[a+3],fe(e,e.h+4),e=2*((o=(s|o<<8|i<<16|r<<24)>>>0)>>31)+1,s=o>>>23&255,o&=8388607,Ge(t,n,255==s?o?NaN:1/0*e:0==s?e*Math.pow(2,-149)*o:e*Math.pow(2,s-150)*(o+Math.pow(2,23))),!0},function(e,t,n){if(null!=(t=qe(t,n))){ve(e.h,8*n+5),e=e.h;var r=+t;0===r?0<1/r?U=G=0:(G=0,U=2147483648):isNaN(r)?(G=0,U=2147483647):34028234663852886e22<(r=(n=0>r?-2147483648:0)?-r:r)?(G=0,U=(2139095040|n)>>>0):11754943508222875e-54>r?(r=Math.round(r/Math.pow(2,-149)),G=0,U=(n|r)>>>0):(t=Math.floor(Math.log(r)/Math.LN2),r*=Math.pow(2,-t),16777216<=(r=Math.round(8388608*r))&&++t,G=0,U=(n|t+127<<23|8388607&r)>>>0),n=U,e.h.push(n>>>0&255),e.h.push(n>>>8&255),e.h.push(n>>>16&255),e.h.push(n>>>24&255)}}),Mt=Ft(function(e,t,n){if(0!==e.i)return!1;var r=e.h,a=0,s=e=0,o=r.i,i=r.h;do{var u=o[i++];a|=(127&u)<<s,s+=7}while(32>s&&128&u);for(32<s&&(e|=(127&u)>>4),s=3;32>s&&128&u;s+=7)e|=(127&(u=o[i++]))<<s;if(fe(r,i),!(128>u))throw Z();return r=a>>>0,(e=2147483648&(u=e>>>0))&&(u=~u>>>0,0==(r=1+~r>>>0)&&(u=u+1>>>0)),r=4294967296*u+(r>>>0),Ge(t,n,e?-r:r),!0},function(e,t,n){null!=(t=Ue(t,n))&&("string"===typeof t&&Y(t),null!=t&&(ve(e.h,8*n),"number"===typeof t?(e=e.h,H(t),xe(e,U,G)):(n=Y(t),xe(e.h,n.i,n.h))))}),Pt=Ft(function(e,t,n){return 0===e.i&&(Ge(t,n,me(e.h)),!0)},function(e,t,n){if(null!=(t=Ue(t,n))&&null!=t)if(ve(e.h,8*n),e=e.h,0<=(n=t))ve(e,n);else{for(t=0;9>t;t++)e.h.push(127&n|128),n>>=7;e.h.push(1)}}),Lt=Ft(function(e,t,n){if(2!==e.i)return!1;var r=me(e.h)>>>0,a=ge(e=e.h,r);if(e=e.i,oe){var s,o=e;(s=ne)||(s=ne=new TextDecoder("utf-8",{fatal:!0})),e=a+r,o=0===a&&e===o.length?o:o.subarray(a,e);try{var i=s.decode(o)}catch(d){if(void 0===se){try{s.decode(new Uint8Array([128]))}catch(p){}try{s.decode(new Uint8Array([97])),se=!0}catch(p){se=!1}}throw!se&&(ne=void 0),d}}else{r=(i=a)+r,a=[];for(var u,l,c=null;i<r;)128>(u=e[i++])?a.push(u):224>u?i>=r?ee():(l=e[i++],194>u||128!==(192&l)?(i--,ee()):a.push((31&u)<<6|63&l)):240>u?i>=r-1?ee():128!==(192&(l=e[i++]))||224===u&&160>l||237===u&&160<=l||128!==(192&(o=e[i++]))?(i--,ee()):a.push((15&u)<<12|(63&l)<<6|63&o):244>=u?i>=r-2?ee():128!==(192&(l=e[i++]))||0!==l-144+(u<<28)>>30||128!==(192&(o=e[i++]))||128!==(192&(s=e[i++]))?(i--,ee()):(u=(7&u)<<18|(63&l)<<12|(63&o)<<6|63&s,u-=65536,a.push(55296+(u>>10&1023),56320+(1023&u))):ee(),8192<=a.length&&(c=te(c,a),a.length=0);i=te(c,a)}return Ge(t,n,i),!0},function(e,t,n){if(null!=(t=Ue(t,n))){var r=!1;if(r=void 0!==r&&r,ie){if(r&&/(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(t))throw Error("Found an unpaired surrogate");t=(re||(re=new TextEncoder)).encode(t)}else{for(var a=0,s=new Uint8Array(3*t.length),o=0;o<t.length;o++){var i=t.charCodeAt(o);if(128>i)s[a++]=i;else{if(2048>i)s[a++]=i>>6|192;else{if(55296<=i&&57343>=i){if(56319>=i&&o<t.length){var u=t.charCodeAt(++o);if(56320<=u&&57343>=u){i=1024*(i-55296)+u-56320+65536,s[a++]=i>>18|240,s[a++]=i>>12&63|128,s[a++]=i>>6&63|128,s[a++]=63&i|128;continue}o--}if(r)throw Error("Found an unpaired surrogate");i=65533}s[a++]=i>>12|224,s[a++]=i>>6&63|128}s[a++]=63&i|128}}t=a===s.length?s:s.subarray(0,a)}ve(e.h,8*n+2),ve(e.h,t.length),Te(e,e.h.end()),Te(e,t)}}),Bt=Ft(function(e,t,n,r,a){if(2!==e.i)return!1;t=Qe(t,n,r),n=e.h.j,r=me(e.h)>>>0;var s=e.h.h+r,o=s-n;if(0>=o&&(e.h.j=s,a(t,e,void 0,void 0,void 0),o=s-e.h.h),o)throw Error("Message parsing ended unexpectedly. Expected to read "+r+" bytes, instead read "+(r-o)+" bytes, either the data ended unexpectedly or the message misreported its own length");return e.h.h=s,e.h.j=n,!0},function(e,t,n,r,a){if(null!=(t=Xe(t,r,n)))for(r=0;r<t.length;r++){var s=e;ve(s.h,8*n+2);var o=s.h.end();Te(s,o),o.push(s.i),s=o,a(t[r],e),o=e;var i=s.pop();for(i=o.i+o.h.length()-i;127<i;)s.push(127&i|128),i>>>=7,o.i++;s.push(i),o.i++}});function Vt(e){return function(t,n){e:{if(Ne.length){var r=Ne.pop();r.setOptions(n),he(r.h,t,n),t=r}else t=new we(t,n);try{var a=_t(e),s=At(new a.P,t,a);break e}finally{(a=t.h).i=null,a.m=!1,a.l=0,a.j=0,a.h=0,a.S=!1,t.l=-1,t.i=-1,100>Ne.length&&Ne.push(t)}s=void 0}return s}}function Wt(e){return function(){var t=new Se;Ot(this,t,St(e)),Te(t,t.h.end());for(var n=new Uint8Array(t.i),r=t.j,a=r.length,s=0,o=0;o<a;o++){var i=r[o];n.set(i,s),s+=i.length}return t.j=[n],n}}function zt(e){ut.call(this,e)}f(zt,ut);var Ut=[zt,1,Pt,2,Dt,3,Lt,4,Lt];function Gt(e){ut.call(this,e,-1,Ht)}zt.prototype.l=Wt(Ut),f(Gt,ut),Gt.prototype.addClassification=function(e,t){return Qe(this,1,zt,e,t),this};var Ht=[1],jt=Vt([Gt,1,Bt,Ut]);function qt(e){ut.call(this,e)}f(qt,ut);var Kt=[qt,1,Dt,2,Dt,3,Dt,4,Dt,5,Dt];function Xt(e){ut.call(this,e,-1,Yt)}qt.prototype.l=Wt(Kt),f(Xt,ut);var Yt=[1],Qt=Vt([Xt,1,Bt,Kt]);function Zt(e){ut.call(this,e)}f(Zt,ut);var Jt=[Zt,1,Dt,2,Dt,3,Dt,4,Dt,5,Dt,6,Mt],en=Vt(Jt);function tn(e,t,n){if(n=e.createShader(0===n?e.VERTEX_SHADER:e.FRAGMENT_SHADER),e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw Error("Could not compile WebGL shader.\n\n"+e.getShaderInfoLog(n));return n}function nn(e){return Xe(e,zt,1).map(function(e){var t=Ue(e,1);return{index:t??0,qa:Je(e,2),label:null!=Ue(e,3)?Ze(Ue(e,3),""):void 0,displayName:null!=Ue(e,4)?Ze(Ue(e,4),""):void 0}})}function rn(e){return{x:Je(e,1),y:Je(e,2),z:Je(e,3),visibility:null!=qe(e,4)?Je(e,4):void 0}}function an(e,t){this.i=e,this.h=t,this.m=0}function sn(e,t,n){return function(e,t){var n=e.h;if(void 0===e.s){var r=tn(n,"\n attribute vec2 aVertex;\n attribute vec2 aTex;\n varying vec2 vTex;\n void main(void) {\n gl_Position = vec4(aVertex, 0.0, 1.0);\n vTex = aTex;\n }",0),a=tn(n,"\n precision mediump float;\n varying vec2 vTex;\n uniform sampler2D sampler0;\n void main(){\n gl_FragColor = texture2D(sampler0, vTex);\n }",1),s=n.createProgram();if(n.attachShader(s,r),n.attachShader(s,a),n.linkProgram(s),!n.getProgramParameter(s,n.LINK_STATUS))throw Error("Could not compile WebGL program.\n\n"+n.getProgramInfoLog(s));r=e.s=s,n.useProgram(r),a=n.getUniformLocation(r,"sampler0"),e.l={O:n.getAttribLocation(r,"aVertex"),N:n.getAttribLocation(r,"aTex"),ya:a},e.v=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,e.v),n.enableVertexAttribArray(e.l.O),n.vertexAttribPointer(e.l.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),e.u=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,e.u),n.enableVertexAttribArray(e.l.N),n.vertexAttribPointer(e.l.N,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,0,1,1]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.uniform1i(a,0)}r=e.l,n.useProgram(e.s),n.canvas.width=t.width,n.canvas.height=t.height,n.viewport(0,0,t.width,t.height),n.activeTexture(n.TEXTURE0),e.i.bindTexture2d(t.glName),n.enableVertexAttribArray(r.O),n.bindBuffer(n.ARRAY_BUFFER,e.v),n.vertexAttribPointer(r.O,2,n.FLOAT,!1,0,0),n.enableVertexAttribArray(r.N),n.bindBuffer(n.ARRAY_BUFFER,e.u),n.vertexAttribPointer(r.N,2,n.FLOAT,!1,0,0),n.bindFramebuffer(n.DRAW_FRAMEBUFFER?n.DRAW_FRAMEBUFFER:n.FRAMEBUFFER,null),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.colorMask(!0,!0,!0,!0),n.drawArrays(n.TRIANGLE_FAN,0,4),n.disableVertexAttribArray(r.O),n.disableVertexAttribArray(r.N),n.bindBuffer(n.ARRAY_BUFFER,null),e.i.bindTexture2d(0)}(e,t),"function"===typeof e.h.canvas.transferToImageBitmap?Promise.resolve(e.h.canvas.transferToImageBitmap()):n?Promise.resolve(e.h.canvas):"function"===typeof createImageBitmap?createImageBitmap(e.h.canvas):(void 0===e.j&&(e.j=document.createElement("canvas")),new Promise(function(t){e.j.height=e.h.canvas.height,e.j.width=e.h.canvas.width,e.j.getContext("2d",{}).drawImage(e.h.canvas,0,0,e.h.canvas.width,e.h.canvas.height),t(e.j)}))}function on(e){this.h=e}Zt.prototype.l=Wt(Jt);var un=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11]);function ln(e,t){return t+e}function cn(e,t){window[e]=t}function dn(e){if(this.h=e,this.listeners={},this.l={},this.L={},this.s={},this.v={},this.M=this.u=this.ga=!0,this.I=Promise.resolve(),this.fa="",this.D={},this.locateFile=e&&e.locateFile||ln,"object"===typeof window)var t=window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/";else{if("undefined"===typeof location)throw Error("solutions can only be loaded on a web page or in a web worker");t=location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/"}if(this.ha=t,e.options)for(var n=(t=o(Object.keys(e.options))).next();!n.done;n=t.next()){n=n.value;var r=e.options[n].default;void 0!==r&&(this.l[n]="function"===typeof r?r():r)}}function pn(e){var t,n,r,a,s,o,u,l,c,d,p;return I(function(h){switch(h.h){case 1:return e.ga?(t=void 0===e.h.files?[]:"function"===typeof e.h.files?e.h.files(e.l):e.h.files,b(h,I(function(e){switch(e.h){case 1:return e.s=2,b(e,WebAssembly.instantiate(un),4);case 4:e.h=3,e.s=0;break;case 2:return e.s=0,e.l=null,e.return(!1);case 3:return e.return(!0)}}),2)):h.return();case 2:if(n=h.i,"object"===typeof window)return cn("createMediapipeSolutionsWasm",{locateFile:e.locateFile}),cn("createMediapipeSolutionsPackedAssets",{locateFile:e.locateFile}),o=t.filter(function(e){return void 0!==e.data}),u=t.filter(function(e){return void 0===e.data}),l=Promise.all(o.map(function(t){var n=hn(e,t.url);if(void 0!==t.path){var r=t.path;n=n.then(function(t){return e.overrideFile(r,t),Promise.resolve(t)})}return n})),c=Promise.all(u.map(function(t){return void 0===t.simd||t.simd&&n||!t.simd&&!n?function(e){var t=document.createElement("script");return t.setAttribute("src",e),t.setAttribute("crossorigin","anonymous"),new Promise(function(e){t.addEventListener("load",function(){e()},!1),t.addEventListener("error",function(){e()},!1),document.body.appendChild(t)})}(e.locateFile(t.url,e.ha)):Promise.resolve()})).then(function(){var t,n,r;return I(function(a){if(1==a.h)return t=window.createMediapipeSolutionsWasm,n=window.createMediapipeSolutionsPackedAssets,r=e,b(a,t(n),2);r.i=a.i,a.h=0})}),d=I(function(t){return e.h.graph&&e.h.graph.url?t=b(t,hn(e,e.h.graph.url),0):(t.h=0,t=void 0),t}),b(h,Promise.all([c,l,d]),7);if("function"!==typeof importScripts)throw Error("solutions can only be loaded on a web page or in a web worker");return r=t.filter(function(e){return void 0===e.simd||e.simd&&n||!e.simd&&!n}).map(function(t){return e.locateFile(t.url,e.ha)}),importScripts.apply(null,i(r)),a=e,b(h,createMediapipeSolutionsWasm(Module),6);case 6:a.i=h.i,e.m=new OffscreenCanvas(1,1),e.i.canvas=e.m,s=e.i.GL.createContext(e.m,{antialias:!1,alpha:!1,va:"undefined"!==typeof WebGL2RenderingContext?2:1}),e.i.GL.makeContextCurrent(s),h.h=4;break;case 7:if(e.m=document.createElement("canvas"),!(p=e.m.getContext("webgl2",{}))&&!(p=e.m.getContext("webgl",{})))return alert("Failed to create WebGL canvas context when passing video frame."),h.return();e.K=p,e.i.canvas=e.m,e.i.createContext(e.m,!0,!0,{});case 4:e.j=new e.i.SolutionWasm,e.ga=!1,h.h=0}})}function hn(e,t){var n,r;return I(function(a){return t in e.L?a.return(e.L[t]):(n=e.locateFile(t,""),r=fetch(n).then(function(e){return e.arrayBuffer()}),e.L[t]=r,a.return(r))})}function fn(e,t,n){var r,a,s,i,u,l,c,d,p,h,f,m,g,y;return I(function(x){switch(x.h){case 1:if(!n)return x.return(t);for(r={},a=0,s=o(Object.keys(n)),i=s.next();!i.done;i=s.next())u=i.value,"string"!==typeof(l=n[u])&&"texture"===l.type&&void 0!==t[l.stream]&&++a;1<a&&(e.M=!1),c=o(Object.keys(n)),i=c.next();case 2:if(i.done){x.h=4;break}if(d=i.value,"string"===typeof(p=n[d]))return g=r,y=d,b(x,function(e,t,n){var r;return I(function(a){return"number"===typeof n||n instanceof Uint8Array||n instanceof e.i.Uint8BlobList?a.return(n):n instanceof e.i.Texture2dDataOut?((r=e.v[t])||(r=new an(e.i,e.K),e.v[t]=r),a.return(sn(r,n,e.M))):a.return(void 0)})}(e,d,t[p]),14);if(h=t[p.stream],"detection_list"===p.type){if(h){for(var v=h.getRectList(),w=h.getLandmarksList(),k=h.getClassificationsList(),N=[],S=0;S<v.size();++S){var T=en(v.get(S)),C=void 0;C=void 0===C?0:C,T={la:{sa:Je(T,1),ta:Je(T,2),height:Je(T,3),width:Je(T,4),rotation:Je(T,5,0),pa:Ze(Ue(T,6),C)},ea:Xe(Qt(w.get(S)),qt,1).map(rn),ba:nn(jt(k.get(S)))},N.push(T)}v=N}else v=[];r[d]=v,x.h=7;break}if("proto_list"===p.type){if(h){for(v=Array(h.size()),w=0;w<h.size();w++)v[w]=h.get(w);h.delete()}else v=[];r[d]=v,x.h=7;break}if(void 0===h){x.h=3;break}if("float_list"===p.type){r[d]=h,x.h=7;break}if("proto"===p.type){r[d]=h,x.h=7;break}if("texture"!==p.type)throw Error("Unknown output config type: '"+p.type+"'");return(f=e.v[d])||(f=new an(e.i,e.K),e.v[d]=f),b(x,sn(f,h,e.M),13);case 13:m=x.i,r[d]=m;case 7:p.transform&&r[d]&&(r[d]=p.transform(r[d])),x.h=3;break;case 14:g[y]=x.i;case 3:i=c.next(),x.h=2;break;case 4:return x.return(r)}})}function mn(e,t){for(var n=t.name||"$",r=[].concat(i(t.wants)),a=new e.i.StringList,s=o(t.wants),u=s.next();!u.done;u=s.next())a.push_back(u.value);s=e.i.PacketListener.implement({onResults:function(a){for(var s={},o=0;o<t.wants.length;++o)s[r[o]]=a.get(o);var i=e.listeners[n];i&&(e.I=fn(e,s,t.outs).then(function(n){n=i(n);for(var a=0;a<t.wants.length;++a){var o=s[r[a]];"object"===typeof o&&o.hasOwnProperty&&o.hasOwnProperty("delete")&&o.delete()}n&&(e.I=n)}))}}),e.j.attachMultiListener(a,s),a.delete()}function gn(e){return void 0===e&&(e=0),1===e?"selfie_segmentation_landscape.tflite":"selfie_segmentation.tflite"}function yn(e){var t=this;e=e||{},this.h=new dn({locateFile:e.locateFile,files:function(e){return[{simd:!0,url:"selfie_segmentation_solution_simd_wasm_bin.js"},{simd:!1,url:"selfie_segmentation_solution_wasm_bin.js"},{data:!0,url:gn(e.modelSelection)}]},graph:{url:"selfie_segmentation.binarypb"},listeners:[{wants:["segmentation_mask","image_transformed"],outs:{image:{type:"texture",stream:"image_transformed"},segmentationMask:{type:"texture",stream:"segmentation_mask"}}}],inputs:{image:{type:"video",stream:"input_frames_gpu"}},options:{useCpuInference:{type:0,graphOptionXref:{calculatorType:"InferenceCalculator",fieldName:"use_cpu_inference"},default:"object"===typeof window&&void 0!==window.navigator&&("iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document)},selfieMode:{type:0,graphOptionXref:{calculatorType:"GlScalerCalculator",calculatorIndex:1,fieldName:"flip_horizontal"}},modelSelection:{type:1,graphOptionXref:{calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value"},onChange:function(e){var n,r,a;return I(function(s){return 1==s.h?(n=gn(e),r="third_party/mediapipe/modules/selfie_segmentation/"+n,b(s,hn(t.h,n),2)):(a=s.i,t.h.overrideFile(r,a),s.return(!0))})}}}})}(e=dn.prototype).close=function(){return this.j&&this.j.delete(),Promise.resolve()},e.reset=function(){var e=this;return I(function(t){e.j&&(e.j.reset(),e.s={},e.v={}),t.h=0})},e.setOptions=function(e,t){var n=this;if(t=t||this.h.options){for(var r=[],a=[],s={},i=o(Object.keys(e)),u=i.next();!u.done;s={X:s.X,Y:s.Y},u=i.next())if(!((u=u.value)in this.l)||this.l[u]!==e[u]){this.l[u]=e[u];var l=t[u];void 0!==l&&(l.onChange&&(s.X=l.onChange,s.Y=e[u],r.push(function(e){return function(){return I(function(t){if(1==t.h)return b(t,e.X(e.Y),2);!0===t.i&&(n.u=!0),t.h=0})}}(s))),l.graphOptionXref&&(u=Object.assign({},{calculatorName:"",calculatorIndex:0},l.graphOptionXref,{valueNumber:1===l.type?e[u]:0,valueBoolean:0===l.type&&e[u],valueString:2===l.type?e[u]:""}),a.push(u)))}0===r.length&&0===a.length||(this.u=!0,this.H=(void 0===this.H?[]:this.H).concat(a),this.F=(void 0===this.F?[]:this.F).concat(r))}},e.initialize=function(){var e=this;return I(function(t){return 1==t.h?b(t,pn(e),2):3!=t.h?b(t,function(e){var t,n,r,a,s,i,u,l;return I(function(c){if(1==c.h)return e.h.graph&&e.h.graph.url&&e.fa===e.h.graph.url?c.return():(e.u=!0,e.h.graph&&e.h.graph.url?(e.fa=e.h.graph.url,b(c,hn(e,e.h.graph.url),3)):void(c.h=2));for(2!=c.h&&(t=c.i,e.j.loadGraph(t)),n=o(Object.keys(e.D)),r=n.next();!r.done;r=n.next())a=r.value,e.j.overrideFile(a,e.D[a]);if(e.D={},e.h.listeners)for(s=o(e.h.listeners),i=s.next();!i.done;i=s.next())u=i.value,mn(e,u);l=e.l,e.l={},e.setOptions(l),c.h=0})}(e),3):b(t,function(e){var t,n,r,a,s,i;return I(function(u){switch(u.h){case 1:if(!e.u)return u.return();if(!e.F){u.h=2;break}t=o(e.F),n=t.next();case 3:if(n.done){u.h=5;break}return b(u,(0,n.value)(),4);case 4:n=t.next(),u.h=3;break;case 5:e.F=void 0;case 2:if(e.H){for(r=new e.i.GraphOptionChangeRequestList,a=o(e.H),s=a.next();!s.done;s=a.next())i=s.value,r.push_back(i);e.j.changeOptions(r),r.delete(),e.H=void 0}e.u=!1,u.h=0}})}(e),0)})},e.overrideFile=function(e,t){this.j?this.j.overrideFile(e,t):this.D[e]=t},e.clearOverriddenFiles=function(){this.D={},this.j&&this.j.clearOverriddenFiles()},e.send=function(e,t){var n,r,a,s,i,u,l,c,d,p=this;return I(function(h){switch(h.h){case 1:return p.h.inputs?(n=1e3*(t??performance.now()),b(h,p.I,2)):h.return();case 2:return b(h,p.initialize(),3);case 3:for(r=new p.i.PacketDataList,a=o(Object.keys(e)),s=a.next();!s.done;s=a.next())if(i=s.value,u=p.h.inputs[i]){e:{var f=e[i];switch(u.type){case"video":var m=p.s[u.stream];if(m||(m=new an(p.i,p.K),p.s[u.stream]=m),0===m.m&&(m.m=m.i.createTexture()),"undefined"!==typeof HTMLVideoElement&&f instanceof HTMLVideoElement)var g=f.videoWidth,y=f.videoHeight;else"undefined"!==typeof HTMLImageElement&&f instanceof HTMLImageElement?(g=f.naturalWidth,y=f.naturalHeight):(g=f.width,y=f.height);y={glName:m.m,width:g,height:y},(g=m.h).canvas.width=y.width,g.canvas.height=y.height,g.activeTexture(g.TEXTURE0),m.i.bindTexture2d(m.m),g.texImage2D(g.TEXTURE_2D,0,g.RGBA,g.RGBA,g.UNSIGNED_BYTE,f),m.i.bindTexture2d(0),m=y;break e;case"detections":for((m=p.s[u.stream])||(m=new on(p.i),p.s[u.stream]=m),m.data||(m.data=new m.h.DetectionListData),m.data.reset(f.length),y=0;y<f.length;++y){g=f[y];var x=m.data,v=x.setBoundingBox,w=y,k=g.la,I=new Zt;if(Ye(I,1,k.sa),Ye(I,2,k.ta),Ye(I,3,k.height),Ye(I,4,k.width),Ye(I,5,k.rotation),Ge(I,6,k.pa),k=I.l(),v.call(x,w,k),g.ea)for(x=0;x<g.ea.length;++x){I=g.ea[x],w=(v=m.data).addNormalizedLandmark,k=y,I=Object.assign({},I,{visibility:I.visibility?I.visibility:0});var N=new qt;Ye(N,1,I.x),Ye(N,2,I.y),Ye(N,3,I.z),I.visibility&&Ye(N,4,I.visibility),I=N.l(),w.call(v,k,I)}if(g.ba)for(x=0;x<g.ba.length;++x)w=(v=m.data).addClassification,k=y,I=g.ba[x],Ye(N=new zt,2,I.qa),I.index&&Ge(N,1,I.index),I.label&&Ge(N,3,I.label),I.displayName&&Ge(N,4,I.displayName),I=N.l(),w.call(v,k,I)}m=m.data;break e;default:m={}}}switch(l=m,c=u.stream,u.type){case"video":r.pushTexture2d(Object.assign({},l,{stream:c,timestamp:n}));break;case"detections":(d=l).stream=c,d.timestamp=n,r.pushDetectionList(d);break;default:throw Error("Unknown input config type: '"+u.type+"'")}}return p.j.send(r),b(h,p.I,4);case 4:r.delete(),h.h=0}})},e.onResults=function(e,t){this.listeners[t||"$"]=e},T("Solution",dn),T("OptionType",{BOOL:0,NUMBER:1,ua:2,0:"BOOL",1:"NUMBER",2:"STRING"}),(e=yn.prototype).close=function(){return this.h.close(),Promise.resolve()},e.onResults=function(e){this.h.onResults(e)},e.initialize=function(){var e=this;return I(function(t){return b(t,e.h.initialize(),0)})},e.reset=function(){this.h.reset()},e.send=function(e){var t=this;return I(function(n){return b(n,t.h.send(e),0)})},e.setOptions=function(e){this.h.setOptions(e)},T("SelfieSegmentation",yn),T("VERSION","0.1.1675465747")}.call(rm)),rm}var sm=am(),om=function(e,t){return(om=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function im(e,t){function n(){this.constructor=e}om(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var um=function(){return um=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},um.apply(this,arguments)};function lm(e,t,n,r){return new(n||(n=Promise))(function(t,a){function s(e){try{i(r.next(e))}catch(t){a(t)}}function o(e){try{i(r.throw(e))}catch(t){a(t)}}function i(e){var r;e.done?t(e.value):(r=e.value,r instanceof n?r:new n(function(e){e(r)})).then(s,o)}i((r=r.apply(e,[])).next())})}function cm(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(s){return function(i){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(i){s=[6,i],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,i])}}}function dm(e){return e instanceof SVGAnimatedLength?e.baseVal.value:e}function pm(e){return lm(this,0,void 0,function(){var t,n;return cm(this,function(r){switch(r.label){case 0:return t=document.createElement("canvas"),e instanceof Yr?[4,bp(e,t)]:[3,2];case 1:return r.sent(),[3,3];case 2:t.width=dm(e.width),t.height=dm(e.height),n=t.getContext("2d"),e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0),r.label=3;case 3:return[2,t]}})})}function hm(e){return lm(this,0,void 0,function(){var t,n,r,a,s,o;return cm(this,function(i){switch(i.label){case 0:return e instanceof Yr?(t=e.shape.slice(0,2),n=t[0],r=t[1],a=ImageData.bind,[4,bp(e)]):[3,2];case 1:return[2,new(a.apply(ImageData,[void 0,i.sent(),r,n]))];case 2:return s=document.createElement("canvas"),o=s.getContext("2d"),s.width=dm(e.width),s.height=dm(e.height),o.drawImage(e,0,0),[2,o.getImageData(0,0,s.width,s.height)]}})})}function fm(e){return lm(this,0,void 0,function(){var t;return cm(this,function(n){switch(n.label){case 0:return e instanceof SVGImageElement||e instanceof OffscreenCanvas?[4,pm(e)]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t=e,n.label=3;case 3:return[2,xp(t,4)]}})})}function mm(e){if(e<0||e>=256)throw new Error("Mask value must be in range [0, 255] but got "+e);if(!Number.isInteger(e))throw new Error("Mask value must be an integer but got "+e)}function gm(e){var t=e.shape[2],n=Qs(e,2),r=vo(n,[-1]);return Ou(r,t)}function ym(e,t){return Ba(function(){return Ls(Gi(e,Ri(t)),"int32")})}function bm(e,t){var n=t.shape,r=n[0],a=n[1],s=n[2];return Ba(function(){var n=gm(t),o=Li(Nl(0,s,1,"int32"),1),i=Ls(No(n,o),"int32"),u=vo(i,[r,a]),l=Ws(u,Ri(1,"int32"));return uu(Gs(l,e),Ri(1,"int32"))})}var xm=function(){function e(e,t){this.model=e,this.outputStride=t;var n=this.model.inputs[0].shape;i(-1===n[1]&&-1===n[2],function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"})}return e.prototype.predict=function(e){var t=this;return Ba(function(){var n=t.preprocessInput(Ls(e,"float32")),r=Li(n,0),a=t.model.predict(r).map(function(e){return Jl(e,[0])}),s=t.nameOutputResults(a);return{heatmapScores:So(s.heatmap),offsets:s.offsets,displacementFwd:s.displacementFwd,displacementBwd:s.displacementBwd,segmentation:s.segmentation,partHeatmaps:s.partHeatmaps,longOffsets:s.longOffsets,partOffsets:s.partOffsets}})},e.prototype.dispose=function(){this.model.dispose()},e}(),vm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return im(t,e),t.prototype.preprocessInput=function(e){return Ba(function(){return uu(Us(e,127.5),1)})},t.prototype.nameOutputResults=function(e){return{offsets:e[0],segmentation:e[1],partHeatmaps:e[2],longOffsets:e[3],heatmap:e[4],displacementFwd:e[5],displacementBwd:e[6],partOffsets:e[7]}},t}(xm),wm=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],km=wm.length,Im=wm.reduce(function(e,t,n){return e[t]=n,e},{});function Nm(e,t,n){var r=e[0],a=e[1],s=t[0],o=t[1],i=n.top,u=n.bottom;return[o/(n.left+n.right+a),s/(i+u+r)]}function Sm(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+km)}}function Tm(e,t,n){var r=Sm(e.heatmapY,e.heatmapX,e.id,n),a=r.y,s=r.x;return{x:e.heatmapX*t+s,y:e.heatmapY*t+a}}function Cm(e,t,n){return e<t?t:e>n?n:e}function $m(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Em(e,t,n){void 0===n&&(n=.3);for(var r=0,a=0,s=0;s<e.length;s++)t.keypoints[s].score>n&&(a+=1,r+=Math.pow(e[s].x-t.keypoints[s].position.x,2)+Math.pow(e[s].y-t.keypoints[s].position.y,2));return 0===a?r=1/0:r/=a,r}function Rm(e,t,n,r,a,s,o){for(var i=o[0],u=o[1],l=n(e),c=l.y*r+l.x,d=a[km*(2*c)+t],p=a[km*(2*c+1)+t],h=e.y+d,f=e.x+p,m=0;m<s;m++){h=Math.min(h,i-1);var g=n({x:f=Math.min(f,u-1),y:h}),y=g.y*r+g.x;h+=d=a[km*(2*y)+t],f+=p=a[km*(2*y+1)+t]}return{x:f,y:h}}function _m(e,t,n,r,a,s,o,i,u,l){for(var c=a[0],d=a[1],p=s[0],h=s[1],f=i[0],m=i[1],g=[],y=function(e){return function(e,t,n,r){var a=t[0],s=t[1],o=n[0],i=n[1],u=Math.round(((a+e.y+1)*i-1)/r);return{x:Math.round(((s+e.x+1)*o-1)/r),y:u}}(e,[c,d],[p,h],u)},b=0;b<r;b++){var x=Rm(e,b,y,o,t,l,[f,m]);g.push(x)}for(var v=-1,w=1/0,k=0;k<n.length;k++){var I=Em(g,n[k]);I<w&&(v=k,w=I)}return v}function Am(e,t){var n=e[0],r=e[1];return[Math.round((r-1)/t+1),Math.round((n-1)/t+1)]}function Om(e,t,n,r,a,s,o,i,u,l,c){for(var d=o[0],p=o[1],h=e.shape,f=h[0],m=h[1],g=t.shape.slice(0,2),y=g[0],b=g[1],x=vo(t,[y,b,2,km]),v=new Float32Array(c*km*3).fill(0),w=0;w<n.length;w++)for(var k=w*km*3,I=n[w],N=0;N<km;N++){var S=I.keypoints[N],T=k+3*N;v[T]=S.score,v[T+1]=S.position.y,v[T+2]=S.position.x}var C=Nm([r,a],[d,p],i),$=C[0],E=C[1],R=Da(v,[c,km,3]),_=i.top,A=i.left,O={variableNames:["segmentation","longOffsets","poses"],outputShape:[f,m],userCode:"\n int convertToPositionInOutput(int pos, int pad, float scale, int stride) {\n return round(((float(pos + pad) + 1.0) * scale - 1.0) / float(stride));\n }\n\n float convertToPositionInOutputFloat(\n int pos, int pad, float scale, int stride) {\n return ((float(pos + pad) + 1.0) * scale - 1.0) / float(stride);\n }\n\n float dist(float x1, float y1, float x2, float y2) {\n return pow(x1 - x2, 2.0) + pow(y1 - y2, 2.0);\n }\n\n float sampleLongOffsets(float h, float w, int d, int k) {\n float fh = fract(h);\n float fw = fract(w);\n int clH = int(ceil(h));\n int clW = int(ceil(w));\n int flH = int(floor(h));\n int flW = int(floor(w));\n float o11 = getLongOffsets(flH, flW, d, k);\n float o12 = getLongOffsets(flH, clW, d, k);\n float o21 = getLongOffsets(clH, flW, d, k);\n float o22 = getLongOffsets(clH, clW, d, k);\n float o1 = mix(o11, o12, fw);\n float o2 = mix(o21, o22, fw);\n return mix(o1, o2, fh);\n }\n\n int findNearestPose(int h, int w) {\n float prob = getSegmentation(h, w);\n if (prob < 1.0) {\n return -1;\n }\n\n // Done(Tyler): convert from output space h/w to strided space.\n float stridedH = convertToPositionInOutputFloat(\n h, "+_+", "+E+", "+s+");\n float stridedW = convertToPositionInOutputFloat(\n w, "+A+", "+$+", "+s+");\n\n float minDist = 1000000.0;\n int iMin = -1;\n for (int i = 0; i < "+c+"; i++) {\n float curDistSum = 0.0;\n int numKpt = 0;\n for (int k = 0; k < "+km+"; k++) {\n float dy = sampleLongOffsets(stridedH, stridedW, 0, k);\n float dx = sampleLongOffsets(stridedH, stridedW, 1, k);\n\n float y = float(h) + dy;\n float x = float(w) + dx;\n\n for (int s = 0; s < "+u+"; s++) {\n int yRounded = round(min(y, float("+(r-1)+")));\n int xRounded = round(min(x, float("+(a-1)+")));\n\n float yStrided = convertToPositionInOutputFloat(\n yRounded, "+_+", "+E+", "+s+");\n float xStrided = convertToPositionInOutputFloat(\n xRounded, "+A+", "+$+", "+s+");\n\n float dy = sampleLongOffsets(yStrided, xStrided, 0, k);\n float dx = sampleLongOffsets(yStrided, xStrided, 1, k);\n\n y = y + dy;\n x = x + dx;\n }\n\n float poseScore = getPoses(i, k, 0);\n float poseY = getPoses(i, k, 1);\n float poseX = getPoses(i, k, 2);\n if (poseScore > "+l+") {\n numKpt = numKpt + 1;\n curDistSum = curDistSum + dist(x, y, poseX, poseY);\n }\n }\n if (numKpt > 0 && curDistSum / float(numKpt) < minDist) {\n minDist = curDistSum / float(numKpt);\n iMin = i;\n }\n }\n return iMin;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int nearestPose = findNearestPose(coords[0], coords[1]);\n setOutput(float(nearestPose));\n }\n "};return Ha().compileAndRun(O,[e,x,R])}function Fm(){return"webgl"===Ua()}function Dm(e,t,n,r,a,s,o,i,u,l,c,d){var p=o[0],h=o[1];return void 0===u&&(u=.2),void 0===l&&(l=8),void 0===c&&(c=.3),void 0===d&&(d=10),lm(this,0,void 0,function(){var o,f,m,g,y;return cm(this,function(b){switch(b.label){case 0:return o=n.filter(function(e){return e.score>=u}),Fm()?(m=Ba(function(){var n=Om(e,t,o,r,a,s,[p,h],i,l,c,d),u=La().makeTensorFromDataId(n.dataId,n.shape,n.dtype);return o.map(function(e,t){return n=u,r=t,Ba(function(){return Ls(ci(n,Ri(r)),"int32")});var n,r})}),[4,Promise.all(m.map(function(e){return e.data()}))]):[3,2];case 1:return f=b.sent(),m.forEach(function(e){return e.dispose()}),[3,5];case 2:return[4,e.data()];case 3:return g=b.sent(),[4,t.data()];case 4:y=b.sent(),f=function(e,t,n,r,a,s,o,i,u,l){var c=o[0],d=o[1];void 0===l&&(l=5);for(var p=n.map(function(e){return new Uint8Array(r*a).fill(0)}),h=i.top,f=i.left,m=Nm([r,a],[c,d],i),g=m[0],y=m[1],b=Am([c,d],s)[0],x=0;x<r;x+=1)for(var v=0;v<a;v+=1){var w=x*a+v;if(1===e[w]){var k=_m({x:v,y:x},t,n,l,[h,f],[g,y],b,[r,a],s,u);k>=0&&(p[k][w]=1)}}return p}(g,y,o,r,a,s,[p,h],i,l),b.label=5;case 5:return[2,f.map(function(e,t){return{data:e,pose:o[t],width:a,height:r}})]}})})}function Mm(e,t,n,r,a,s,o,i,u,l,c,d,p){var h=i[0],f=i[1];return void 0===l&&(l=.2),void 0===c&&(c=8),void 0===d&&(d=.3),void 0===p&&(p=10),lm(this,0,void 0,function(){var i,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return i=r.filter(function(e){return e.score>=l}),Fm()?(g=Ba(function(){var r=Om(e,t,i,a,s,o,[h,f],u,c,d,p),l=La().makeTensorFromDataId(r.dataId,r.shape,r.dtype);return i.map(function(e,t){return r=l,a=n,s=t,Ba(function(){return uu(Gs(Ls(ci(r,Ri(s)),"int32"),Ws(a,1)),1)});var r,a,s})}),[4,Promise.all(g.map(function(e){return e.data()}))]):[3,2];case 1:return m=v.sent(),g.forEach(function(e){return e.dispose()}),[3,6];case 2:return[4,e.data()];case 3:return y=v.sent(),[4,t.data()];case 4:return b=v.sent(),[4,n.data()];case 5:x=v.sent(),m=function(e,t,n,r,a,s,o,i,u,l,c){var d=i[0],p=i[1];void 0===c&&(c=5);for(var h=r.map(function(e){return new Int32Array(a*s).fill(-1)}),f=u.top,m=u.left,g=Nm([a,s],[d,p],u),y=g[0],b=g[1],x=Am([d,p],o)[0],v=0;v<a;v+=1)for(var w=0;w<s;w+=1){var k=v*s+w;if(1===e[k]){var I=_m({x:w,y:v},t,r,c,[f,m],[y,b],x,[a,s],o,l);I>=0&&(h[I][k]=n[k])}}return h}(y,b,x,i,a,s,o,[h,f],u,c),v.label=6;case 6:return[2,m.map(function(e,t){return{pose:i[t],data:e,height:a,width:s}})]}})})}function Pm(e){return Math.floor(e/2)}[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]});var Lm=function(){function e(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return e.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},e.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},e.prototype.empty=function(){return-1===this.numberOfElements},e.prototype.size=function(){return this.numberOfElements+1},e.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},e.prototype.max=function(){return this.priorityQueue[0]},e.prototype.swim=function(e){for(;e>0&&this.less(Pm(e),e);)this.exchange(e,Pm(e)),e=Pm(e)},e.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(t<this.numberOfElements&&this.less(t,t+1)&&t++,!this.less(e,t))break;this.exchange(e,t),e=t}},e.prototype.getValueAt=function(e){return this.getElementValue(this.priorityQueue[e])},e.prototype.less=function(e,t){return this.getValueAt(e)<this.getValueAt(t)},e.prototype.exchange=function(e,t){var n=this.priorityQueue[e];this.priorityQueue[e]=this.priorityQueue[t],this.priorityQueue[t]=n},e}();function Bm(e,t,n,r,a,s){for(var o=s.shape,i=o[0],u=o[1],l=!0,c=Math.max(n-a,0),d=Math.min(n+a+1,i),p=c;p<d;++p){for(var h=Math.max(r-a,0),f=Math.min(r+a+1,u),m=h;m<f;++m)if(s.get(p,m,e)>t){l=!1;break}if(!l)break}return l}var Vm=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]}),Wm=Vm.map(function(e){return e[1]}),zm=Vm.map(function(e){return e[0]});function Um(e,t,n,r){return{y:Cm(Math.round(e.y/t),0,n-1),x:Cm(Math.round(e.x/t),0,r-1)}}function Gm(e,t,n,r,a,s,o,i){void 0===i&&(i=2);for(var u=r.shape,l=u[0],c=u[1],d=function(e,t,n){var r=n.shape[2]/2;return{y:n.get(t.y,t.x,e),x:n.get(t.y,t.x,r+e)}}(e,Um(t.position,s,l,c),o),p=$m(t.position,d),h=0;h<i;h++){var f=Um(p,s,l,c),m=Sm(f.y,f.x,n,a);p=$m({x:f.x*s,y:f.y*s},{x:m.x,y:m.y})}var g=Um(p,s,l,c),y=r.get(g.y,g.x,n);return{position:p,part:wm[n],score:y}}function Hm(e,t,n,r,a,s){var o=t.shape[2],i=Wm.length,u=new Array(o),l=e.part,c=e.score,d=Tm(l,r,n);u[l.id]={score:c,part:wm[l.id],position:d};for(var p=i-1;p>=0;--p){var h=Wm[p],f=zm[p];u[h]&&!u[f]&&(u[f]=Gm(p,u[h],f,t,n,r,s))}for(p=0;p<i;++p)h=zm[p],f=Wm[p],u[h]&&!u[f]&&(u[f]=Gm(p,u[h],f,t,n,r,a));return u}function jm(e,t,n,r){var a=n.x,s=n.y;return e.some(function(e){var n,o,i,u,l=e.keypoints[r].position;return n=s,o=a,(i=l.y-n)*i+(u=l.x-o)*u<=t})}function qm(e,t,n){return n.reduce(function(n,r,a){var s=r.position,o=r.score;return jm(e,t,s,a)||(n+=o),n},0)/n.length}function Km(e,t,n,r,a,s,o,i){void 0===o&&(o=.5),void 0===i&&(i=20);for(var u=[],l=function(e,t,n){for(var r=n.shape,a=r[0],s=r[1],o=r[2],i=new Lm(a*s*o,function(e){return e.score}),u=0;u<a;++u)for(var l=0;l<s;++l)for(var c=0;c<o;++c){var d=n.get(u,l,c);d<e||Bm(c,d,u,l,1,n)&&i.enqueue({score:d,part:{heatmapY:u,heatmapX:l,id:c}})}return i}(o,0,e),c=i*i;u.length<s&&!l.empty();){var d=l.dequeue();if(!jm(u,c,Tm(d.part,a,t),d.part.id)){var p=Hm(d,e,t,a,n,r),h=qm(u,c,p);u.push({keypoints:p,score:h})}}return u}var Xm,Ym=[-123.15,-115.9,-103.06],Qm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return im(t,e),t.prototype.preprocessInput=function(e){return Ws(e,Ym)},t.prototype.nameOutputResults=function(e){var t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5];return{offsets:s,segmentation:e[6],partHeatmaps:o,longOffsets:a,heatmap:r,displacementFwd:n,displacementBwd:t,partOffsets:e[7]}},t}(xm),Zm="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/",Jm="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/mobilenet/";function eg(e){if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){if("offsetHeight"in e&&0!==e.offsetHeight&&"offsetWidth"in e&&0!==e.offsetWidth)return[e.offsetHeight,e.offsetWidth];if(null!=e.height&&null!=e.width)return[e.height,e.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return[e.height,e.width];if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return(t=e).hasAttribute("height")&&t.hasAttribute("width")?[t.height,t.width]:[t.videoHeight,t.videoWidth];var t;if(e instanceof Yr)return[e.shape[0],e.shape[1]];throw new Error("error: Unknown input type: "+e+".")}function tg(e,t){return(e-1)%t==0?e:Math.floor(e/t)*t+1}var ng={low:"low",medium:"medium",high:"high",full:"full"},rg=((Xm={})[ng.low]=.25,Xm[ng.medium]=.5,Xm[ng.high]=.75,Xm[ng.full]=1,Xm);function ag(e,t,n){var r=n[0],a=n[1],s=function(e){if("string"==typeof e){var t=rg[e];return i("number"==typeof t,function(){return"string value of inputResolution must be one of "+Object.values(ng).join(",")+" but was "+e+"."}),t}return i("number"==typeof e&&e<=2&&e>=.1,function(){return"inputResolution must be a string or number between 0.1 and 2, but was "+e}),e}(e);return[tg(r*s,t),tg(a*s,t)]}function sg(e,t,n,r,a){var s=t[0],o=t[1],i=n[0],u=n[1],l=r[0],c=l[0],d=l[1],p=r[1],h=p[0],f=p[1];return Ba(function(){var t=Md.resizeBilinear(e,[i,u],!0);return function(e,t,n){var r=t[0],a=t[1],s=n[0],o=s[0],i=s[1],u=n[1],l=u[0],c=u[1];return Ba(function(){var t=Li(e);return Jl(Md.cropAndResize(t,[[o/(r+o+i-1),l/(a+l+c-1),(o+r-1)/(r+o+i-1),(l+a-1)/(a+l+c-1)]],[0],[r,a]),[0])})}(t=So(t),[s,o],[[c,d],[h,f]])})}function og(e,t){var n=t[0],r=t[1],a=eg(e),s=a[0],o=a[1],i=r/n,u=[0,0,0,0],l=u[0],c=u[1],d=u[2],p=u[3];return o/s<i?(l=0,c=0,d=Math.round(.5*(i*s-o)),p=Math.round(.5*(i*s-o))):(l=Math.round(.5*(1/i*o-s)),c=Math.round(.5*(1/i*o-s)),d=0,p=0),{resized:Ba(function(){var t,a=(t=e)instanceof Yr?t:xp(t);return a=Bu(a,[[l,c],[d,p],[0,0]]),Md.resizeBilinear(a,[n,r])}),padding:{top:l,left:d,right:p,bottom:c}}}function ig(e){return lm(this,0,void 0,function(){return cm(this,function(t){return[2,Promise.all(e.map(function(e){return e.buffer()}))]})})}function ug(e,t,n,r,a){var s,o,i,u,l,c=t[0],d=t[1],p=n[0],h=n[1],f=(s=e,o=(c+r.top+r.bottom)/p,i=(d+r.left+r.right)/h,u=-r.top,l=-r.left,void 0===u&&(u=0),void 0===l&&(l=0),1===i&&1===o&&0===u&&0===l?s:s.map(function(e){return n=o,r=i,void 0===(a=u)&&(a=0),void 0===(s=l)&&(s=0),{score:(t=e).score,keypoints:t.keypoints.map(function(e){var t=e.score,o=e.part,i=e.position;return{score:t,part:o,position:{x:i.x*r+s,y:i.y*n+a}}})};var t,n,r,a,s}));return a?function(e,t){return t<=0?e:e.map(function(e){return r=t,{score:(n=e).score,keypoints:n.keypoints.map(function(e){var t=e.score,n=e.part,a=e.position;return{score:t,part:n,position:{x:r-1-a.x,y:a.y}}})};var n,r})}(f,d):f}var lg={architecture:"MobileNetV1",outputStride:16,quantBytes:4,multiplier:.75},cg=["MobileNetV1","ResNet50"],dg={MobileNetV1:[8,16,32],ResNet50:[32,16]},pg={MobileNetV1:[.5,.75,1],ResNet50:[1]},hg=[1,2,4],fg={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20},mg={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20,minKeypointScore:.3,refineSteps:10};function gg(e){var t=e.segmentationThreshold,n=e.maxDetections,r=e.scoreThreshold,a=e.nmsRadius;if(t<0||t>1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".")}function yg(e){var t=e.segmentationThreshold,n=e.maxDetections,r=e.scoreThreshold,a=e.nmsRadius,s=e.minKeypointScore,o=e.refineSteps;if(t<0||t>1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".");if(s<0||s>1)throw new Error("Invalid minKeypointScore "+s+".Should be in range [0.0, 1.0]");if(o<=0||o>20)throw new Error("Invalid refineSteps "+o+".Should be in range [1, 20]")}var bg=function(){function e(e){this.baseModel=e}return e.prototype.predictForPersonSegmentation=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForPersonSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,partHeatmapLogits:t.partHeatmaps,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForMultiPersonInstanceSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,longOffsets:t.longOffsets,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd,partHeatmaps:t.partHeatmaps}},e.prototype.segmentPersonActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentation(l),t=e.segmentLogits,a=e.heatmapScores,i=e.offsets,u=e.displacementFwd,d=e.displacementBwd,p=l.shape,h=p[0],f=p[1],m=sg(t,[s,o],[h,f],[[c.top,c.bottom],[c.left,c.right]]);return{segmentation:ym(Jl(m),n),heatmapScores:a,offsets:i,displacementFwd:u,displacementBwd:d}}),p=d.segmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{segmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPerson=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonActivation(e,t.internalResolution,t.segmentationThreshold),r=n.segmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPerson=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I=this;return cm(this,function(N){switch(N.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e,n=I.predictForMultiPersonInstanceSegmentationAndPart(i),o=n.segmentLogits,l=n.longOffsets,c=n.heatmapScores,d=n.offsets,p=n.displacementFwd,h=n.displacementBwd,f=sg(o,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]);return e=l,{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:e,heatmapScoresRaw:c,offsetsRaw:d,displacementFwdRaw:p,displacementBwdRaw:h}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,[4,ig([p,h,f,m])];case 1:return g=N.sent(),y=g[0],b=g[1],x=g[2],v=g[3],w=ug(w=Km(y,b,x,v,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Dm(c,d,w,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return k=N.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),[2,k]}})})},e.prototype.segmentPersonPartsActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentationAndPart(l),t=e.segmentLogits,a=e.partHeatmapLogits,i=e.heatmapScores,u=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=l.shape,f=h[0],m=h[1],g=sg(t,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]),y=sg(a,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]);return{partSegmentation:bm(ym(Jl(g),n),y),heatmapScores:i,offsets:u,displacementFwd:d,displacementBwd:p}}),p=d.partSegmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{partSegmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPersonParts=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonPartsActivation(e,t.internalResolution,t.segmentationThreshold),r=n.partSegmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPersonParts=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I,N=this;return cm(this,function(S){switch(S.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e=N.predictForMultiPersonInstanceSegmentationAndPart(i),n=e.segmentLogits,o=e.longOffsets,l=e.heatmapScores,c=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=e.partHeatmaps,f=sg(n,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),m=sg(h,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),g=o;return{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:g,heatmapScoresRaw:l,offsetsRaw:c,displacementFwdRaw:d,displacementBwdRaw:p,partSegmentation:function(e){var t=e.shape,n=t[0],r=t[1],a=t[2];return Ba(function(){var t=gm(e),s=Li(Nl(0,a,1,"int32"),1),o=Ls(No(t,s),"int32");return vo(o,[n,r])})}(m)}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,g=l.partSegmentation,[4,ig([p,h,f,m])];case 1:return y=S.sent(),b=y[0],x=y[1],v=y[2],w=y[3],k=ug(k=Km(b,x,v,w,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Mm(c,d,g,k,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return I=S.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),g.dispose(),[2,I]}})})},e.prototype.dispose=function(){this.baseModel.dispose()},e}();function xg(e){return lm(this,0,void 0,function(){var t,n,r,a,s,o;return cm(this,function(i){switch(i.label){case 0:if(t=e.outputStride,n=e.quantBytes,r=e.multiplier,null==Ah)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return a=function(e,t,n){var r={1:"100",.75:"075",.5:"050"},a="model-stride"+e+".json";return 4===n?Jm+"float/"+r[t]+"/"+a:Jm+"quant"+n+"/"+r[t]+"/"+a}(t,r,n),[4,tm(e.modelUrl||a)];case 1:return s=i.sent(),o=new vm(s,t),[2,new bg(o)]}})})}function vg(e){return lm(this,0,void 0,function(){var t,n,r,a,s;return cm(this,function(o){switch(o.label){case 0:if(t=e.outputStride,n=e.quantBytes,null==Ah)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return r=function(e,t){var n="model-stride"+e+".json";return 4===t?Zm+"float/"+n:Zm+"quant"+t+"/"+n}(t,n),[4,tm(e.modelUrl||r)];case 1:return a=o.sent(),s=new Qm(a,t),[2,new bg(s)]}})})}function wg(e){return void 0===e&&(e=lg),lm(this,0,void 0,function(){return cm(this,function(t){return"ResNet50"===(e=function(e){if(null==(e=e||lg).architecture&&(e.architecture="MobileNetV1"),cg.indexOf(e.architecture)<0)throw new Error("Invalid architecture "+e.architecture+". Should be one of "+cg);if(null==e.outputStride&&(e.outputStride=16),dg[e.architecture].indexOf(e.outputStride)<0)throw new Error("Invalid outputStride "+e.outputStride+". Should be one of "+dg[e.architecture]+" for architecture "+e.architecture+".");if(null==e.multiplier&&(e.multiplier=1),pg[e.architecture].indexOf(e.multiplier)<0)throw new Error("Invalid multiplier "+e.multiplier+". Should be one of "+pg[e.architecture]+" for architecture "+e.architecture+".");if(null==e.quantBytes&&(e.quantBytes=4),hg.indexOf(e.quantBytes)<0)throw new Error("Invalid quantBytes "+e.quantBytes+". Should be one of "+hg+" for architecture "+e.architecture+".");return e}(e)).architecture?[2,vg(e)]:"MobileNetV1"===e.architecture?[2,xg(e)]:[2,null]})})}var kg=["left_face","right_face","left_upper_arm_front","left_upper_arm_back","right_upper_arm_front","right_upper_arm_back","left_lower_arm_front","left_lower_arm_back","right_lower_arm_front","right_lower_arm_back","left_hand","right_hand","torso_front","torso_back","left_upper_leg_front","left_upper_leg_back","right_upper_leg_front","right_upper_leg_back","left_lower_leg_front","left_lower_leg_back","right_lower_leg_front","right_lower_leg_back","left_feet","right_feet"],Ig=function(){function e(e){this.mask=e}return e.prototype.toCanvasImageSource=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,pm(this.mask)]})})},e.prototype.toImageData=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,this.mask]})})},e.prototype.toTensor=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,fm(this.mask)]})})},e.prototype.getUnderlyingType=function(){return"imagedata"},e}();function Ng(e){if(mm(e),255!==e)throw new Error("Foreground id must be 255 but got "+e);return"person"}function Sg(e){if(mm(e),e>=kg.length)throw new Error("Invalid body part value "+e);return kg[e]}var Tg=function(){function e(e){this.bodyPixModel=e}return e.prototype.segmentPeople=function(e,t){return lm(this,0,void 0,function(){var n,r,a,s;return cm(this,function(o){switch(o.label){case 0:return e instanceof ImageBitmap&&((n=document.createElement("canvas")).getContext("2d").drawImage(e,0,0),e=n),t.segmentBodyParts?t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPersonParts(e,t)]:[3,2]:[3,5];case 1:return a=o.sent(),[3,4];case 2:return[4,this.bodyPixModel.segmentPersonParts(e,t)];case 3:a=[o.sent()],o.label=4;case 4:return r=a.map(function(e){var t=e.data,n=e.width,r=e.height,a=new Uint8ClampedArray(n*r*4).fill(0);return t.forEach(function(e,t){-1===e?(a[4*t]=kg.length,a[4*t+3]=0):(a[4*t]=e,a[4*t+3]=255)}),{maskValueToLabel:Sg,mask:new Ig(new ImageData(a,n,r))}}),[3,10];case 5:return t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPerson(e,t)]:[3,7];case 6:return s=o.sent(),[3,9];case 7:return[4,this.bodyPixModel.segmentPerson(e,t)];case 8:s=[o.sent()],o.label=9;case 9:r=s.map(function(e){var t=e.data,n=e.width,r=e.height,a=new Uint8ClampedArray(n*r*4).fill(0);return t.forEach(function(e,t){0===e?(a[4*t]=0,a[4*t+3]=0):(a[4*t]=255,a[4*t+3]=255)}),{maskValueToLabel:Ng,mask:new Ig(new ImageData(a,n,r))}}),o.label=10;case 10:return[2,r]}})})},e.prototype.dispose=function(){this.bodyPixModel.dispose()},e.prototype.reset=function(){},e}();function Cg(e){return lm(this,0,void 0,function(){return cm(this,function(t){return[2,wg(e).then(function(e){return new Tg(e)})]})})}var $g={runtime:"mediapipe",modelType:"general"},Eg=function(){function e(e){this.mask=e}return e.prototype.toCanvasImageSource=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,this.mask]})})},e.prototype.toImageData=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,hm(this.mask)]})})},e.prototype.toTensor=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,fm(this.mask)]})})},e.prototype.getUnderlyingType=function(){return"canvasimagesource"},e}();function Rg(e){return mm(e),"person"}var _g=function(){function e(e){var t,n,r=this;this.selfieMode=!1,this.selfieSegmentationSolution=new sm.SelfieSegmentation({locateFile:null!==(t=e.locateFile)&&void 0!==t?t:function(t,n){return e.solutionPath?e.solutionPath.replace(/\/+$/,"")+"/"+t:n+"/"+t}}),n="landscape"===e.modelType?1:0,this.selfieSegmentationSolution.setOptions({modelSelection:n,selfieMode:this.selfieMode}),this.selfieSegmentationSolution.onResults(function(e){r.segmentation=[{maskValueToLabel:Rg,mask:new Eg(e.segmentationMask)}]})}return e.prototype.segmentPeople=function(e,t){return lm(this,0,void 0,function(){var n,r;return cm(this,function(a){switch(a.label){case 0:return t&&t.flipHorizontal&&t.flipHorizontal!==this.selfieMode&&(this.selfieMode=t.flipHorizontal,this.selfieSegmentationSolution.setOptions({selfieMode:this.selfieMode})),e instanceof Yr?(r=ImageData.bind,[4,bp(e)]):[3,2];case 1:return n=new(r.apply(ImageData,[void 0,a.sent(),e.shape[1],e.shape[0]])),[3,3];case 2:n=e,a.label=3;case 3:return e=n,[4,this.selfieSegmentationSolution.send({image:e})];case 4:return a.sent(),[2,this.segmentation]}})})},e.prototype.dispose=function(){this.selfieSegmentationSolution.close()},e.prototype.reset=function(){this.selfieSegmentationSolution.reset(),this.segmentation=null,this.selfieMode=!1},e.prototype.initialize=function(){return this.selfieSegmentationSolution.initialize()},e}();function Ag(e){return lm(this,0,void 0,function(){var t,n;return cm(this,function(r){switch(r.label){case 0:return t=function(e){if(null==e)return um({},$g);var t=um({},e);return t.runtime="mediapipe",null==t.modelType&&(t.modelType=$g.modelType),t}(e),[4,(n=new _g(t)).initialize()];case 1:return r.sent(),[2,n]}})})}function Og(e){return e instanceof Yr?{height:e.shape[0],width:e.shape[1]}:{height:e.height,width:e.width}}function Fg(e,t,n){var r,a=t.outputTensorSize,s=t.outputTensorFloatRange,o=Og(e),u={xCenter:.5*(r=o).width,yCenter:.5*r.height,width:r.width,height:r.height,rotation:0},l=function(){return{top:0,left:0,right:0,bottom:0}}(),c=function(e,t,n){var r=e.width,a=e.height,s=Math.cos(e.rotation),o=Math.sin(e.rotation),i=e.xCenter,u=e.yCenter,l=1/t,c=1/n,d=new Array(16);return d[0]=r*s*1*l,d[1]=-a*o*l,d[2]=0,d[3]=(-.5*r*s*1+.5*a*o+i)*l,d[4]=r*o*1*c,d[5]=a*s*c,d[6]=0,d[7]=(-.5*a*s-.5*r*o*1+u)*c,d[8]=0,d[9]=0,d[10]=r*l,d[11]=0,d[12]=0,d[13]=0,d[14]=0,d[15]=1,function(e){if(16!==e.length)throw new Error("Array length must be 16 but got "+e.length);return[[e[0],e[1],e[2],e[3]],[e[4],e[5],e[6],e[7]],[e[8],e[9],e[10],e[11]],[e[12],e[13],e[14],e[15]]]}(d)}(u,o.width,o.height),d=Ba(function(){var t,n=(t=e)instanceof Yr?t:xp(t),r=sc(function(e,t,n){return function(e,t){i(0!==e.width,function(){return t+" width cannot be 0."}),i(0!==e.height,function(){return t+" height cannot be 0."})}(n,"inputResolution"),[1/n.width*e[0][0]*t.width,1/n.height*e[0][1]*t.width,e[0][3]*t.width,1/n.width*e[1][0]*t.height,1/n.height*e[1][1]*t.height,e[1][3]*t.height,0,0]}(c,o,a),[1,8]),u=Md.transform(Li(Ls(n,"float32")),r,"bilinear","constant",0,[a.height,a.width]);return null!=s?function(e,t){var n=function(e,t,n,r){var a=(r-n)/255;return{scale:a,offset:n-0*a}}(0,0,t[0],t[1]);return Ba(function(){return Ws(Gs(e,n.scale),n.offset)})}(u,s):u});return{imageTensor:d,padding:l,transformationMatrix:c}}var Dg={runtime:"tfjs",modelType:"general",modelUrl:"https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1"},Mg={flipHorizontal:!1},Pg={outputTensorSize:{width:256,height:256},outputTensorFloatRange:[0,1]},Lg={outputTensorSize:{width:256,height:144},outputTensorFloatRange:[0,1]},Bg={activation:"none"},Vg=function(){function e(e){this.mask=e}return e.prototype.toCanvasImageSource=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,pm(this.mask)]})})},e.prototype.toImageData=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,hm(this.mask)]})})},e.prototype.toTensor=function(){return lm(this,0,void 0,function(){return cm(this,function(e){return[2,this.mask]})})},e.prototype.getUnderlyingType=function(){return"tensor"},e}();function Wg(e){return mm(e),"person"}var zg,Ug,Gg=function(){function e(e,t){this.modelType=e,this.model=t}return e.prototype.segmentPeople=function(e,t){return lm(this,0,void 0,function(){var n,r=this;return cm(this,function(a){return t=function(e){if(null==e)return um({},Mg);var t=um({},e);return null==t.flipHorizontal&&(t.flipHorizontal=Mg.flipHorizontal),t}(t),null==e?(this.reset(),[2,[]]):(n=Ba(function(){var t=Fg(e,"general"===r.modelType?Pg:Lg).imageTensor,n=To(r.model.predict(t),[0,0,0,1],-1),a=Og(e),s=function(e,t,n){return Ba(function(){var r=Jl(e,[0]),a=r.shape[2];if(1===a){var s=r;switch(t.activation){case"none":break;case"sigmoid":s=So(s);break;case"softmax":throw new Error("Softmax activation requires two channels.");default:throw new Error("Activation not supported ("+t.activation+")")}var o=n?Md.resizeBilinear(s,[n.height,n.width]):s;return Jl(o,[2])}throw new Error("Unsupported number of tensor channels "+a)})}(n,Bg,a),o=Li(s,2),i=Mu(o,[[0,0],[0,0],[0,1]]);return Cu(i,[[0,0],[0,0],[0,2]],"symmetric")}),[2,[{maskValueToLabel:Wg,mask:new Vg(n)}]])})})},e.prototype.dispose=function(){this.model.dispose()},e.prototype.reset=function(){},e}();function Hg(e){return lm(this,0,void 0,function(){var t,n,r;return cm(this,function(a){switch(a.label){case 0:return t=function(e){if(null==e)return um({},Dg);var t=um({},e);if(t.runtime="tfjs",null==t.modelType&&(t.modelType=Dg.modelType),"general"!==t.modelType&&"landscape"!==t.modelType)throw new Error("Model type must be one of general or landscape, but got "+t.modelType);return null==t.modelUrl&&("general"===t.modelType?t.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1":t.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/landscape/1"),t}(e),n="string"==typeof t.modelUrl&&t.modelUrl.indexOf("https://tfhub.dev")>-1,[4,tm(t.modelUrl,{fromTFHub:n})];case 1:return r=a.sent(),[2,new Gg(t.modelType,r)]}})})}(Ug=zg||(zg={})).BodyPix="BodyPix",Ug.MediaPipeSelfieSegmentation="MediaPipeSelfieSegmentation";var jg={};function qg(e){if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){if("offsetHeight"in e&&0!==e.offsetHeight&&"offsetWidth"in e&&0!==e.offsetWidth)return[e.offsetHeight,e.offsetWidth];if(null!=e.height&&null!=e.width)return[e.height,e.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return[e.height,e.width];if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return(t=e).hasAttribute("height")&&t.hasAttribute("width")?[t.height,t.width]:[t.videoHeight,t.videoWidth];var t;if(e instanceof Yr)return[e.shape[0],e.shape[1]];throw new Error("error: Unknown input type: "+e+".")}function Kg(e){return jg[e]||(jg[e]=function(){if("undefined"!=typeof document)return document.createElement("canvas");if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0);throw new Error("Cannot create a canvas in this context")}()),jg[e]}function Xg(e,t){var n,r,a=Kg(t);return n=e,(r=a).width=n.width,r.height=n.height,r.getContext("2d").putImageData(n,0,0),a}function Yg(e,t,n,r,a,s){return lm(this,0,void 0,function(){var o,i,u,l;return cm(this,function(c){switch(c.label){case 0:return t instanceof Yr?[4,bp(t)]:[3,2];case 1:o=c.sent(),i=qg(t),u=i[0],l=i[1],t=new ImageData(o,l,u),c.label=2;case 2:return t instanceof ImageData&&(t=Xg(t,"draw-image")),null==a||null==s?e.drawImage(t,n,r):e.drawImage(t,n,r,a,s),[2]}})})}function Qg(e,t){return lm(this,0,void 0,function(){var n,r,a;return cm(this,function(s){switch(s.label){case 0:return n=qg(e),r=n[0],a=n[1],t.width=a,t.height=r,[4,Yg(t.getContext("2d"),e,0,0,a,r)];case 1:return s.sent(),[2]}})})}function Zg(e,t,n){return lm(this,0,void 0,function(){var r,a,s,o,i,u,l,c;return cm(this,function(d){switch(d.label){case 0:for(r=e.getContext("2d"),a=0,s=5,o=1/(2*Math.PI*s*s),i=n<3?1:2,l=-n;l<=n;l+=i)for(c=-n;c<=n;c+=i)u=o*Math.exp(-(c*c+l*l)/(2*s*s)),a+=u;l=-n,d.label=1;case 1:if(!(l<=n))return[3,6];c=-n,d.label=2;case 2:return c<=n?(r.globalAlpha=o*Math.exp(-(c*c+l*l)/(2*s*s))/a*n,[4,Yg(r,t,c,l)]):[3,5];case 3:d.sent(),d.label=4;case 4:return c+=i,[3,2];case 5:return l+=i,[3,1];case 6:return r.globalAlpha=1,[2]}})})}function Jg(e,t,n){return lm(this,0,void 0,function(){var r,a,s,o;return cm(this,function(i){switch(i.label){case 0:return r=qg(e),a=r[0],s=r[1],o=n.getContext("2d"),n.width=s,n.height=a,o.clearRect(0,0,s,a),o.save(),/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?[4,Zg(n,e,t)]:[3,2];case 1:return i.sent(),[3,4];case 2:return o.filter="blur("+t+"px)",[4,Yg(o,e,0,0,s,a)];case 3:i.sent(),i.label=4;case 4:return o.restore(),[2]}})})}function ey(e,t,n){return lm(this,0,void 0,function(){var r;return cm(this,function(a){switch(a.label){case 0:return r=Kg(n),0!==t?[3,2]:[4,Qg(e,r)];case 1:return a.sent(),[3,4];case 2:return[4,Jg(e,t,r)];case 3:a.sent(),a.label=4;case 4:return[2,r]}})})}function ty(e,t,n,r,a,s){void 0===s&&(s={r:0,g:255,b:255,a:255});for(var o=-a;o<=a;o++)for(var i=-a;i<=a;i++)if(0!==o&&0!==i){var u=(t+o)*r+(n+i);e[4*u+0]=s.r,e[4*u+1]=s.g,e[4*u+2]=s.b,e[4*u+3]=s.a}}function ny(e,t,n,r,a,s,o){void 0===o&&(o=1);for(var i=0,u=-o;u<=o;u++)for(var l=-o;l<=o;l++)if(0!==u&&0!==l){var c=(t+u)*r+(n+l);(!a[e[4*c]]||e[4*c+3]<s)&&(i+=1)}return i>0}function ry(e,t,n,r,a,s){return void 0===r&&(r=.7),void 0===a&&(a=0),void 0===s&&(s=!1),lm(this,0,void 0,function(){var o,i,u,l,c;return cm(this,function(d){switch(d.label){case 0:return o=qg(t),i=o[0],u=o[1],e.width=u,e.height=i,(l=e.getContext("2d")).save(),s&&function(e){var t=e.getContext("2d");t.scale(-1,1),t.translate(-e.width,0)}(e),[4,Yg(l,t,0,0)];case 1:return d.sent(),l.globalAlpha=r,n?(function(e,t,n,r){var a=e.width,s=e.height,o=t.width,i=t.height;if(a!==o||s!==i)throw new Error("error: dimensions must match. "+n+" has dimensions "+a+"x"+s+", "+r+" has dimensions "+o+"x"+i)}({width:u,height:i},n,"image","mask"),[4,ey(Xg(n,"mask"),a,"blurred-mask")]):[3,3];case 2:c=d.sent(),l.drawImage(c,0,0,u,i),d.label=3;case 3:return l.restore(),[2]}})})}const ay={},sy={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function oy(e,t){if(!(e in ay)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=t??function(e){if(V().getBool("IS_SAFARI")||"undefined"===typeof OffscreenCanvas||2!==e){if("undefined"!==typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e);n.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete ay[e]},!1),V().getBool("SOFTWARE_WEBGL_ENABLED")&&(sy.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",sy)||n.getContext("experimental-webgl",sy);return n.getContext("webgl2",sy)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;ay[e]=n}const n=ay[e];return null==n||n.isContextLost()?(delete ay[e],oy(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),ay[e])}var iy,uy,ly,cy,dy,py;function hy(e,t){return[t,e]}function fy(e){const t=c(e);return h(Math.ceil(t/4))}function my(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function gy(e,t){const n=e;let r,a,s,o,i,u,l,c,d,p;return 2===V().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,c=1,d=n.HALF_FLOAT,p=n.FLOAT,u=n.RGBA8):(r=e.RGBA,a=e.RGBA,s=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,c=4,d=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:d,textureTypeFloat:p}}function yy(e,t){const n=t();return V().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}(uy=iy||(iy={}))[uy.DENSE=0]="DENSE",uy[uy.SHARED_BATCH=1]="SHARED_BATCH",(cy=ly||(ly={}))[cy.RENDER=0]="RENDER",cy[cy.UPLOAD=1]="UPLOAD",cy[cy.PIXELS=2]="PIXELS",cy[cy.DOWNLOAD=3]="DOWNLOAD",(py=dy||(dy={}))[py.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",py[py.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",py[py.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",py[py.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",py[py.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16";function by(e){return!!(V().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function xy(e,t){return $y(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}const vy=/ERROR: [0-9]+:([0-9]+):/g;function wy(e,t){const n=vy.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const r=+n[1],a=e.split("\n"),s=a.length.toString().length+2,o=a.map((e,t)=>f((t+1).toString(),s)+e);let i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);const u=o.slice(0,r-1),l=o.slice(r-1,r),c=o.slice(r);console.log(u.join("\n")),console.log(t.split("\n")[0]),console.log(`%c ${f(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function ky(e,t){if(yy(e,()=>e.validateProgram(t)),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Iy(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(yy(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),yy(e,()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o)),yy(e,()=>e.enableVertexAttribArray(i)),!0)}function Ny(e,t,n){!function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}(e,n),yy(e,()=>e.activeTexture(e.TEXTURE0+n)),yy(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function Sy(e,t,n){yy(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),yy(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Ty(e,t){yy(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),yy(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Cy(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(e,t))}function $y(e,t,n){const r=yy(e,()=>t());if(null==r)throw new Error(n);return r}function Ey(e,t=2){return c(e.slice(0,e.length-t))}function Ry(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function _y(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Ey(e),...Ry(e)]),t}function Ay(e){return e%2===0}function Oy(e,t){if(d(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e[e.length-1],r=t[t.length-1];if(n===r)return!0;if(Ay(n)&&Ay(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Ay(e[0])&&Ay(t[0])}let Fy,Dy;function My(e,t){return null!=e.getExtension(t)}function Py(e){try{if(null!=oy(e))return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function Ly(e){if(0===e)return!1;const t=oy(e);if(1!==e){if(My(t,"EXT_color_buffer_float"))return By(t);const e="EXT_color_buffer_half_float";if(My(t,e)){const n=t.getExtension(e);return function(e,t){const n=gy(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);const a=1,s=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,a,s,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(o),i}(t,n)}return!1}if(!My(t,"OES_texture_float"))return!1;if(!My(t,"WEBGL_color_buffer_float"))return!1;return By(t)}function By(e){const t=gy(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),a}function Vy(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&i("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const Wy=V();function zy(){let e,t,n,r,a,s,o,i,u,l;return 2===V().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i=V().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",a="texture2D",s="gl_FragColor",o="",i="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function Uy(e,t,n="index"){const r=C(t);return r.map((t,a)=>`${`int ${e[a]} = ${n} / ${t}`}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`};`).join("")}function Gy(e,t,n="index"){const r=C(t);return r.map((t,a)=>`${`int ${e[a]} = ${n} / outShapeStrides[${a}]`}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`};`).join("")}function Hy(e,t,n="index"){const r=function(e,t){const n=e.length,r=e.map(e=>`${t}[${e}]`),a=new Array(n-1);a[n-2]=r[n-1];for(let s=n-3;s>=0;--s)a[s]=`(${a[s+1]} * ${r[s+1]})`;return a}(e.map((e,t)=>t),t);return r.map((t,a)=>`${`int ${e[a]} = ${n} / ${r[a]}`}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${r[a]}`:`index -= ${e[a]} * ${r[a]}`};`).join("")}function jy(e){const t=C(e).map(e=>e.toString());return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}Wy.registerFlag("HAS_WEBGL",()=>Wy.getNumber("WEBGL_VERSION")>0),Wy.registerFlag("WEBGL_VERSION",()=>Py(2)?2:Py(1)?1:0),Wy.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Wy.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>2===Wy.get("WEBGL_VERSION")),Wy.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Wy.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Wy.registerFlag("WEBGL_PACK",()=>Wy.getBool("HAS_WEBGL")),Wy.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_CLIP",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_REDUCE",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_LAZILY_UNPACK",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_CONV_IM2COL",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>Wy.getBool("WEBGL_PACK")),Wy.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>function(e){if(null==Fy){const t=oy(e);Fy=t.getParameter(t.MAX_TEXTURE_SIZE)}return Fy}(Wy.getNumber("WEBGL_VERSION"))),Wy.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>function(e){if(null==Dy){const t=oy(e);Dy=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Dy)}(Wy.getNumber("WEBGL_VERSION"))),Wy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Wy.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=oy(e);return t=My(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:My(n,"EXT_disjoint_timer_query")?1:0,t}(e)}),Wy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Wy.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Ia()),Wy.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>function(e){if(0===e)return!1;const t=oy(e);if(1===e){if(!My(t,"OES_texture_float"))return!1}else if(!My(t,"EXT_color_buffer_float"))return!1;return By(t)}(Wy.getNumber("WEBGL_VERSION"))),Wy.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>!Wy.getBool("WEBGL_FORCE_F16_TEXTURES")&&Wy.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Wy.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>Ly(Wy.getNumber("WEBGL_VERSION"))),Wy.registerFlag("WEBGL_FENCE_API_ENABLED",()=>{return 2===(e=Wy.getNumber("WEBGL_VERSION"))&&null!=oy(e).fenceSync;var e}),Wy.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Wy.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),Wy.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if("number"!==typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)}),Wy.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Ia()?1:-1,e=>{if("number"!==typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)}),Wy.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),Wy.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),Wy.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),Wy.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),Wy.registerFlag("WEBGL_EXP_CONV",()=>!1),Wy.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>Wy.getBool("IS_TEST")),Wy.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),Wy.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),Wy.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),Wy.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);const qy="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:Ky}=_h;function Xy(e,t,n){const r=[];if(e.forEach(e=>{const t=c(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=ob(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)});const a=r.join("\n"),s=e.map(e=>function(e,t,n=!1,r){let a="";a+=n?Qy(e,r):Yy(e,r);const s=e.shapeInfo.logicalShape,o=t.logicalShape;s.length<=o.length&&(a+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=Ky(e.shapeInfo.logicalShape,t.logicalShape),u=sb(o),l=o-s;let d;const p=["x","y","z","w","u","v"];d=0===s?"":o<2&&i.length>=1?"coords = 0;":i.map(e=>`coords.${p[e+l]} = 0;`).join("\n");let h="";h=o<2&&s>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>`coords.${p[t+l]}`).join(", ");let f="return outputValue;";const m=1===c(e.shapeInfo.logicalShape),g=c(t.logicalShape),y=1===g;if(1!==s||m||y){if(m&&!y)f=1===o?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(i.length){const e=s-2,t=s-1;i.indexOf(e)>-1&&i.indexOf(t)>-1?f="return vec4(outputValue.x);":i.indexOf(e)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(t)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${a}() {\n ${u} coords = getOutputCoords();\n ${d}\n vec4 outputValue = get${r}(${h});\n ${f}\n }\n `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===u&&null==e.shapeInfo.flatOffset&&d(o,s))return`\n float ${a}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=sb(u),c=Ky(e.shapeInfo.logicalShape,t.logicalShape),p=u-i;let h;const f=["x","y","z","w","u","v"];h=0===i?"":u<2&&c.length>=1?"coords = 0;":c.map(e=>`coords.${f[e+p]} = 0;`).join("\n");let m="";m=u<2&&i>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>`coords.${f[t+p]}`).join(", ");return`\n float ${a}() {\n ${l} coords = getOutputCoords();\n ${h}\n return get${r}(${m});\n }\n `}(e,t));return a}(e,t,n.packedInputs,n.enableShapeUniforms)).join("\n"),o=t.texShape,i=zy(),u=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(i);let l,p,h=function(e){const t=`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${Zy}\n ${Jy}\n ${eb}\n `;return t}(i);t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return nb();case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===r[0])return n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${r[1]}.0);\n }\n `;if(1===r[1])return n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${r[0]}.0);\n }\n `;if(n)return"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ";return`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(d(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n }\n `;const a=Math.ceil(e[1]/2);if(n)return"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ";return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2);let o=s,i="",u="b, r, c";for(let l=2;l<e.length-1;l++)o*=e[e.length-l-1],i=`\n int b${l} = index / ${o};\n index -= b${l} * ${o};\n `+i,u=`b${l}, `+u;return`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n ${i}\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec${e.length}(${u});\n }\n `}(e,t,n)}}(t.logicalShape,o,n.enableShapeUniforms),p=function(e){return`\n void setOutput(vec4 val) {\n ${e.output} = val;\n }\n `}(i)):(l=function(e,t,n){switch(e.length){case 0:return nb();case 1:return function(e,t,n){if(1===t[0])return n?"\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.x * ${t[1]}.0);\n }\n `;if(1===t[1])return n?"\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.y * ${t[0]}.0);\n }\n `;if(n)return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n ";return`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.x * ${t[1]} + resTexRC.y;\n }\n `}(0,t,n);case 2:return function(e,t,n){if(d(e,t))return n?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n }\n `;if(1===e[1])return n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `;if(1===e[0])return n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `;if(n)return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n ";return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n){return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Gy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`}const r=Uy(["r","c","d"],e);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec3(r, c, d);\n }\n `}(e,t,n);case 4:return function(e,t,n){if(n){return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Gy(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `}const r=Uy(["r","c","d","d2"],e);return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec4(r, c, d, d2);\n }\n `}(e,t,n);case 5:return function(e,t){const n=Uy(["r","c","d","d2","d3"],e);return`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n ${t[1]}));\n\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `}(e,t);case 6:return function(e,t){const n=Uy(["r","c","d","d2","d3","d4"],e);return`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,o,n.enableShapeUniforms),p=function(e){return`\n void setOutput(float val) {\n ${e.output} = vec4(val, 0, 0, 0);\n }\n `}(i)),n.packedInputs&&(h+=tb);return[h,u,p,a,l,s,n.userCode].join("\n")}function Yy(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;const[a,s]=e.shapeInfo.texShape;if(1===a&&1===s)return`\n float ${r}() {\n return sampleTexture(${n}, halfCR);\n }\n `;const o=rb(n);if(t)return`\n float ${r}() {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});\n return sampleTexture(${n}, uv);\n }\n `;const[i,u]=e.shapeInfo.texShape;return`\n float ${r}() {\n vec2 uv = uvFromFlat(${i}, ${u}, ${o});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n float ${r}(int index) {\n ${ab(e)}\n }\n `;const a=e.shapeInfo.texShape,s=a[0],o=a[1];if(1===o&&1===s)return`\n float ${r}(int index) {\n return sampleTexture(${n}, halfCR);\n }\n `;const i=rb(n);if(1===o)return t?`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(1===s)return t?`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);\n return sampleTexture(${n}, uv);\n }\n `;if(t)return`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});\n return sampleTexture(${n}, uv);\n }\n `;return`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${s}, ${o}, index + ${i});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape;if(null!=s&&d(n,s)){if(t)return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `;const e=s[0];return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${s[1]}.0, ${e}.0);\n return sampleTexture(${r}, uv);\n }\n `}const{newShape:o,keptDims:i}=b(n),u=o;if(u.length<n.length){const n=["row","col"];return`\n ${Yy(ib(e,u),t)}\n float ${a}(int row, int col) {\n return ${a}(${ub(n,i)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n ${ab(e)}\n }\n `;const l=s[0],c=s[1],p=rb(r);if(1===c)return t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(1===l)return t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n return sampleTexture(${r}, uv);\n }\n `;if(t)return`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${r}Shape[1] + col + ${p};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `;return`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${n[1]} + col + ${p};\n vec2 uv = uvFromFlat(${l}, ${c}, index);\n return sampleTexture(${r}, uv);\n }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[1]*n[2],o=n[2],{newShape:i,keptDims:u}=b(n),l=i;if(l.length<n.length){const n=["row","col","depth"];return`\n ${Yy(ib(e,l),t)}\n float ${a}(int row, int col, int depth) {\n return ${a}(${ub(n,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${s}, ${o}, 1)));\n ${ab(e)}\n }\n `;const c=e.shapeInfo.texShape,d=c[0],p=c[1],h=e.shapeInfo.flatOffset;if(p===s&&null==h)return t?`\n float ${a}(int row, int col, int depth) {\n int stride1 = ${r}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${o}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${d}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(p===o&&null==h)return t?`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);\n return sampleTexture(${r}, uv);\n }\n `;const f=rb(r);if(t)return`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${r}Shape[1] * ${r}Shape[2];\n int stride1 = ${r}Shape[2];\n int index = row * stride0 + col * stride1 + depth + ${f};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `;return`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${s} + col * ${o} + depth + ${f};\n vec2 uv = uvFromFlat(${d}, ${p}, index);\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[3],o=n[2]*s,i=n[1]*o,{newShape:u,keptDims:l}=b(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n ${Yy(ib(e,u),t)}\n float ${a}(int row, int col, int depth, int depth2) {\n return ${a}(${ub(n,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, 1)));\n ${ab(e)}\n }\n `;const c=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n ${f}\n ${m}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${o}, ${s}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(h===s&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${n[1]*n[2]}, ${n[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;const y=rb(r);if(t)return`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${f}\n ${m}\n ${g}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${y});\n return sampleTexture(${r}, uv);\n }\n `;return`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} +\n depth * ${s} + depth2;\n vec2 uv = uvFromFlat(${p}, ${h}, index + ${y});\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[4],s=t[3]*a,o=t[2]*s,i=t[1]*o,{newShape:u,keptDims:l}=b(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${Yy(ib(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${ub(t,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, ${a})) +\n depth3;\n ${ab(e)}\n }\n `;const c=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&null==c)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${o}, ${s}, ${a}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(h===a&&null==c)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]},\n ${t[2]*t[3]}, ${t[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;const f=rb(n);return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} + depth * ${s} +\n depth2 * ${a} + depth3 + ${f};\n vec2 uv = uvFromFlat(${p}, ${h}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:a,keptDims:s}=b(t);if(a.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${Yy(ib(e,a))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${ub(t,s)});\n }\n `}const o=t[5],i=t[4]*o,u=t[3]*i,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${c}, ${l}, ${u}, ${i})) +\n dot(\n vec2(depth3, depth4),\n vec2(${o}, 1)));\n ${ab(e)}\n }\n `;const d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===c&&null==d)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${l}, ${u}, ${i}, ${o})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(f===o&&null==d)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]*t[4]},\n ${t[2]*t[3]*t[4]},\n ${t[3]*t[4]},\n ${t[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `;const m=rb(n);return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth2 * ${i} + depth3 * ${o} + depth4 + ${m};\n vec2 uv = uvFromFlat(${h}, ${f}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function Qy(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=zy();return`\n vec4 ${n}() {\n return ${r.texture2D}(${t}, halfCR);\n }\n `}(e);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,s=zy();if(t)return`\n vec4 ${r}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${s.texture2D}(${n}, uv);\n }\n `;const o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n vec4 ${r}(int index) {\n vec2 uv = packedUVfrom1D(\n ${o[0]}, ${o[1]}, index);\n return ${s.texture2D}(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=s[0],i=s[1],u=zy();if(null!=s&&d(n,s))return t?`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n\n return ${u.texture2D}(${r}, uv);\n }\n `:`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);\n\n return ${u.texture2D}(${r}, uv);\n }\n `;if(t)return`\n vec4 ${a}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `;const l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],c=Math.ceil(n[1]/2);return`\n vec4 ${a}(int row, int col) {\n vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(1===n[0]){const r=[1,2],s=["b","row","col"];return`\n ${Qy(ib(e,n.slice(1)),t)}\n vec4 ${a}(int b, int row, int col) {\n return ${a}(${ub(s,r)});\n }\n `}const i=zy();if(t)return`\n vec4 ${a}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `;const u=o[0],l=o[1],c=Math.ceil(n[2]/2),d=c*Math.ceil(n[1]/2);return`\n vec4 ${a}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${u}, ${l}, ${d}, ${c}, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `}(e,t);default:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=zy();if(t)return`\n vec4 ${r}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${n}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${a.texture2D}(${n}, uv);\n }\n `;const s=e.shapeInfo.logicalShape,o=s.length,i=e.shapeInfo.texShape,u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=u[0],c=u[1],d=Math.ceil(s[o-1]/2);let p=d*Math.ceil(s[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=s[o-m-1],f=`b${m} * ${p} + `+f;return`\n vec4 ${r}(${h}) {\n int index = ${f};\n int texR = index / ${c};\n int texC = index - texR * ${c};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\n return ${a.texture2D}(${n}, uv);\n }\n `}(e,t)}}const Zy="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Jy="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",eb="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",tb="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function nb(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function rb(e){return`offset${e}`}function ab(e){const t=e.name,n=c(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n for (int i = 0; i < ${n}; i++) {\n if (i == index) {\n return ${t}[i];\n }\n }\n `}function sb(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function ob(e,t,n){const{newShape:r,keptDims:a}=b(t),s=t.length,o=e&&3===s&&1===t[0],i=o?t.slice(1):r,u=!e&&s>1&&!d(t,n)&&r.length<s||o;return{useSqueezeShape:u,uniformShape:u?i:t,keptDims:a}}function ib(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function ub(e,t){return t.map(t=>e[t]).join(", ")}function lb(e,t,n,r){const a=n.map((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}}),s=a.map(e=>e.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=Xy(a,o,t),u=function(e,t){const n=$y(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(yy(e,()=>e.shaderSource(n,t)),yy(e,()=>e.compileShader(n)),V().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw wy(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,i),l=e.createProgram(u);return V().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(l),Object.assign({program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},cb(e,t,l)))}function cb(e,t,n){const r=[],a=[];let s,o,i,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===V().getNumber("WEBGL_VERSION")&&(u=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const d of t.variableNames){const a={name:d,uniform:e.getUniformLocation(n,d,c),offset:e.getUniformLocation(n,`offset${d}`,c)};t.enableShapeUniforms&&(a.shape=e.getUniformLocation(n,`${d}Shape`,c),a.texShape=e.getUniformLocation(n,`${d}TexShape`,c)),r.push(a)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(n,"outShape",c),i=e.getUniformLocation(n,"outShapeStrides",c),o=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const d of t.customUniforms)a.push(e.getUniformLocation(n,d.name,c));return{variablesLocations:r,customUniformLocations:a,infLoc:u,nanLoc:l,outShapeLocation:s,outShapeStridesLocation:i,outTexShapeLocation:o}}function db(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((e,n)=>{const r=e.logicalShape,a=t[n],s=a.shape;if(!d(r,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${s} must match`);if(e.isUniform&&a.isUniform)return;const o=e.texShape,i=a.isUniform?null:a.texData.texShape;if(!d(o,i))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${i} must match`)})}function pb(e){return V().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class hb{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=iy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=zy();this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Gy(["r","c","d"],e):Uy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class fb{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=iy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=zy();this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Gy(["r","c","d"],e):Uy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class mb{constructor(e){this.variableNames=["A"],this.outTexUsage=ly.DOWNLOAD;const t=zy();this.outputShape=e,this.userCode=`\n ${qy}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class gb{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ly.DOWNLOAD;const t=zy();this.outputShape=e,this.userCode=`\n ${qy}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}const yb={R:0,G:1,B:2,A:3};class bb{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=zy();this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let s="";for(let o=0;o<n.length;o++){const e=n[o];s+=`\n if(offset == ${o}) {\n result = values[${yb[e]}];\n }`}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":jy(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${n.length});\n\n flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${r.texture2D}(A, uv);\n ${s}\n }\n ${r.output} = vec4(${a}, 0., 0., 0.);\n }\n `}}class xb{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=zy();this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length);let r="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let t=0;t<=1;t++){const a=2*s+t;r+=`\n localCoords = coords;\n if(localCoords[2] + ${t} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${t};\n if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${s};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${a}] = values[0];\n } else if (offset == 1) {\n result[${a}] = values[1];\n } else if (offset == 2) {\n result[${a}] = values[2];\n } else {\n result[${a}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":jy(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${r}\n\n ${n.output} = ${a};\n }\n `}}function vb(e){const t=zy();return function(e,t){const n=$y(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(yy(e,()=>e.shaderSource(n,t)),yy(e,()=>e.compileShader(n)),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}function wb(e){return function(e,t){const n=$y(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return yy(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),yy(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function kb(e){return function(e,t){const n=$y(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return yy(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),yy(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}(e,new Uint16Array([0,1,2,2,1,3]))}function Ib(e,t,n,r,a,s){!function(e,t){const n=V().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const o=function(e){return $y(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return yy(e,()=>e.bindTexture(i,o)),yy(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),yy(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),yy(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),yy(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),1===V().getNumber("WEBGL_VERSION")?yy(e,()=>e.texImage2D(i,0,r,t,n,0,a,s,null)):yy(e,()=>e.texStorage2D(i,1,r,t,n)),yy(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:o,texShape:[n,t]}}function Nb(e){return e.internalFormatFloat}function Sb(e){return e.internalFormatHalfFloat}function Tb(e){return e.downloadTextureFormat}function Cb(e){return e.internalFormatPackedFloat}function $b(e){return e.internalFormatPackedHalfFloat}function Eb(e,t,n,r,a,s,o,i){const u=e,l=new Float32Array(function(e,t){const[n,r]=my(e,t);return n*r*4}(s,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}class Rb{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=V().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){ay[e]=t}(t,e)):this.gl=oy(t),e=this.gl,2===V().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>yy(t,()=>t.createVertexArray()),this.bindVertexArray=e=>yy(t,()=>t.bindVertexArray(e)),this.deleteVertexArray=e=>yy(t,()=>t.deleteVertexArray(e)),this.getVertexArray=()=>yy(t,()=>t.getParameter(t.VERTEX_ARRAY_BINDING))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>yy(e,()=>t.createVertexArrayOES()),this.bindVertexArray=n=>yy(e,()=>t.bindVertexArrayOES(n)),this.deleteVertexArray=n=>yy(e,()=>t.deleteVertexArrayOES(n)),this.getVertexArray=()=>yy(e,()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===V().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=xy(this.gl,e),My(this.gl,t))this.textureHalfFloatExtension=xy(this.gl,t);else if(V().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),My(this.gl,r))this.colorBufferHalfFloatExtension=xy(this.gl,r);else if(V().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",My(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!My(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=wb(this.gl),this.indexBuffer=kb(this.gl),this.framebuffer=function(e){return $y(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=gy(this.gl,this.textureHalfFloatExtension)}get debug(){return V().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;yy(e,()=>e.finish()),yy(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),yy(e,()=>e.deleteFramebuffer(this.framebuffer)),yy(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),yy(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),yy(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=hy(t,n);return Ib(e,a,s,Nb(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=hy(t,n);return Ib(e,a,s,Sb(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=hy(t,n);return Ib(e,a,s,Tb(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){yy(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?2===V().getNumber("WEBGL_VERSION")?yy(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):yy(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):2===V().getNumber("WEBGL_VERSION")?yy(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):yy(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),yy(e,()=>e.bindTexture(e.TEXTURE_2D,null))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),function(e,t,n,r,a,s){let o,i,u;yy(e,()=>e.bindTexture(e.TEXTURE_2D,t)),a instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,u=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,u=s.internalFormatPackedFloat),o.set(a),2===V().getNumber("WEBGL_VERSION")?yy(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)):yy(e,()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o)),yy(e,()=>e.bindTexture(e.TEXTURE_2D,null))}(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=my(t,n);return Ib(e,a,s,$b(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=my(t,n);return Ib(e,a,s,Cb(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ty(this.gl,this.framebuffer),this.outputTexture=null),yy(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>function(e,t,n,r){const[a,s]=hy(t,n),o=new Uint8Array(t*n*4);return yy(e,()=>e.readPixels(0,0,a,s,r.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return Eb(this.gl,e,0,0,0,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n){const r=e.createBuffer();yy(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));const a=16*t*n;return yy(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),yy(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),yy(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(V().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>function(e,t,n){const r=new Float32Array(t*n*4);return yy(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=vb(t));const n=function(e){return $y(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}(t);yy(t,()=>t.attachShader(n,this.vertexShader)),yy(t,()=>t.attachShader(n,e)),function(e,t){if(yy(e,()=>e.linkProgram(t)),!V().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,n);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&ky(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;yy(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),function(e,t,n){yy(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Iy(e,t,"clipSpacePos",n,3,20,0)&&Iy(e,t,"uv",n,2,20,12)}(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(yy(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&ky(this.gl,this.program),yy(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return $y(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),yy(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),function(e,t,n,r){yy(e,()=>Ny(e,t,r)),yy(e,()=>e.uniform1i(n,r))}(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=my(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&ky(this.gl,this.program),Cy(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}yy(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),yy(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=xy(this.gl,2===V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await m(()=>this.disposed||this.isQueryAvailable(e,V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=function(e){let t=0;for(;t<e.length;++t){if(!e[t]())break}return t-1}(this.itemsToPoll.map(e=>e.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in V().platform&&(n=V().platform.setTimeoutCustom.bind(V().platform)),m(()=>(this.pollItems(),0===this.itemsToPoll.length),()=>0,null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Sy(this.gl,e,this.framebuffer),this.debug&&Cy(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Sy(this.gl,this.outputTexture,this.framebuffer),this.debug&&Cy(this.gl)):Ty(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;Sy(r,e,this.framebuffer),this.debug&&Cy(r),this.outputTexture=e,yy(r,()=>r.viewport(0,0,t,n)),yy(r,()=>r.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),yy(this.gl,()=>this.gl.scissor(e,t,n,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}function _b(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&i("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the CPU backend.`)})}function Ab(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}const Ob={kernelName:H,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;_b(t,"abs");let r=new Float32Array(c(t.shape));return r=Ab(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,t.dtype)}};function Fb(e){return(t,n,r,a,s)=>{const o=li(t,n),i=o.length,u=C(o),l=x(s,c(o)),d=t.length,p=n.length,h=C(t),f=C(n),m=ii(t,o),g=ii(n,o);if(m.length+g.length===0)for(let c=0;c<l.length;++c)l[c]=e(r[c%r.length],a[c%a.length]);else for(let c=0;c<l.length;++c){const t=D(c,i,u),n=t.slice(-d);m.forEach(e=>n[e]=0);const s=F(n,d,h),o=t.slice(-p);g.forEach(e=>o[e]=0);const y=F(o,p,f);l[c]=e(r[s],a[y])}return[l,o]}}function Db(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,i=n.makeTensorInfo(r.shape,"complex64");return n.data.get(i.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",s),imag:n.makeTensorInfo(a.shape,"float32",o)},i}const Mb={kernelName:ye,backendName:"cpu",kernelFunc:Db};function Pb(e,t,n="float32"){if("complex64"===n){return Db({inputs:{real:Pb(e,t,"float32"),imag:Pb(e,t,"float32")},backend:e})}const r=_(c(t),n);return e.makeTensorInfo(t,n,r)}function Lb(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const Bb={kernelName:ot,backendName:"cpu",kernelFunc:Lb};function Vb(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.real,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}const Wb={kernelName:Jt,backendName:"cpu",kernelFunc:Vb};function zb(e,t,n,r){if("int32"===r){return[t,"int32",Int32Array.from(e)]}if("bool"===r){const r=Or([0],n),[a,s]=Fb((e,t)=>e!==t?1:0)(t,[],e,r,"bool");return[s,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${r}`)}function Ub(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return Lb({inputs:{x:a},backend:n});const e=Pb(n,a.shape,a.dtype),t=Ub({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=Db({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=Vb({inputs:{input:a},backend:n}),t=Ub({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!w(a.dtype,s)){const e=Lb({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}const o=n.data.get(a.dataId).values,[i,u,l]=zb(o,a.shape,a.dtype,s);return n.makeTensorInfo(i,u,l)}const Gb={kernelName:fe,backendName:"cpu",kernelFunc:Ub};function Hb(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;_b([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c="string"===s.dtype?Eh(u):u,d="string"===s.dtype?Eh(l):l,p=r||s.dtype,[h,f]=t(s.shape,o.shape,c,d,p);return i.makeTensorInfo(f,p,h)}:({inputs:e,backend:a})=>{const{a:s,b:o}=e,i=a;if("complex64"===s.dtype||"complex64"===o.dtype){const e=Ub({inputs:{x:s},backend:i,attrs:{dtype:"complex64"}}),t=i.data.get(e.dataId),r=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,u=i.data.get(r.dataId).values,l=i.data.get(a.dataId).values,c=Ub({inputs:{x:o},backend:i,attrs:{dtype:"complex64"}}),d=i.data.get(c.dataId),p=d.complexTensorInfos.real,h=d.complexTensorInfos.imag,f=i.data.get(p.dataId).values,m=i.data.get(h.dataId).values,[g,y,b]=n(s.shape,o.shape,u,l,f,m),x=i.makeTensorInfo(b,"float32",g),v=i.makeTensorInfo(b,"float32",y),w=Db({inputs:{real:x,imag:v},backend:i});return i.disposeIntermediateTensorInfo(e),i.disposeIntermediateTensorInfo(c),i.disposeIntermediateTensorInfo(x),i.disposeIntermediateTensorInfo(v),w}{const e=i.data.get(s.dataId).values,n=i.data.get(o.dataId).values,a=r||s.dtype,[u,l]=t(s.shape,o.shape,e,n,a);return i.makeTensorInfo(l,a,u)}}}function jb(e){return(t,n,r,a,s,o)=>{const i=li(t,n),u=c(i),l=i.length,d=C(i),p=x("float32",u),h=x("float32",u),f=ii(t,i),m=ii(n,i),g=Jp(r,a),y=Jp(s,o),b=t.length,v=C(t),w=n.length,k=C(n);if(f.length+m.length===0)for(let c=0;c<p.length;c++){const t=c%g.length,n=c%y.length,r=e(g[2*t],g[2*t+1],y[2*n],y[2*n+1]);p[c]=r.real,h[c]=r.imag}else for(let c=0;c<p.length;c++){const t=D(c,l,d),n=t.slice(-b);f.forEach(e=>n[e]=0);const r=F(n,b,v),a=t.slice(-w);m.forEach(e=>a[e]=0);const s=F(a,w,k),o=e(g[2*r],g[2*r+1],y[2*s],y[2*s+1]);p[c]=o.real,h[c]=o.imag}return[p,h,i]}}const qb=Fb((e,t)=>e+t),Kb=jb((e,t,n,r)=>({real:e+n,imag:t+r})),Xb=Hb(K,qb,Kb),Yb={kernelName:K,backendName:"cpu",kernelFunc:Xb};function Qb(e,t,n,r,a){const s=c(r),o=_(a,n);for(let i=0;i<e.length;i++){const n=e[i];if(n<0)throw new Error("Input x must be non-negative!");n>=a||(o[n]+=s>0?t[i]:1)}return o}function Zb(e,t,n,r=!1){const a=e.shape[0],s=e.shape[1],o=Ps([a,n],t.dtype);for(let i=0;i<a;i++)for(let a=0;a<s;a++){const s=e.get(i,a);if(s<0)throw new Error("Input x must be non-negative!");s>=n||(r?o.set(1,i,s):t.size>0?o.set(o.get(i,s)+t.get(i,a),i,s):o.set(o.get(i,s)+1,i,s))}return o}const Jb=Fb((e,t)=>e&t),ex=Hb(pe,Jb),tx={kernelName:pe,backendName:"cpu",kernelFunc:ex};function nx(e){return(t,n,r)=>{const a=v(n,t.length);for(let s=0;s<t.length;++s)a[s]=e(t[s],r);return a}}function rx(e,t,n){return ax(e,nx(t),n)}function ax(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;_b(o,e);const i=s,u=i.data.get(o.dataId).values;let l;if("string"===o.dtype){if(!Array.isArray(u))throw new Error("String tensor's value was not an instance of Array");l=Eh(u)}else l=u;const c=n||o.dtype,d=t(l,c,a);return i.makeTensorInfo(o.shape,c,d)}}const sx=nx(e=>Math.ceil(e)),ox=ax(me,sx),ix={kernelName:me,backendName:"cpu",kernelFunc:ox};function ux(e,t,n,r){const a=v(n,c(t));if(r&&"string"!==n){let t=0;e.forEach(e=>{const n=c(e.shape);a.set(e.vals,t),t+=n})}else{let r=0;e.forEach(e=>{const s="string"===n?Eh(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const i=n*t[1]+r;for(let t=0;t<e.shape[1];++t)a[i+t]=s[o++]}r+=e.shape[1]})}return a}const lx=Fb((e,t)=>e===t?1:0),cx=Hb(je,lx,null,"bool"),dx={kernelName:je,backendName:"cpu",kernelFunc:cx},px=nx(e=>Math.exp(e)),hx=ax(qe,px,"float32"),fx={kernelName:qe,backendName:"cpu",kernelFunc:hx},mx=nx(e=>Math.expm1(e)),gx=ax(Xe,mx),yx={kernelName:Xe,backendName:"cpu",kernelFunc:gx},bx=nx(e=>Math.floor(e)),xx=ax(Je,bx),vx={kernelName:Je,backendName:"cpu",kernelFunc:xx},wx=Fb((e,t)=>Math.floor(e/t)),kx=Hb(et,wx,null,"int32"),Ix={kernelName:et,backendName:"cpu",kernelFunc:kx};function Nx(e,t,n,r,a,s,o,i,u){const l=Ps([r,s],n);for(let c=0;c<r;c++){const n=[];let r=0;for(let t=0;t<a;t++){const s=e[c*a+t];r+=s*o[t],n.push(s)}if(r<0||r>=u/s)throw new Error(`Invalid indices: ${n} does not index into ${i}`);for(let e=0;e<s;e++)l.values[c*s+e]=t.get(...t.indexToLoc(r*s+e))}return l}function Sx(e,t,n){const r=Ps(n,e.dtype);for(let a=0;a<r.size;++a){const n=r.indexToLoc(a).slice(),s=n[0],o=n[2],i=t.locToIndex([s,o]);n[2]=t.values[i];const u=e.locToIndex(n);0<=u&&u<e.values.length&&(r.values[a]=e.values[u])}return r}const Tx=Fb((e,t)=>e>t?1:0),Cx=Hb(at,Tx,null,"bool"),$x={kernelName:at,backendName:"cpu",kernelFunc:Cx},Ex=Fb((e,t)=>e>=t?1:0),Rx=Hb(st,Ex,null,"bool"),_x={kernelName:st,backendName:"cpu",kernelFunc:Rx},Ax=Fb((e,t)=>e<t?1:0),Ox=Hb(ht,Ax,null,"bool"),Fx={kernelName:ht,backendName:"cpu",kernelFunc:Ox},Dx=Fb((e,t)=>e<=t?1:0),Mx=Hb(ft,Dx,null,"bool"),Px={kernelName:ft,backendName:"cpu",kernelFunc:Mx};function Lx(e,t,n){const r=(t-e)/(n-1),a=_(n,"float32");a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+r;return a}const Bx=nx(e=>Math.log(e)),Vx=ax(gt,Bx),Wx={kernelName:gt,backendName:"cpu",kernelFunc:Vx};function zx(e,t,n,r){const a=x(r,c(n));for(let s=0;s<a.length;++s){const n=s*t;let r=e[n];for(let a=0;a<t;++a){const t=e[n+a];(Number.isNaN(t)||t>r)&&(r=t)}a[s]=r}return a}const Ux=Fb((e,t)=>Math.max(e,t)),Gx=Hb(Nt,Ux),Hx={kernelName:Nt,backendName:"cpu",kernelFunc:Gx},jx=Fb((e,t)=>Math.min(e,t)),qx=Hb(At,jx),Kx={kernelName:At,backendName:"cpu",kernelFunc:qx},Xx=Fb((e,t)=>e*t),Yx=jb((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n})),Qx=Hb(Mt,Xx,Yx),Zx={kernelName:Mt,backendName:"cpu",kernelFunc:Qx};function Jx(e,t,n){const r=Ar(-1,n);return Xx([],t,r,e,n)}const ev={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;_b(r,"neg");const a=n.data.get(r.dataId).values,[s,o]=Jx(a,r.shape,r.dtype);return n.makeTensorInfo(o,r.dtype,s)}},tv=Fb((e,t)=>e!==t?1:0),nv=Hb(Lt,tv,null,"bool"),rv={kernelName:Lt,backendName:"cpu",kernelFunc:nv};function av(e,t,n,r,a){const s=t.length,o=c(t),i=C(t),u=C(a),l=x(n,c(a));for(let c=0;c<o;++c){const t=D(c,s,i),n=new Array(t.length);for(let e=0;e<n.length;e++)n[e]=t[r[e]];l[F(n,s,u)]=e[c]}return l}function sv(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;_b(a,"transpose");const o=a.shape.length,i=new Array(o);for(let l=0;l<i.length;l++)i[l]=a.shape[s[l]];const u=av(r.data.get(a.dataId).values,a.shape,a.dtype,s,i);return{dataId:r.write(u,i,a.dtype),shape:i,dtype:a.dtype}}const ov={kernelName:jn,backendName:"cpu",kernelFunc:sv};function iv(e,t,n,r){const[a,s]=wi(e,r),o=ca(t,"int32"),i=_(c(a),o),u=c(s);for(let l=0;l<i.length;++l){const e=l*u;let t=1;for(let r=0;r<u;++r)t*=n[e+r];i[l]=t}return{outVals:i,outShape:a,outDtype:o}}const uv={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;_b(a,"prod");const i=a.shape.length,u=y(s,a.shape),l=Ni(u,i);let c=u,d=a;const p=[];null!=l&&(d=sv({inputs:{x:a},backend:n,attrs:{perm:l}}),p.push(d),c=Ti(c.length,i));const h=n.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=iv(d.shape,d.dtype,h,c);let b=m;return o&&(b=ki(m,u)),p.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(b,g,f)}};function lv(e,t,n,r){const a=[];let s=0;const o=t.length-1+n.length,i=new Array(o).fill(null).map(()=>[0]);!function(e,t){for(let n=0;n<e.length;++n){const r=e[n],a=n===e.length-1?t:e[n+1].length;if(0===r.length)throw new Error("Ragged splits may not be empty");if(r[0]<0)throw new Error("Ragged splits must be non-negative");if(r[r.length-1]>a)throw new Error("Ragged splits must not point past values");for(let e=1;e<r.length;++e)if(r[e-1]>r[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,r);let u=1;for(let l=0;l<t.length-1;++l){u*=t[l];const e=t[l+1];for(let t=1;t<u+1;++t)i[l].push(t*e)}for(let l=0;l<e.length;++l){let r=e[l],o=e[l]+1;for(let e=0;e<n.length;++e){const a=n[e],s=e+t.length-1;if(s>=0){const e=i[s],t=e[e.length-1]-a[r];for(let n=r;n<o;++n)i[s].push(a[n+1]+t)}r=a[r],o=a[o]}o!==r&&(a.push([r,o]),s+=o-r)}return{outSplits:i,valueSlices:a,numValues:s}}function cv(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let r=t;r<e.length;r++)n[t-1]*=e[r];return n}function dv(e,t,n,r,a){const s=t.slice();s[0]=a;const o=v(n,c(s)),i=e.length;return function(e,t,n,r,a,s){const o=cv(t,2)[1],i=cv(s,2)[1];let u=0;for(const l of n)for(let t=l[0];t<l[1];++t){for(let n=0;n<r;++n)a[u*i+n]=e[t*o+n];++u}}(e,t,r,0===i?0:i/t[0],o,s),[o,s]}function pv(e,t,n,r,a,s,o,i){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach((e,r)=>{if(e<0||e>=n){const a=D(r,t.length,C(t)).join(",");throw new Error(`indices[${a}] = ${e} is not in [0, ${n})`)}})}(s,o,t[0][0]-1),0===r.length)throw new Error("params.rank must be nonzero");const u=r[0],{outSplits:l,valueSlices:c,numValues:d}=lv(s,o,e,u),p=function(e){const t=[];for(let n=0;n<e.length;++n){const r=v("int32",e[n].length);t.push(r),e[n].forEach((e,t)=>r[t]=e)}return t}(l),h=dv(n,r,a,c,d);return[p,h[0],h[1]]}const hv=2147483647;function fv(e,t,n,r,a,s,o){if(t.length>1)throw new Error("starts must be a scalar or vector");if(a.length>1)throw new Error("limits must be a scalar or vector");if(o.length>1)throw new Error("deltas must be a scalar or vector");const i=0===t.length,u=0===a.length,l=0===o.length,c=[];i||c.push(t[0]),u||c.push(a[0]),l||c.push(o[0]);for(let m=1;m<c.length;++m)if(c[m]!==c[m-1])throw new Error("starts, limits, and deltas must have the same shape");const d=0===c.length?1:c[0],p=v("int32",d+1);p[0]=0;for(let m=0;m<d;++m){const t=i?e[0]:e[m],n=u?r[0]:r[m],a=l?s[0]:s[m];if(0===a)throw new Error("Requires delta != 0");let o;if(a>0&&n<t||a<0&&n>t)o=0;else if(o=Math.ceil(Math.abs((n-t)/a)),o>hv)throw new Error("Requires ((limit - start) / delta) <= 2147483647");p[m+1]=p[m]+o}const h=v(n,p[d]);let f=0;for(let m=0;m<d;++m){const t=p[m+1]-p[m];let n=i?e[0]:e[m];const r=l?s[0]:s[m];for(let e=0;e<t;++e)h[f++]=n,n+=r}return[p,h]}var mv=Ap;class gv{constructor(e,t,n,r,a,s,o,i,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=a,this.defaultValue=s,this.defaultValueShape=o,this.rowPartitionValues=i,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=Dp(l),this.raggedRank=Mp(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===mv.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===mv.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case mv.VALUE_ROWIDS:return gv.getMaxWidthValueRowID(t);case mv.ROW_SPLITS:return gv.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${mv[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let r=0;r<t-1;++r){const t=e[r+1]-e[r];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,r=e[0],a=0;for(let s=1;s<t;++s){const t=e[s];t!==r&&(r=t,a=Math.max(s-n,a),n=s)}return Math.max(t-n,a)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return bv(e,n)}calculateOutputSize(e){const t=this.valuesShape;Pp(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=Fp(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let a=1;a<=this.raggedRank;++a)r[a]<0&&(r[a]=this.getMaxWidth(a));return r}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),a=[];let s=0;for(let o=0;o<r;++o,s+=t)a.push(s);for(let o=r;o<e;++o)a.push(-1);return i(a.length===e,()=>"Final length of result must be equal to firstDimension."),a}calculateOutputIndexRowSplit(e,t,n,r){const a=e.length,s=[];for(let o=0;o<a-1;++o){const a=e[o+1]-e[o];let i=Math.min(r,a),u=t[o];-1===u&&(i=0);for(let e=0;e<i;++e)s.push(u),u+=n;for(let e=0;e<a-i;++e)s.push(-1)}if(a>0&&s.length!==e[a-1])throw new Error("Invalid row split size.");return s}calculateOutputIndexValueRowID(e,t,n,r){const a=e.length,s=[];if(0===a)return[];let o=0,i=e[0];if(i>=t.length)throw new Error(`Got currentValueRowId=${i}, which is not less than ${t.length}`);let u=t[i];s.push(u);for(let l=1;l<a;++l){const a=e[l];if(a===i)u>=0&&(++o,o<r?u+=n:u=-1);else{if(o=0,i=a,a>=t.length)throw new Error(`Got nextValueRowId=${a} which is not less than ${t.length}`);u=t[a]}s.push(u)}if(s.length!==e.length)throw new Error("Invalid row ids.");return s}calculateOutputIndex(e,t,n,r){const a=this.getRowPartitionTensor(e),s=this.getRowPartitionTypeByDimension(e);switch(s){case mv.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case mv.ROW_SPLITS:if(a.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${a.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(a,t,n,r);default:throw new Error(`Unsupported partition type: ${mv[s]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case mv.FIRST_DIM_SIZE:return e[0];case mv.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case mv.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${mv[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let s=n.length-2;s>=0;--s)n[s]=n[s+1]*t[s+1];const r=bv(t,!1),a=v(this.valuesDType,c(r));if(n[0]*t[0]>0){let s=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e){s=this.calculateOutputIndex(e-1,s,n[e],t[e])}this.setOutput(this.raggedRank,s,a,r)}return[r,a]}setOutput(e,t,n,r){if(0===n.length)return;const a=this.values,s=n;let o=r.slice();o=o.slice(e+1);const i=c(o),u=t.length;let l=this.defaultValue;if(l.length!==i&&1!==l.length){const e=this.defaultValueShape;Ba(()=>{const t=vo(l,e),n=Po(t,o);l=n.dataSync()})}let d=0,p=0,h=0;for(let c=0;c<=u;++c){let e=c<u?t[c]:-1;if(e!==h){if(p<h){const e=a.subarray(d*i);yv(s.subarray(p*i),e,(h-p)*i)}if(c>=u){const t=n.length;e=Math.floor(t/i)}if(e>h)if(1===this.defaultValue.length)s.subarray(h*i,e*i).fill(this.defaultValue[0]),h=e;else for(;e>h;){yv(s.slice(h*i),l,i),++h}e<0?(d=c+1,p=h):(d=c,p=h,h=p+1)}else++h}}}function yv(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function bv(e,t){const n=[];for(let r of e){if(r<0){if(!t)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}n.push(r)}return n}function xv(e,t,n,r,a,s,o,i,u,l){return new gv(e,t,n,r,a,s,o,i,u,l).compute()}function vv(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return _(0,r);const a=_(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+n;return a}const wv=nx(e=>1/Math.sqrt(e)),kv=ax(dn,wv),Iv={kernelName:dn,backendName:"cpu",kernelFunc:kv};function Nv(e,t,n,r,a,s,o,i,u,l){const c=[r/a,a],d=e.values,p=t.values;if(0===r)return Ps(n,t.dtype);const h=u instanceof qr?u:Ps(c,t.dtype);"string"===typeof u||"number"===typeof u?h.values.fill(u):"boolean"===typeof u&&h.values.fill(+u);for(let f=0;f<s;f++){const e=[];let s=0;for(let t=0;t<o;t++){const n=d[f*o+t];e.push(n),s+=n*i[t]}if(s<0||s>=r/a)throw new Error(`Invalid indices: ${e} does not index into ${n}`);for(let n=0;n<a;n++)l?h.values[s*a+n]+=p[f*a+n]:h.values[s*a+n]=0===t.rank?p[0]:p[f*a+n]}return h}const Sv=nx(e=>1/(1+Math.exp(-e))),Tv=rx(wn,e=>1/(1+Math.exp(-e))),Cv={kernelName:wn,backendName:"cpu",kernelFunc:Tv};function $v(e,t,n,r,a){const s=Ip(r,t,n),o=c(n),i=C(r);if(s){const n=Np(t,i);return"string"===a?e.slice(n,n+o):e.subarray(n,n+o)}const u=Ps(r,a,"string"===a?Eh(e):e),l=Ps(n,a);for(let c=0;c<l.size;++c){const e=l.indexToLoc(c),n=e.map((e,n)=>e+t[n]);l.set(u.get(...n),...e)}return"string"===a?Rh(l.values):l.values}function Ev(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;_b(a,"slice");const[i,u]=Sp(a,s,o);wp(a,i,u);const l=$v(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const Rv={kernelName:yn,backendName:"cpu",kernelFunc:Ev};function _v(e,t,n,r,a,s,o){const i=t[0],u=s[0],l=new Array(u),c=new Array(i),d=t[1];if(0===u){if(0!==i)throw new Error(gh(i));return[v(n,0),[0,d],v(a,0),l,c]}let p=!0,h=0;const f=new Array(u).fill(0);for(let g=0;g<i;++g){const t=e[g*d];if(t<0)throw new Error(yh(g,t));if(t>=u)throw new Error(bh(g,t,u));++f[t],p=p&&t>=h,h=t}let m=!0;for(let g=0;g<u;++g){const e=0===f[g];l[g]=e,m=m&&!e,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){const t=e,n=r;for(let e=0;e<i;++e)c[e]=e;return[t,[i,d],n,l,c]}{const t=f[u-1],s=v(n,t*d),p=v(a,t),h=new Array(u).fill(0);for(let n=0;n<i;++n){const t=e[n*d],a=h[t],o=(0===t?0:f[t-1])+a;h[t]++;for(let r=0;r<d;++r)s[o*d+r]=e[n*d+r];p[o]=r[n],c[n]=o}for(let e=0;e<u;++e){if(0===h[e]){const t=0===e?0:f[e-1];s[t*d+0]=e;for(let e=1;e<d;++e)s[t*d+e]=0;p[t]=o}}return[s,[t,d],p,l,c]}}function Av(e,t,n,r,a){const s=c(r),o=t[0],i=a.length,u=[];let l=1,d=-1;for(let c=0;c<i;++c){const e=a[c];if(-1===e){if(-1!==d)throw new Error(xh(d,c));d=c,u.push(1)}else{if(e<0)throw new Error(vh(c,e));l*=e,u.push(e)}}if(-1!==d){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(s/l);if(l*e!==s)throw new Error(kh(r,u));u[d]=e}if(c(u)!==s)throw new Error(Ih(r,u));const p=r.length,h=[];if(p>0){h[p-1]=1;for(let e=p-2;e>=0;--e)h[e]=h[e+1]*r[e+1]}const f=[];if(i>0){f[i-1]=1;for(let e=i-2;e>=0;--e)f[e]=f[e+1]*u[e+1]}const m=v(n,o*i);for(let c=0;c<o;++c){let t=0;for(let n=0;n<p;++n)t+=e[c*p+n]*h[n];for(let e=0;e<i;++e)m[c*i+e]=Math.trunc(t/f[e]),t%=f[e]}return[m,[o,i],u]}function Ov(e,t,n,r,a,s=!1,o=0){const i=r.length,u=[t[0],e.length/t[0]],l=u[1],c=i>0?a[i-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const d=t.slice();d[0]=c;const p=v(n,d.reduce((e,t)=>e*t,1));if(0===i)return c>0&&p.fill(o),[p,d];if(c<=0)throw new Error("segment ids must be >= 0");let h=0,f=1,m=0,g=a[h];for(;;){let t=0;if(f<i){if(t=a[f],g===t){++f;continue}if(g>=t)throw new Error(Sh())}if(g<0||g>=c)throw new Error(Th(g,c));g>m&&p.fill(o,m*l,g*l);for(let n=h;n<f;++n){const t=r[n];if(t<0||t>=u[0])throw new Error(Ch(n,r[n],u[0]));for(let n=0;n<l;n++)p[g*l+n]+=e[t*l+n]}if(s)for(let e=0;e<l;e++)p[g*l+e]/=f-h;if(h=f,++f,m=g+1,g=t,f>i)break}return m<c&&p.fill(o,m*l,c*l),[p,d]}const Fv=nx(e=>Math.sqrt(e)),Dv=rx(In,e=>Math.sqrt(e)),Mv={kernelName:In,backendName:"cpu",kernelFunc:Dv},Pv=Fb((e,t)=>{const n=e-t;return n*n}),Lv=Hb(On,Pv),Bv={kernelName:On,backendName:"cpu",kernelFunc:Lv},Vv=nx((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:a}=t;return e.replace(new RegExp(n,r?"g":""),a)}),Wv=ax(Dn,Vv),zv={kernelName:Dn,backendName:"cpu",kernelFunc:Wv};function Uv(e,t,n,r){const a=Ps(e,t.dtype);for(let s=0;s<a.size;s++){const e=a.indexToLoc(s),o=new Array(e.length);for(let t=0;t<o.length;t++)o[t]=e[t]*n[t]+r[t];a.set(t.get(...o),...e)}return a}class Gv{constructor(e,t,n,r,a,s){this.separator=Dr(e),this.nGramWidths=t,this.leftPad=Dr(n),this.rightPad=Dr(r),this.padWidth=a,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,a,s){for(let o=0;o<a;++o){const i=this.getPadWidth(s),u=Math.max(0,i-o),l=Math.max(0,i-(a-(o+1))),c=s-(u+l),d=t+(u>0?0:o-i);let p=0;p+=u*this.leftPad.length;for(let t=0;t<c;++t)p+=e[d+t].length;p+=l*this.rightPad.length;p+=(u+l+c-1)*this.separator.length,n[r+o]=new Uint8Array(p);const h=n[r+o];let f=0;const m=e=>e.forEach(e=>h[f++]=e);for(let e=0;e<u;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[d+t]),m(this.separator);if(c>0){m(e[d+c-1]);for(let e=0;e<l;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<l-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,r=t.length;if(r>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let a=1;a<r;++a){let r=t[a]>=e;if(r=r&&t[a]<=n,!r)throw new Error(`Invalid split value ${t[a]}, must be in [${e}, ${n}]`);e=t[a]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const a=r-1,s=v("int32",r);if(0===n||0===r){const e=new Array(n);for(let t=0;t<=a;++t)s[t]=0;return[e,s]}s[0]=0;for(let i=1;i<=a;++i){const e=t[i]-t[i-1];let n=0;this.nGramWidths.forEach(t=>{n+=this.getNumNGrams(e,t)}),this.preserveShort&&e>0&&0===n&&(n=1),s[i]=s[i-1]+n}const o=new Array(s[a]);for(let i=0;i<a;++i){const n=t[i];let r=s[i];if(this.nGramWidths.forEach(a=>{const s=t[i+1]-t[i],u=this.getNumNGrams(s,a);this.createNGrams(e,n,o,r,u,a),r+=u}),this.preserveShort&&r===s[i]){const a=t[i+1]-t[i];if(0===a)continue;const s=a+2*this.padWidth,u=1;this.createNGrams(e,n,o,r,u,s)}}return[o,s]}}function Hv(e,t,n,r,a,s,o,i){return new Gv(n,r,a,s,o,i).compute(e,t)}function jv(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)r.push(e.subarray(t,t+1));return}if(1===t.length){const a=t[0];let s=e.indexOf(a);for(;-1!==s;){const t=e.subarray(0,s);n&&0===t.length||r.push(t),s=(e=e.subarray(s+1)).indexOf(a)}return void(n&&0===e.length||r.push(e))}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||-1!==t.indexOf(e[s])){const t=e.subarray(a,s);n&&0===t.length||r.push(t),a=s+1}}function qv(e,t,n){const r=e.length,a=[];let s=0,o=0;const i=new Array(r);for(let p=0;p<r;++p){const r=a.length;jv(e[p],t,n,a);const u=a.length-r;i[p]=u,s+=u,o=Math.max(o,u)}const u=v("int32",2*s),l=new Array(s),c=[r,o];let d=0;for(let p=0;p<r;++p)for(let e=0;e<i[p];++e)u[2*d]=p,u[2*d+1]=e,l[d]=a[d],++d;return[u,l,c]}function Kv(e,t){const n=v("int32",e.length);for(let r=0;r<e.length;++r)n[r]=_r(e[r]).modulo(t).getLowBitsUnsigned();return n}const Xv=Fb((e,t)=>e-t),Yv=jb((e,t,n,r)=>({real:e-n,imag:t-r})),Qv=Hb(Vn,Xv,Yv),Zv={kernelName:Vn,backendName:"cpu",kernelFunc:Qv};function Jv(e,t){const n=new Array(e.rank);for(let a=0;a<n.length;a++)n[a]=e.shape[a]*t[a];const r=Ps(n,e.dtype);for(let a=0;a<r.values.length;++a){const t=r.indexToLoc(a),n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=t[r]%e.shape[r];const s=e.locToIndex(n);r.values[a]=e.values[s]}return r}const ew=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function tw(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const a=r-n+1,s=t-n+1,o=Math.log(a),i=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*i*(a-i)/a)*Math.sign(s-a/2);tw(e,t,Math.max(n,Math.floor(t-s*i/a+u)),Math.min(r,Math.floor(t+(a-s)*i/a+u)))}const a=e[t];let s=n,i=r;for(o(e,n,t),ew(e[r],a)>0&&o(e,n,r);s<i;){for(o(e,s,i),s++,i--;ew(e[s],a)<0;)s+=1;for(;ew(e[i],a)>0;)i-=1}0===ew(e[n],a)?o(e,n,i):(i+=1,o(e,i,r)),i<=t&&(n=i+1),t<=i&&(r=i-1)}}function nw(e,t,n,r,a){const s=t[t.length-1],[o,i]=[e.length/s,s],u=x(n,o*r),l=x("int32",o*r);for(let d=0;d<o;d++){const t=d*i,n=e.subarray(t,t+i);let s=new Array(n.length);n.forEach((e,t)=>s[t]={value:e,index:t}),r<s.length&&(tw(s,r),s=s.slice(0,r)),a&&s.sort(ew);const o=d*r,c=u.subarray(o,o+r),p=l.subarray(o,o+r);for(let e=0;e<r;e++)c[e]=s[e].value,p[e]=s[e].index}const c=t.slice();return c[c.length-1]=r,[Ps(c,n,u),Ps(c,"int32",l)]}function rw(e,t,n,r){const a=y(t,n)[0],s=[1,n[0],1];for(let f=0;f<a;f++)s[0]*=n[f];s[1]=n[a];for(let f=a+1;f<n.length;f++)s[2]*=n[f];const o=new Map,i=new Int32Array(n[a]),u=new qr(s,r,e),l=[],c=1===s[0]&&1===s[2];for(let f=0;f<n[a];f++){let t;if(c)t=e[f].toString();else{const e=[];for(let t=0;t<s[0];t++)for(let n=0;n<s[2];n++)e.push(u.get(t,f,n));t=e.join(",")}const n=o.get(t);if(null!=n)i[f]=n;else{const e=o.size;o.set(t,e),i[f]=e,l.push(f)}}const d=s.slice();d[1]=o.size;const p=new qr(d,r);l.forEach((e,t)=>{for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)p.set(u.get(n,e,r),n,t,r)});const h=n.slice();return h[a]=d[1],{outputValues:p.values,outputShape:h,indices:i}}const aw=Object.freeze(Object.defineProperty({__proto__:null,addImpl:qb,bincountImpl:Qb,bincountReduceImpl:Zb,bitwiseAndImpl:Jb,castImpl:zb,ceilImpl:sx,concatImpl:ux,equalImpl:lx,expImpl:px,expm1Impl:mx,floorDivImpl:wx,floorImpl:bx,gatherNdImpl:Nx,gatherV2Impl:Sx,greaterEqualImpl:Ex,greaterImpl:Tx,lessEqualImpl:Dx,lessImpl:Ax,linSpaceImpl:Lx,logImpl:Bx,maxImpl:zx,maximumImpl:Ux,minimumImpl:jx,multiplyImpl:Xx,negImpl:Jx,notEqualImpl:tv,prodImpl:iv,raggedGatherImpl:pv,raggedRangeImpl:fv,raggedTensorToTensorImpl:xv,rangeImpl:vv,rsqrtImpl:wv,scatterImpl:Nv,sigmoidImpl:Sv,simpleAbsImpl:Ab,sliceImpl:$v,sparseFillEmptyRowsImpl:_v,sparseReshapeImpl:Av,sparseSegmentReductionImpl:Ov,sqrtImpl:Fv,squaredDifferenceImpl:Pv,staticRegexReplaceImpl:Vv,stridedSliceImpl:Uv,stringNGramsImpl:Hv,stringSplitImpl:qv,stringToHashBucketFastImpl:Kv,subImpl:Xv,tileImpl:Jv,topKImpl:nw,transposeImpl:av,uniqueImpl:rw},Symbol.toStringTag,{value:"Module"})),{addImpl:sw,bincountImpl:ow,bincountReduceImpl:iw,bitwiseAndImpl:uw,castImpl:lw,ceilImpl:cw,concatImpl:dw,equalImpl:pw,expImpl:hw,expm1Impl:fw,floorImpl:mw,gatherNdImpl:gw,gatherV2Impl:yw,greaterImpl:bw,greaterEqualImpl:xw,lessImpl:vw,lessEqualImpl:ww,linSpaceImpl:kw,logImpl:Iw,maxImpl:Nw,maximumImpl:Sw,minimumImpl:Tw,multiplyImpl:Cw,negImpl:$w,notEqualImpl:Ew,prodImpl:Rw,raggedGatherImpl:_w,raggedRangeImpl:Aw,raggedTensorToTensorImpl:Ow,rangeImpl:Fw,rsqrtImpl:Dw,scatterImpl:Mw,sigmoidImpl:Pw,simpleAbsImpl:Lw,sliceImpl:Bw,sparseFillEmptyRowsImpl:Vw,sparseReshapeImpl:Ww,sparseSegmentReductionImpl:zw,sqrtImpl:Uw,staticRegexReplaceImpl:Gw,stridedSliceImpl:Hw,stringNGramsImpl:jw,stringSplitImpl:qw,stringToHashBucketFastImpl:Kw,subImpl:Xw,tileImpl:Yw,topKImpl:Qw,transposeImpl:Zw,uniqueImpl:Jw}=aw;function ek(e,t){return["x","y","z","w","u","v"].slice(0,t).map(t=>`${e}.${t}`)}function tk(e,t){return 1===t?[e]:ek(e,t)}class nk{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=pb(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=tk("rc",this.rank),t=sb(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),a=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${a}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let a=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t<this.rank;t++)a=`${e[e.length-1-t]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n int r = ${t[0]};\n int c = ${t[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${n};\n bool rEdge = rp1 >= ${r};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);if(1===this.rank){return`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`}return`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class rk{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length);let n="";for(let s=0;s<4;s++){let e="thisRC = rc;";s%2===1&&(e+="thisRC.z += 1;"),s>1&&(e+="thisRC.y += 1;"),n+=`\n ${e}\n ${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${s}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${s>0?"}":""}\n `}var r,a;this.userCode=`\n ${r=t,a=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${a?Hy(["r","c","d"],"inputShape"):Uy(["r","c","d"],r)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":jy(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class ak{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){const r=ok(t,n),a=ik(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=sk(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();const e=this.freeTextures[a].pop();return this.usedTextures[a].push(e),e}let o;return r===dy.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===dy.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===dy.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===dy.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===dy.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(o),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),o}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const a=ok(n,r),s=ik(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=sk(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=V().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==i&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const u=this.usedTextures[s],l=u&&u.indexOf(e);if(null==l||l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[l]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(const e in this.usedTextures)this.usedTextures[e].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function sk(e,t,n,r,a){const s=function(e,t){switch(e){case dy.PACKED_2X2_FLOAT32:return Cb(t);case dy.PACKED_2X2_FLOAT16:return $b(t);case dy.UNPACKED_FLOAT32:return Nb(t);case dy.UNPACKED_FLOAT16:return Sb(t);case dy.PACKED_4X1_UNSIGNED_BYTE:return Tb(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let o;if(a){const[t,n]=my(e[0],e[1]);o=t*n}else{const[t,n]=hy(e[0],e[1]);o=t*n}const i=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,s);return o*i}function ok(e,t){if(e===ly.UPLOAD)return dy.PACKED_2X2_FLOAT32;if(e===ly.RENDER||null==e)return function(e){return V().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?dy.PACKED_2X2_FLOAT32:dy.UNPACKED_FLOAT32:e?dy.PACKED_2X2_FLOAT16:dy.UNPACKED_FLOAT16}(t);if(e===ly.DOWNLOAD||e===ly.PIXELS)return dy.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function ik(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class uk{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const lk="if (isnan(x)) return x;",ck="return abs(x);",dk=lk+"\n return (x < 0.0) ? 0.0 : x;\n",pk=lk+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",hk="return x;";class fk{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class mk{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length);const t=e.length,n=tk("rc",t),r=sb(t),a=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),s=n.slice(-2),o=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 packedInput = getA(${a});\n\n setOutput(getChannel(packedInput, ${o}));\n }\n `}}const gk=wc,yk={};const bk=V().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class xk extends n{nextDataId(){return xk.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!V().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let n;if(null!=e){if(e instanceof Rb)n=e;else{const t=oy(V().getNumber("WEBGL_VERSION"),e);n=new Rb(t)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=oy(V().getNumber("WEBGL_VERSION"));n=new Rb(e),this.binaryCache=((r=V().getNumber("WEBGL_VERSION"))in yk||(yk[r]={}),yk[r]),this.gpgpuCreatedLocally=!0}var r;this.gpgpu=n,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new ak(this.gpgpu),this.numMBBeforeWarning=null==V().global.screen?1024:V().global.screen.height*V().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new t(this,La())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,a,s){const o=this.makeTensorInfo(t,n),i=this.texData.get(o.dataId);i.isPacked=!1,i.texture={texture:e,texShape:[r,a]},i.texShape=[r,a];const u=_y(t),l=new bb(u,!1,s),c=this.runWebGLProgram(l,[o],n,[[r,a]]);return c.shape=t,i.texture=null,this.disposeIntermediateTensorInfo(o),c.dataId}write(e,t,n){if((V().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||V().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:ly.UPLOAD,refCount:1}),r}refCount(e){if(this.texData.has(e)){return this.texData.get(e).refCount}return 0}incRef(e){this.texData.get(e).refCount++}decRef(e){if(this.texData.has(e)){this.texData.get(e).refCount--}}move(e,t,n,r,a){if(V().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:ly.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:a,slice:s,shape:o,isPacked:i}=t;if(null!=s){let t;t=i?new fk(o,hk):new uk(o,hk);const n=this.runWebGLProgram(t,[{dataId:e,shape:o,dtype:r}],r),a=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;if(u&&(l=Fr()),"complex64"===r){c=Jp(this.readSync(a.real.dataId),this.readSync(a.imag.dataId))}else c=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=Fr()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise(e=>t.push(e))}const t=this.texData.get(e),{values:n,shape:r,slice:a,dtype:s,complexTensorInfos:o,isPacked:i}=t;if(null!=a){let t;t=i?new fk(r,hk):new uk(r,hk);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(V().getBool("DEBUG")&&!V().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===V().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,d=null;if("complex64"!==s&&V().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);d=this.gpgpu.createBufferFromTexture(t.texture.texture,...fy(r))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);l=Jp(e[0],e[1])}else if(null==d)l=this.getValuesFromTexture(e);else{const e=c(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(d,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=d){const e=this.gpgpu.gl;yy(e,()=>e.deleteBuffer(d))}const p=this.convertAndCacheOnCPU(e,l),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach(e=>e(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&La().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:a,slice:s,dtype:o,isPacked:i,texture:u}=n;if("complex64"===o)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=s){let n;n=i?new fk(a,hk):new uk(a,hk);const r=this.runWebGLProgram(n,[{dataId:e,shape:a,dtype:o}],o),s=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),s}if(null==u)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),c=La().makeTensorFromTensorInfo(l),d=this.texData.get(l.dataId);return Object.assign({tensorRef:c},d.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map(e=>Mr(e));return Ps(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ps(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!by(n)){if(V().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),a=c(t);if(V().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...fy(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=V().getBool("WEBGL_PACK")&&!0===r,o=s?_y(t):t,i=s?new gb(o):new mb(o),u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),d}timerAvailable(){return V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=Lr(this.activeTimers.map(e=>e.query)).filter(e=>null!=e),s=Lr(this.activeTimers.map(e=>e.name)).filter(e=>null!=e);this.activeTimers=t,r&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o.kernelMs=function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}(e),o.getExtraProfileInfo=()=>e.map((e,t)=>({name:s[t],ms:e})).map(e=>`${e.name}: ${e.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Fr(),endMs:null}}endTimer(e){return V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Fr(),e)}async getQueryTime(e){if(V().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,u=this.dataRefCount.get(i);u>1?this.dataRefCount.set(i,u-1):(this.dataRefCount.delete(i),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,s)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=bk){return V().getBool("WEBGL_CPU_FORWARD")&&e.every(e=>null==this.texData.get(e.dataId).texture&&c(e.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){rr("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return gk(e.shape,t)}packedUnaryOp(e,t,n){const r=new fk(e.shape,t),a=this.compileAndRun(r,[e],n);return La().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=Lw(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(V().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ck,e.dtype);const t=new uk(e.shape,ck),n=this.compileAndRun(t,[e]);return La().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&I(n[0])){const a=n.map(e=>Dr(e));r=this.write(a,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return La().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new mk(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new nk(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[Ey(e.shape),...Ry(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[Ey(t),...Ry(t)],s=new rk(a,n),o=[n],i=this.runWebGLProgram(s,[r],e.dtype,o,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:a,dtype:s}=n;if(null!=t){i(c(a)<=t[0]*t[1]*4,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}const o=_y(a);let u;u=r?new fb(o):new hb(o);const l=[null!=t?t:fy(o)];return{dtype:s,shape:a,dataId:this.runWebGLProgram(u,[{shape:o,dtype:s,dataId:e}],s,l,!0,t).dataId}}runWebGLProgram(e,t,n,r,a=!1,s){const o=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(o.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===iy.DENSE){const t=null!=s?s:fy(e.outputShape);i.texShape=t.map(e=>2*e)}if(null!=e.outTexUsage&&(i.usage=e.outTexUsage),0===c(o.shape))return i.values=x(o.dtype,0),o;const u=[],l=t.map(t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&c(t.shape)<=V().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!==!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!Oy(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),u.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}});this.uploadToGPU(o.dataId);const p={shape:o.shape,texData:i,isUniform:!1},h=function(e,t,n){let r="";t.concat(n).forEach(t=>{const a=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const s=t.texData.texShape,{useSqueezeShape:o,uniformShape:i,keptDims:u}=ob(e.packedInputs,t.shape,s);let l="",p="",h="";if(1===i.length&&e.packedInputs){const e=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==i.length||e.packedInputs){if(i.length>2&&!e.packedInputs){const e=C(i);h=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}}else p=`${i[0]>1}_${i[1]>1}`;const f=t.shape.length,m=2===i.length&&d(t.shape,s),g=1===c(t.shape),y=ii(t.shape,n.shape),b=!e.packedInputs&&f===n.shape.length&&d(s,n.texData.texShape),x=e.packedInputs||i.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${f}_${b}_${o?u:""}_${i.length}_${g}_${y}_${m}_${l}_${p}_${h}_${x}_${a}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${a}`}});const a=e.userCode;let s=e.constructor.name;return s+="_"+r+"_"+a+`${V().getNumber("WEBGL_VERSION")}`,s}(e,l,p),f=this.getAndSaveBinary(h,()=>lb(this.gpgpu,e,l,p)),m=null!=this.activeTimers;let g;m&&(g=this.startTimer()),V().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(db(t.inShapeInfos,n),db([t.outShapeInfo],[r]));const s=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,o[0],o[1]):e.setOutputMatrixTexture(s.texture,o[0],o[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===V().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let u=0;u<n.length;++u){const r=n[u],{uniform:a,offset:s,shape:o,texShape:i}=t.variablesLocations[u];if(o){const{uniformShape:n}=ob(t.program.packedInputs,r.shape,r.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(o,new Int32Array(n));break;case 2:e.gl.uniform2iv(o,new Int32Array(n));break;case 3:e.gl.uniform3iv(o,new Int32Array(n));break;case 4:e.gl.uniform4iv(o,new Int32Array(n))}}if(i&&e.gl.uniform2i(i,r.texData.texShape[0],r.texData.texShape[1]),null!=a)if(r.isUniform)if(c(r.shape)<2)e.gl.uniform1f(a,r.uniformValues[0]);else{let t=r.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=r.texData.slice&&null!=s&&e.gl.uniform1i(s,r.texData.slice.flatOffset),e.setInputMatrixTexture(r.texData.texture.texture,a,u)}const i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=C(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&a)for(let u=0;u<t.program.customUniforms.length;++u){const n=t.program.customUniforms[u],r=t.customUniformLocations[u],s=a[u];if("float"===n.type)e.gl.uniform1fv(r,s);else if("vec2"===n.type)e.gl.uniform2fv(r,s);else if("vec3"===n.type)e.gl.uniform3fv(r,s);else if("vec4"===n.type)e.gl.uniform4fv(r,s);else if("int"===n.type)e.gl.uniform1iv(r,s);else if("ivec2"===n.type)e.gl.uniform2iv(r,s);else if("ivec3"===n.type)e.gl.uniform3iv(r,s);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(r,s)}}e.executeProgram()}(this.gpgpu,f,l,p,r),u.forEach(e=>this.disposeIntermediateTensorInfo(e)),m&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)}));const y=V().getNumber("WEBGL_FLUSH_THRESHOLD");if(y>0){const e=Fr();e-this.lastGlFlushTime>y&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!V().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&!1===a){const e=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),e}return o}compileAndRun(e,t,n,r,a=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!V().getBool("IS_TEST")){Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})}this.textureManager.dispose(),null!=this.canvas&&"undefined"!==typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Ba(()=>{if(!V().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=V().getBool("DEBUG");V().set("DEBUG",!1);const t=this.abs(Ri(1e-8)).dataSync()[0];if(V().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:a,texture:o,usage:i,isPacked:u}=t;if(null!=o)return;const l=null!=this.activeTimers;let d;l&&(d=Fr());let p=t.texShape;if(null==p&&(p=function(e,t=!1){let n=V().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=V().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&V().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,1===(e=e.map((t,n)=>n>=e.length-2?s(e[n]):e[n])).length&&(e=[2,e[0]])),2!==e.length){const t=b(e);e=t.newShape}let a=c(e),o=null;e.length<=1&&a<=n?o=[1,a]:2===e.length&&e[0]<=n&&e[1]<=n?o=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?o=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?o=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?o=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(o=[e[0],e[1]*e[2]*e[3]]);const i=null!=o&&Math.max(...o)>r&&Math.min(...o)<=(t?2:1)&&Math.min(...o)>0;if(null==o||i)if(t){const t=Ey(e);let n=2,r=2;e.length&&([n,r]=Ry(e)),a=t*(n/2)*(r/2),o=h(a).map(e=>2*e)}else o=h(a);return o}(n,u),t.texShape=p),null!=a){const e=_y(n);let s,o=p[1],i=p[0];const c=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!u&&c||([o,i]=my(p[0],p[1])),s=u?new xb(e,c):new bb(e,c);const h=c?[i,o]:p,f=this.makeTensorInfo(h,r),m=this.texData.get(f.dataId);m.usage=c?ly.PIXELS:ly.UPLOAD,m.texShape=h,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),o,i,a);const g=[[i,o]],y=!0,b=this.runWebGLProgram(s,[f],r,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,V().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),l&&(this.uploadWaitMs+=Fr()-d)}else{const e=this.acquireTexture(p,i,r,u);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*k(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise(e=>{try{this.checkCompletion_(t),e(!0)}catch(n){throw n}});e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await Ep(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw wy(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}=cb(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.outShapeLocation=s,e.outShapeStridesLocation=o,e.outTexShapeLocation=i}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:a,width:s,channels:o}=e,i=La().backend;if(!i.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const u=i.writeTexture(r,t,n,a,s,o);return La().makeTensorFromDataId(u,t,n,i)}}xk.nextDataId=0,Na()&&Ga("webgl",()=>new xk,2);const vk="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";class wk{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=li(t,n),this.enableShapeUniforms=pb(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}const kk="\n result.r = isNaN.r ? NAN : result.r;\n result.g = isNaN.g ? NAN : result.g;\n result.b = isNaN.b ? NAN : result.b;\n result.a = isNaN.a ? NAN : result.a;\n";class Ik{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=li(t,n);const a=this.outputShape.length;this.enableShapeUniforms=pb(a);let s="";if(r)if(0===a||1===c(this.outputShape))s="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else{if(s=`\n ${sb(a)} coords = getOutputCoords();\n `,1===a)this.enableShapeUniforms?s+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":s+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=tk("coords",a);this.enableShapeUniforms?s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= outShape[${a} - 2];\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= outShape[${a} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${s}\n\n setOutput(result);\n }\n `}}function Nk(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const Sk={kernelName:ot,backendName:"webgl",kernelFunc:Nk};function Tk(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(s.dataId),i=Nk({inputs:{x:r},backend:n}),u=Nk({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}const Ck={kernelName:ye,backendName:"webgl",kernelFunc:Tk},$k="return (a < 0.) ? b * a : a;",Ek="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const Rk={kernelName:pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r,o=n.makeTensorInfo([],"float32",Ar(s,"float32")),i=V().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ik(Ek,a.shape,o.shape):new wk($k,a.shape,o.shape),u=n.runWebGLProgram(i,[a,o],"float32");return n.disposeIntermediateTensorInfo(o),u}},_k="return (a < 0.) ? b * a : a;",Ak="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const Ok={kernelName:qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=V().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ik(Ak,r.shape,a.shape):new wk(_k,r.shape,a.shape);return n.runWebGLProgram(s,[r,a],"float32")}},Fk="if (isnan(x)) return x;";function Dk({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:o}=a,i=s,u=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&null!=n){const e=i.texData.get(o.dataId),t=n(e.values,u);return i.makeTensorInfo(o.shape,u,t)}let l;return l=V().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new fk(o.shape,t):new uk(o.shape,e),i.runWebGLProgram(l,[o],u)}}function Mk({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:a,dtype:s}){return({inputs:o,backend:i})=>{const{a:u,b:l}=o,c=i;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map(t=>{const[n,r]=t,a={dataId:n.dataId,dtype:n.dtype,shape:u.shape},s={dataId:r.dataId,dtype:r.dtype,shape:l.shape},o=new wk(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],ca(n.dtype,r.dtype))}),s=Tk({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const d=s||ca(u.dtype,l.dtype);if(("string"===u.dtype||"string"===l.dtype||c.shouldExecuteOnCPU([u,l]))&&null!=a){const e=c.texData.get(u.dataId).values,t=c.texData.get(l.dataId).values,n="string"===u.dtype?Eh(e):e,r="string"===u.dtype?Eh(t):t,[s,o]=a(u.shape,l.shape,n,r,d),i=c.makeTensorInfo(o,d);return c.texData.get(i.dataId).values=s,i}let p;return p=V().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Ik(t,u.shape,l.shape,n):new wk(e,u.shape,l.shape),c.runWebGLProgram(p,[u,l],d)}}function Pk(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":dk;if("elu"===e)return t?"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":pk;if("prelu"===e)return t?Ak:_k;if("leakyrelu"===e)return t?Ek:$k;if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class Lk{constructor(e,t,n,r=!1,a=!1,s=!1,o=null,i=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=pb(this.outputShape.length);const l=r?e[1]:e[2],c=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";o&&(m=i?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${o}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${o}\n }`:`vec4 activation(vec4 x) {\n ${o}\n }`,g="result = activation(result);");const y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`\n ${m}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${c}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${b};\n int batchB = ${x};\n for (int i = 0; i < ${c}; i++) {\n vec4 a = getMatrixA(batchA, ${d});\n vec4 b = getMatrixB(batchB, ${p});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${h[0]} * ${f[0]});\n result += (${h[1]} * ${f[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${y}\n\n ${g}\n\n setOutput(result);\n }\n `}}const Bk="return areal * breal - aimag * bimag;",Vk="return areal * bimag + aimag * breal;";class Wk{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=li(t,n),this.userCode=`\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${e}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `}}const zk="return a * b;";function Uk(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=ca(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new Wk(Bk,r.shape,a.shape),o=new Wk(Vk,r.shape,a.shape),i=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:a.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:a.shape}],u=n.runWebGLProgram(s,i,"float32"),l=n.runWebGLProgram(o,i,"float32"),c=Tk({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,a])){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),[o,i]=Cw(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(i,s);return n.texData.get(u.dataId).values=o,u}let o;return o=V().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ik(zk,r.shape,a.shape):new wk(zk,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const Gk={kernelName:Mt,backendName:"webgl",kernelFunc:Uk};function Hk(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=n,u=c(a.shape),l=g(s,u),d=c(l);i(u===d,()=>`The new shape (${l}) has ${d} elements and the old shape (${a.shape}) has ${u} elements. The new shape and old shape must have the same number of elements.`);const p=o.texData.get(a.dataId);return!p.isPacked||Oy(a.shape,l)||null!==p.texture&&Oy(p.shape,l)?(o.incRef(a.dataId),{dataId:a.dataId,shape:l,dtype:a.dtype}):function(e,t,n){const r=[Ey(e.shape),...Ry(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[Ey(t),...Ry(t)],o=new rk(s,r),i=[r],u=n.runWebGLProgram(o,[a],e.dtype,i,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(a,l,o)}const jk={kernelName:nn,backendName:"webgl",kernelFunc:Hk};class qk{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const o=4*Math.floor(n/4),i=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${p(e)?e.toPrecision(2):e}, ones);`}let l="";a%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${l}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===i}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${u}\n } else if (${2===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${u}\n } else if (${3===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}class Kk{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let o="0.0",i="";"prod"===t?o="1.0":"min"===t?(o="1.0 / 1e-20",i="min"):"max"===t&&(o="-1.0 / 1e-20",i="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let d=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${i}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${i}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,p="vec4";"all"===t?(o="1.0",d="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(o="0.0",d="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let h="";a%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${o};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${h}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${o});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${l}; i += 4) {\n int inIdx = inOffset + i;\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${d}\n }\n\n int inIdx = inOffset + ${l};\n if (${1===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${d}\n } else if (${2===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${d}\n } else if (${3===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${d}\n }\n setOutput(${u});\n }\n `}}function Xk(e,t,n,r){const a=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=Lp(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let s=e;for(let o=0;o<a.length;o++){const{inSize:i,windowSize:u,outSize:l}=a[o];let c,d;c="mean"===n?0===o?new qk({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new qk({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l}):new Kk({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},n),d=s,s=r.runWebGLProgram(c,[s],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return s}class Yk{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;const r=sb(this.rank),a=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let a=0;a<e.length;a++)r[e[a]]=n[a];return r.join()}(t);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${a}));\n }\n `}}class Qk{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let l=0;l<n.length;l++)n[l]=e[t[l]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=sb(this.rank),a=ek("rc",this.rank),s=new Array(this.rank);for(let l=0;l<t.length;l++)s[t[l]]=a[l];const o=`vec2(${s.slice(-2).join()})`,i=`++${a[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${s.join()}), ${o})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${u};\n if(${i}) {\n result[1] = ${u};\n }\n --${a[this.rank-1]};\n if(++${a[this.rank-2]} < ${n[this.rank-2]}) {\n result[2] = ${u};\n if(${i}) {\n result[3] = ${u};\n }\n }\n setOutput(result);\n }\n `}}function Zk(e,t,n){const r=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Qk(e.shape,t):new Yk(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function Jk(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;return function(e,t,n,r){const a=t,s=e.shape.length,o=y(a,e.shape);let i=o;const u=Ni(i,s),l=null!=u;let d=e;l&&(d=Zk(e,u,r),i=Ti(i.length,s)),Ii("sum",i,s);const[p,h]=wi(d.shape,i);let f=p;n&&(f=ki(p,o));const m=c(h),g=Hk({inputs:{x:d},attrs:{shape:[c(e.shape)/m,m]},backend:r}),b=Xk(g,da(e.dtype),"sum",r),x=Hk({inputs:{x:b},attrs:{shape:f},backend:r});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(b),l&&r.disposeIntermediateTensorInfo(d),x}(a,s,o,n)}const eI={kernelName:Nn,backendName:"webgl",kernelFunc:Jk};function tI(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{perm:s}=r,o=n,i=a.shape.length,u=new Array(i);for(let c=0;c<u.length;c++)u[c]=a.shape[s[c]];let l;if(o.shouldExecuteOnCPU([a])){const e=o.texData.get(a.dataId).values,t=Zw(e,a.shape,a.dtype,s,u);l=o.makeTensorInfo(u,a.dtype);o.texData.get(l.dataId).values=t}else l=Zk(a,s,o);return l}const nI={kernelName:jn,backendName:"webgl",kernelFunc:tI};function rI({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:u=0,activation:l=null}){const d=e.shape.length,p=t.shape.length,h=n?e.shape[d-2]:e.shape[d-1],f=r?t.shape[p-1]:t.shape[p-2],m=n?e.shape[d-1]:e.shape[d-2],g=r?t.shape[p-2]:t.shape[p-1],y=e.shape.slice(0,-2),b=t.shape.slice(0,-2),x=c(y),v=c(b),w=li(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([m,g]);i(h===f,()=>`Error in matMul: inner shapes (${h}) and (${f}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);const k=n?[x,h,m]:[x,m,h],I=r?[v,g,f]:[v,f,g],N=Hk({inputs:{x:e},backend:a,attrs:{shape:k}}),S=Hk({inputs:{x:t},backend:a,attrs:{shape:I}}),T=[N,S],C=Math.max(x,v),$=n?N.shape[1]:N.shape[2],E=null!=s,R=null!=o,_="leakyrelu"===l,A=null!=l?Pk(l,!0):null;let O;if((1===m||1===g)&&$>1e3&&!1===(E||R||_||null!=A)){let e=N,t=S;n&&(e=tI({inputs:{x:N},backend:a,attrs:{perm:[0,2,1]}}),T.push(e)),r&&(t=tI({inputs:{x:S},backend:a,attrs:{perm:[0,2,1]}}),T.push(t));const s=1===g;let o=e;1!==g&&(o=Hk({inputs:{x:e},backend:a,attrs:{shape:[C,$,1]}}),T.push(o));const i=1===g?2:1;let u=t;s&&(u=Hk({inputs:{x:t},backend:a,attrs:{shape:[C,1,$]}}),T.push(u));const l=Uk({inputs:{a:o,b:u},backend:a});O=Jk({inputs:{x:l},backend:a,attrs:{axis:i,keepDims:!0}}),T.push(l)}else{const i=ca(e.dtype,t.dtype),l=new Lk(k,I,[C,m,g],n,r,E,A,R,_),c=[N,S];if(null!=s&&c.push(s),R&&c.push(o),_){const e=a.makeTensorInfo([],"float32",Ar(u,"float32"));c.push(e),T.push(e)}O=a.runWebGLProgram(l,c,i)}const F=Hk({inputs:{x:O},backend:a,attrs:{shape:w}});T.push(O);for(const i of T)a.disposeIntermediateTensorInfo(i);return F}const aI={kernelName:er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;return rI({a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:c})}},sI="return abs(x);";const oI={kernelName:H,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&"complex64"!==r.dtype){const e=n.texData.get(r.dataId),t=Lw(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let a;return a=V().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new fk(r.shape,sI):new uk(r.shape,sI),n.runWebGLProgram(a,[r],r.dtype)}},iI=Dk({opSnippet:lk+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),uI={kernelName:j,backendName:"webgl",kernelFunc:iI},lI=Dk({opSnippet:lk+"\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),cI={kernelName:q,backendName:"webgl",kernelFunc:lI},dI="return a + b;",pI=Mk({opSnippet:dI,packedOpSnippet:dI,supportsComplex:!0,cpuKernelImpl:sw}),hI={kernelName:K,backendName:"webgl",kernelFunc:pI};class fI{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((e,t)=>`T${t}`);const n=[];this.variableNames.forEach(e=>{n.push(`float v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>`v${e}`).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${r};\n setOutput(result);\n }\n `}}class mI{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((e,t)=>`T${t}`);const n=[];this.variableNames.forEach(e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>`v${e}`).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${r};\n setOutput(result);\n }\n `}}const gI={kernelName:X,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,a=n;if(1===a.length)return Nk({inputs:{x:a[0]},backend:r});if(a.length>V().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(a.length/2),n=e({inputs:a.slice(0,t),backend:r}),s=e({inputs:a.slice(t),backend:r});return e({inputs:[n,s],backend:r})}const s=a.map(e=>e.dtype).reduce((e,t)=>ca(e,t)),o=a.map(e=>e.shape),i=V().getBool("WEBGL_PACK")?new mI(a[0].shape,o):new fI(a[0].shape,o);return r.runWebGLProgram(i,a,s)}};const yI={kernelName:Y,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=y(s,a.shape);let l=u;const d=Ni(l,i);let p=a;null!=d&&(p=tI({inputs:{x:a},backend:n,attrs:{perm:d}}),l=Ti(l.length,i)),Ii("all",l,i);const[h,f]=wi(p.shape,l),m=Hk({inputs:{x:p},backend:n,attrs:{shape:[-1,c(f)]}}),g=Xk(m,m.dtype,"all",n);let b;if(o){b=Hk({inputs:{x:g},backend:n,attrs:{shape:ki(h,u)}})}else b=Hk({inputs:{x:g},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=d&&n.disposeIntermediateTensorInfo(p),b}};const bI={kernelName:Q,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=y(s,a.shape);let l=u;const d=Ni(l,i);let p=a;null!=d&&(p=tI({inputs:{x:a},backend:n,attrs:{perm:d}}),l=Ti(l.length,i)),Ii("any",l,i);const[h,f]=wi(p.shape,l),m=Hk({inputs:{x:p},backend:n,attrs:{shape:[-1,c(f)]}}),g=Xk(m,m.dtype,"any",n);let b;if(o){b=Hk({inputs:{x:g},backend:n,attrs:{shape:ki(h,u)}})}else b=Hk({inputs:{x:g},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=d&&n.disposeIntermediateTensorInfo(p),b}};class xI{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:a,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];const o="max"===t?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${i};\n float candidate = getA(batch, inIdx);\n if (candidate ${o} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class vI{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,i(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");const o=this.outputShape,u=o.length,l=sb(u),c=tk("coords",u);let d,p;if(1===s){p=u+1;const e=sb(p);d=`\n ${e} sourceLocR = ${e}(${c.join()}, 0);\n ++${c[u-1]};\n ${e} sourceLocG = ${e}(${c.join()}, 0);\n ++${c[u-2]};\n ${e} sourceLocA = ${e}(${c.join()}, 0);\n --${c[u-1]};\n ${e} sourceLocB = ${e}(${c.join()}, 0);\n --${c[u-2]};`}else p=u,d=`\n ${l} sourceLocR = coords;\n ++${c[u-1]};\n ${l} sourceLocG = coords;\n ++${c[u-2]};\n ${l} sourceLocA = coords;\n --${c[u-1]};\n ${l} sourceLocB = coords;\n --${c[u-2]};`;const h=["x","y","z","w","u","v"].slice(0,p),f="."+h[p-1],m=h.map(e=>"int "+e),g=tk("sourceLocR",p-1).concat("inIdx.r"),y=tk("sourceLocG",p-1).concat("inIdx.g"),b=tk("sourceLocB",p-1).concat("inIdx.b"),x=tk("sourceLocA",p-1).concat("inIdx.a"),v="max"===n?"greaterThan":"lessThan",w=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()}),\n getBestIndicesAChannel(${x.join()})));`,k=`vec4(\n getAChannel(${g.join()}),\n hasNextCol ? getAChannel(${y.join()}) : 0.,\n hasNextRow ? getAChannel(${b.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,I=r?"":`\n float getBestIndicesAChannel(${m.join()}) {\n return getChannel(getBestIndicesA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${m.join()}) {\n return getChannel(getA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }\n ${I}\n void main() {\n ${l} coords = getOutputCoords();\n bool hasNextCol = ${c[u-1]} < ${o[u-1]-1};\n bool hasNextRow = ${c[u-2]} < ${o[u-2]-1};\n ${d}\n ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},\n sourceLocB${f}, sourceLocA${f}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${k};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${k};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function wI(e,t,n,r=null){let a=t.shape[0],s=t.shape[1];null!=r&&(a=r.shape[0],s=r.shape[1]);const o=Lp(s),i={windowSize:o,inSize:s,batchSize:a,outSize:Math.ceil(s/o)},u=new xI(i,n,null==r),l=[t];null!=r&&l.push(r);const c=e.runWebGLProgram(u,l,"int32");if(1===c.shape[1])return c;const d=wI(e,t,n,c);return e.disposeIntermediateTensorInfo(c),d}function kI(e,t,n,r=null){const a=null!=r?r.shape:t.shape,s=Lp(a[a.length-1]),o=new vI(a,s,n,null==r),i=null==r?[t]:[t,r],u=e.runWebGLProgram(o,i,"int32");if(u.shape.length===t.shape.length){const r=kI(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function II(e,t,n,r){const a=[n];if(Ii("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!V().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let o=t;null!==s&&s.isPacked&&(o=e.unpackTensor(t),n.push(o));const[i,u]=wi(o.shape,a),l=c(u),d=Hk({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(d);const p=wI(e,d,r);n.push(p);const h=Hk({inputs:{x:p},backend:e,attrs:{shape:i}});return n.forEach(t=>e.disposeIntermediateTensorInfo(t)),h}return kI(e,t,r)}const NI={kernelName:Z,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=y(s,a.shape);const i=Ni(o,a.shape.length);let u=a;const l=[];null!=i&&(u=tI({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Ti(o.length,u.shape.length)),Ii("argMax",[o[0]],u.shape.length);const c=II(n,u,o[0],"max");return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}};const SI={kernelName:J,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=y(s,a.shape);const i=Ni(o,a.shape.length);let u=a;const l=[];null!=i&&(u=tI({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Ti(o.length,u.shape.length)),Ii("argMin",[o[0]],u.shape.length);const c=II(n,u,o[0],"min");return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}},TI=Dk({opSnippet:lk+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),CI={kernelName:ee,backendName:"webgl",kernelFunc:TI},$I=Dk({opSnippet:lk+"return log(x + sqrt(x * x + 1.0));"}),EI={kernelName:te,backendName:"webgl",kernelFunc:$I},RI=Dk({opSnippet:lk+"\n return atan(x);\n"}),_I={kernelName:ne,backendName:"webgl",kernelFunc:RI},AI=Mk({opSnippet:vk+"\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+kk+"\n return result;\n"}),OI={kernelName:ae,backendName:"webgl",kernelFunc:AI},FI=Dk({opSnippet:lk+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),DI={kernelName:re,backendName:"webgl",kernelFunc:FI};class MI{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideHeight,i=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${p}, ${h});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${d};\n wC += ${l}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?a?m:g:`wR * ${d} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const x=4*Math.floor(s/4),v=s%4,w=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${p}, ${h});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${x}; wC += 4) {\n int xC = xCCorner + wC * ${l};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n getValue(batch, xR, xC + 3 * ${l}, d)\n );\n\n ${w}\n }\n\n int xC = xCCorner + ${x};\n if (${1===v}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${w}\n } else if (${2===v}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n initializationValue,\n initializationValue\n );\n\n ${w}\n } else if (${3===v}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n initializationValue\n );\n\n ${w}\n }\n }\n setOutput(${b});\n }\n `}}class PI{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideDepth,i=e.strideHeight,u=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${o}, ${i}, ${u});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${p};\n wD += ${l}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f};\n wC += ${d}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(v="avgValue / max(count, 1.0)");const w=4*Math.floor(s/4),k=s%4,I=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${o}, ${i}, ${u});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n const float initializationValue = ${x};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${x});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${l}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${w}; wC += 4) {\n int xC = xCCorner + wC * ${d};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n getValue(batch, xD, xR, xC + 3 * ${d}, ch)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${w};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${2===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n initializationValue\n );\n\n ${I}\n }\n }\n }\n setOutput(${v});\n }\n `}}const LI={kernelName:se,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;Vy(a,"avgPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:l}=r;i(go(o,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const c=so(a.shape,s,o,1,u,l);if(1===c.filterWidth&&1===c.filterHeight&&d(c.inShape,c.outShape))return Nk({inputs:{x:a},backend:n});const p=new MI(c,"avg",!1);return n.runWebGLProgram(p,[a],"float32")}};const BI={kernelName:ie,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r,c=oo(a.shape,s,o,[1,1,1],i,u,l),d=new PI(c,"avg",!1);return n.runWebGLProgram(d,[a],"float32")}};class VI{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=i-1-e.padInfo.top,c=u-1-e.padInfo.left,d=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${l}, ${c});\n const float avgMultiplier = float(${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${i};\n wR += ${s}) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC+= ${o}) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class WI{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=c-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`\n const ivec3 pads = ivec3(${h}, ${f}, ${m});\n const float avgMultiplier = float(${g});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${c};\n wD += ${i}) {\n float dyD = float(dyDCorner + wD) / ${a}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${d};\n wR += ${u}) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${p};\n wC += ${l}) {\n float dyC = float(dyCCorner + wC) / ${o}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const zI={kernelName:ue,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s,{filterSize:i,strides:u,pad:l,dimRoundingMode:c}=r,d=oo(o.shape,i,u,[1,1,1],l,c),p=new WI(d);return n.runWebGLProgram(p,[a],o.dtype)}};const UI={kernelName:oe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s;Vy([a,s],"avgPoolGrad");const{filterSize:i,strides:u,pad:l}=r,c=so(o.shape,i,u,1,l),d=new VI(c);return n.runWebGLProgram(d,[a],o.dtype)}};const GI={kernelName:le,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;return rI({a,b:s,transposeA:o,transposeB:i,backend:n})}};class HI{constructor(e,t,n,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],li(e,t),li(e,n);let o="0.0";null!=r&&(li(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";null!=a&&(li(e,a),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${o};\n float scale = ${i};\n float inv = scale * inversesqrt(variance + float(${s}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class jI{constructor(e,t,n,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],li(e,t),li(e,n);let o="vec4(0.0)";null!=r&&(li(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";null!=a&&(li(e,a),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${o};\n vec4 scale = ${i};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${s}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const qI={kernelName:tt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:a,variance:s,offset:o,scale:u}=e;i(a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),i(null==o||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),i(null==u||a.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;null==l&&(l=.001);const c=[r,a,s];let d=null;null!=o&&(d=o.shape,c.push(o));let p=null;null!=u&&(p=u.shape,c.push(u));const h=V().getBool("WEBGL_PACK_NORMALIZATION")?new jI(r.shape,a.shape,s.shape,d,p,l):new HI(r.shape,a.shape,s.shape,d,p,l);return t.runWebGLProgram(h,c,c[0].dtype)}};class KI{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=sb(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return XI.slice(0,e).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map((e,t)=>`sourceLoc.${XI[t]} = start[${t}] + coords.${XI[t]};`).join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const XI=["x","y","z","w","u","v"];class YI{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=sb(this.rank),n=tk("coords",this.rank),r=tk("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,s=`getChannel(getSource(${r.join()}), ${a})`,o=`\n result.x = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${s};\n --${r[this.rank-1]};\n }\n `,i=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${s};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map((e,t)=>`start[${t}]`).join()});`:e.map((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${o}\n ${i}\n setOutput(result);\n }\n `}}function QI(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r,[i,u]=Sp(a,s,o);if(wp(a,i,u),0===c(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=Bw(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),d=Ip(a.shape,i,u);if(l||!d){const e=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new YI(u):new KI(u),t=[i];return n.runWebGLProgram(e,[a],a.dtype,t)}return n.uploadToGPU(a.dataId),function(e,t,n,r){const a=r.texData.get(e.dataId),s=r.makeTensorInfo(n,e.dtype),o=r.texData.get(s.dataId);Object.assign(o,a),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Np(t,C(e.shape));a.slice&&(i+=a.slice.flatOffset),o.slice={flatOffset:i,origDataId:a.slice&&a.slice.origDataId||e.dataId};const u=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,u+1),s}(a,i,u,n)}const ZI={kernelName:yn,backendName:"webgl",kernelFunc:QI},JI={kernelName:ce,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;i(a.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const u=s.reduce((e,t)=>e*t),l=Vp(a.shape,s,u),c=Wp(l.length,s.length),d=zp(a.shape,s,u),p=Up(o,s.length),h=Gp(d,o,s.length),f=[],m=Hk({inputs:{x:a},backend:n,attrs:{shape:l}}),g=tI({inputs:{x:m},backend:n,attrs:{perm:c}}),y=Hk({inputs:{x:g},backend:n,attrs:{shape:d}}),b=QI({inputs:{x:y},backend:n,attrs:{begin:p,size:h}});return f.push(m),f.push(g),f.push(y),f.forEach(e=>n.disposeIntermediateTensorInfo(e)),b}};const eN={kernelName:de,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o}=r,i=n.readSync(a.dataId),u=n.readSync(s.dataId),l=ow(i,u,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,l)}};const tN={kernelName:pe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=V().getBool("WEBGL_PACK_BINARY_OPERATIONS"),o=V().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([r,a])||1===o){const e=n.texData.get(r.dataId).values,t=n.texData.get(a.dataId).values,[s,o]=uw(r.shape,a.shape,e,t,r.dtype),i=n.makeTensorInfo(o,r.dtype);return n.texData.get(i.dataId).values=s,i}let i;return i=s?new Ik("\n int r = int(a.r) & int(b.r);\n int g = int(a.g) & int(b.g);\n int rb = int(a.b) & int(b.b);\n int ra = int(a.a) & int(b.a);\n return vec4(r, g, rb, ra);\n",r.shape,a.shape,!1):new wk("\n return float(int(a.r) & int(b.r));\n",r.shape,a.shape),n.runWebGLProgram(i,[r,a],r.dtype)}};const nN={kernelName:he,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,s=n.readSync(r.dataId),o=n.readSync(a.dataId),i=li(Array.from(s),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}},rN=Mk({opSnippet:"return float(a != b);",cpuKernelImpl:Ew,dtype:"bool"}),aN={kernelName:Lt,backendName:"webgl",kernelFunc:rN};function sN(e){const{inputs:t,backend:n}=e,{input:r}=t;return Nk({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const oN={kernelName:Jt,backendName:"webgl",kernelFunc:sN};const iN={kernelName:fe,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:a}=t,{x:s}=n,{dtype:o}=a;if("complex64"===o){if("complex64"===s.dtype)return Nk({inputs:{x:s},backend:r});const t=Iu(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=Tk({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=sN({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:o}});return r.disposeIntermediateTensorInfo(t),n}if(!w(s.dtype,o)){const e=Nk({inputs:{x:s},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:o}}if(r.shouldExecuteOnCPU([s])){const e=r.texData.get(s.dataId).values,[t,n,a]=lw(e,s.shape,s.dtype,o);return r.makeTensorInfo(t,n,a)}if("int32"===o)return function(e,t){const n=new uk(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,r);if("bool"===o){const e=r.makeTensorInfo([],"bool",x("bool",1)),t=rN({inputs:{a:s,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},uN="return ceil(x);",lN=Dk({opSnippet:uN,packedOpSnippet:uN,cpuKernelImpl:cw}),cN={kernelName:me,backendName:"webgl",kernelFunc:lN};class dN{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class pN{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const hN={kernelName:ge,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=V().getBool("WEBGL_PACK_CLIP")?new pN(a.shape):new dN(a.shape);const u=[[s],[o]];return n.runWebGLProgram(i,[a],a.dtype,u)}};class fN{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function mN(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const gN={kernelName:be,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=n.texData.get(r.dataId),s=new fN(r.shape),o=[mN(r,a.complexTensorInfos.real),mN(r,a.complexTensorInfos.imag)];return n.runWebGLProgram(s,o,o[0].dtype)}};class yN{constructor(e){this.outputShape=[],this.outputShape=_p(e,1),this.variableNames=e.map((e,t)=>`T${t}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){const e=t[s-1];n.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${e}));`)}const r=t.length,a=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${a}));`),this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${n.join("\n ")}\n }\n `}}class bN{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_p(e,t);const n=this.outputShape,r=n.length,a=sb(r),s=tk("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((e,t)=>`T${t}`);const i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];const u=o[t],l=o.slice(-2),c=o.join();let d=`if (${u} < ${i[0]}) {\n return getChannel(\n getT0(${c}), vec2(${l.join()}));\n }`;for(let f=1;f<i.length;f++){const e=i[f-1];d+=`\n if (${u} < ${i[f]} && ${u} >= ${i[f-1]}) {\n return getChannel(\n getT${f}(${xN(o,u,e)}),\n vec2(${xN(l,u,e)}));\n }`}const p=i.length,h=i[i.length-1];d+=`\n return getChannel(\n getT${p}(${xN(o,u,h)}),\n vec2(${xN(l,u,h)}));`,this.userCode=`\n float getValue(${o.map(e=>"int "+e)}) {\n ${d}\n }\n\n void main() {\n ${a} coords = getOutputCoords();\n vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n ${s[r-1]} = ${s[r-1]} + 1;\n if (${s[r-1]} < ${n[r-1]}) {\n result.g = getValue(${s});\n }\n\n ${s[r-2]} = ${s[r-2]} + 1;\n if (${s[r-2]} < ${n[r-2]}) {\n result.a = getValue(${s});\n }\n\n ${s[r-1]} = ${s[r-1]} - 1;\n if (${s[r-2]} < ${n[r-2]} &&\n ${s[r-1]} < ${n[r-1]}) {\n result.b = getValue(${s});\n }\n setOutput(result);\n }\n `}}function xN(e,t,n){const r=e.indexOf(t);return e.map((e,t)=>t===r?`${e} - ${n}`:e).join()}function vN(e){const{inputs:t,backend:n}=e,{input:r}=t;return Nk({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const wN={kernelName:ut,backendName:"webgl",kernelFunc:vN};function kN(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map(e=>sN({inputs:{input:e},backend:n})),a=e.map(e=>vN({inputs:{input:e},backend:n})),s=kN(r,t,n),o=kN(a,t,n),i=Tk({inputs:{real:s,imag:o},backend:n});return r.forEach(e=>n.disposeIntermediateTensorInfo(e)),a.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(o),i}let a=n.shouldExecuteOnCPU(e);if("string"===r&&(a=!0),a){const a=e.map(e=>{const r=c(e.shape.slice(t));return Hk({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})}),s=a.map(e=>({vals:n.readSync(e.dataId),shape:e.shape})),o=_p(a.map(e=>e.shape),1),i=1===a[0].shape[0],u=dw(s,o,r,i),l=_p(e.map(e=>e.shape),t),d=n.makeTensorInfo(l,r,u);return a.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}const s=e.filter(e=>c(e.shape)>0),o=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=o?new uk(e[0].shape,hk):new fk(e[0].shape,hk);return n.runWebGLProgram(t,e,r)}const i=V().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>i){const e=[];for(let a=0;a<s.length;a+=i){const r=s.slice(a,a+i);e.push(kN(r,t,n))}const r=kN(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(o){const e=new bN(s.map(e=>e.shape),t);return n.runWebGLProgram(e,s,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=_p(e.map(e=>e.shape),t),a=e.map(e=>Hk({inputs:{x:e},attrs:{shape:[-1,c(e.shape.slice(t))]},backend:n}));return{tensors2D:a,outShape:r}}(s,t,n),d=new yN(u.map(e=>e.shape)),p=n.runWebGLProgram(d,u,r);u.forEach(e=>n.disposeIntermediateTensorInfo(e));const h=Hk({inputs:{x:p},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(p),h}function IN(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=y(a,t[0].shape)[0],o=t.map(e=>e.shape);Rp(o,s);const i=_p(t.map(e=>e.shape),s);if(0===c(i))return n.makeTensorInfo(i,t[0].dtype,[]);const u=t.filter(e=>c(e.shape)>0);return 1===u.length?Nk({inputs:{x:u[0]},backend:n}):kN(u,s,n)}const NN={kernelName:xe,backendName:"webgl",kernelFunc:IN};class SN{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",v="";n&&(x=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,v="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${x}\n\n const ivec2 strides = ivec2(${i}, ${u});\n const ivec2 pads = ivec2(${s}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${d}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${h}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${h}) *\n getW(wR, wC, ${h}, d2);\n } else {\n dotProd +=\n getX(batch, ${h}, xR, xC) *\n getW(wR, wC, ${h}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${h}, d2),\n getW(wR, wC, ${h} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${h}),\n getX(batch, xR, xC, ${h} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${h}, xR, xC),\n getX(batch, ${h} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${h}, d2),\n getW(wR, wC, ${h} + 1, d2),\n getW(wR, wC, ${h} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${h}),\n getX(batch, xR, xC, ${h} + 1),\n getX(batch, xR, xC, ${h} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${h}, xR, xC),\n getX(batch, ${h} + 1, xR, xC),\n getX(batch, ${h} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${w}\n ${v}\n setOutput(result);\n }\n `}}class TN{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${a}, ${s}, ${o});\n const ivec3 pads = ivec3(${t}, ${n}, ${r});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${c}; wF++) {\n int xF = xFCorner + wF * ${i};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d}; wR++) {\n int xR = xRCorner + wR * ${u};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${l};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${h}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===f}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${h}) *\n getW(wF, wR, wC, ${h}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${h}),\n getX(batch, xF, xR, xC, ${h} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${h}, d2),\n getW(wF, wR, wC, ${h} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${h}),\n getX(batch, xF, xR, xC, ${h} + 1),\n getX(batch, xF, xR, xC, ${h} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${h}, d2),\n getW(wF, wR, wC, ${h} + 1, d2),\n getW(wF, wR, wC, ${h} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class CN{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=pb(this.outputShape.length);const o=e.padInfo.left,i=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,d=c;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let s=0;s<c;s++)p+=`\n vec4 xTexelC${2*s};\n int xTexelC${2*s}Ready;\n vec4 xTexelC${2*s+1};\n int xTexelC${2*s+1}Ready;\n vec4 xC${s};`;p+=`\n for (int r = 0; r < ${l}; r++) {\n for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n `;for(let s=0;s<c;s++)p+=`\n xTexelC${2*s} = vec4(0.0);\n xTexelC${2*s}Ready = 0;\n xTexelC${2*s+1} = vec4(0.0);\n xTexelC${2*s+1}Ready = 0;\n xC${s} = vec4(0.0);`;p+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let g=0;g<(d+1)/2;g++){const t=2*g;if(p+=`\n xC = xCCorner + ${t*u};\n `,1===i){if(t<c&&(o%2===1?(p+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,p+=1===u&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1<c)){const e=o%2===0?s(u):u;u%2===0&&o%2===1||u%2!==0&&o%2!==1?(p+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,p+=u>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):p+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t<c&&(o%2===1?(p+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1<c&&(p+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1<c&&(p+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `)));t<c&&(p+=`\n wTexel = getW(r, ${t}, d1, d2);\n dotProd += xC${t}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${t}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `,t+1<c&&(p+=`\n wTexel = getW(r, ${t+1}, d1, d2);\n dotProd += xC${t+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${t+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `))}p+="\n }\n ",p+="\n }\n ",p+="\n }\n ";let h="",f="";n&&(h=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${h}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${p}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${m}\n ${f}\n setOutput(result);\n }\n `}}class $N{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=pb(this.outputShape.length);const{dataFormat:n}=t,r=zy(),a="channelsLast"===n,s=a?1:2,o=a?2:3,i=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let u="";for(let l=0;l<=1;l++)for(let e=0;e<=1;e++)u+=`\n blockIndex = rc.z + ${e};\n pos = rc.y + ${l};\n\n ${i}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${s}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${o}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${a}) {\n innerDims = vec2(d1, ch);\n result[${2*l+e}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*l+e}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${u}\n\n ${r.output} = result;\n }\n `}}function EN(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function RN({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:u=null}){const l=e.shape,c=r.texData.get(e.dataId),p=n.inChannels,h=l[0]*l[1]*l[2],f=n.outChannels,m="channelsLast"===n.dataFormat,g=!1;let y;const b=[];if(null!=s){const e=EN(s.shape,m);null!=e&&(s=Hk({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=EN(a.shape,m);null!=e&&(a=Hk({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}if(!((1===h||1===f)&&p>1e3)&&c.isPacked&&m&&null!=c.texture&&l[2]%2!==0&&d(c.shape.slice(-3),l.slice(-3))){const d=l[0]*l[1]*(l[2]+1),p={dataId:e.dataId,shape:[1,d,n.inChannels],dtype:e.dtype},h=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,i(Oy(c.shape,p.shape),()=>`packed reshape ${c.shape} to ${p.shape} isn't free`);const f=Hk({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(f);const m=rI({a:p,b:f,backend:r,transposeA:false,transposeB:g,bias:a,activation:u,preluActivationWeights:s,leakyreluAlpha:o}),x=r.texData.get(m.dataId);i(x.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=h,x.shape=n.outShape,y=Nk({inputs:{x:m},backend:r}),y.shape=n.outShape,b.push(m)}else{const i=n.outHeight*n.outWidth,l=Hk({inputs:{x:e},backend:r,attrs:{shape:m?[n.batchSize,i,n.inChannels]:[n.batchSize,n.inChannels,i]}}),c=Hk({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),d=rI({a:m?l:c,b:m?c:l,transposeA:!m,transposeB:g,backend:r,bias:a,activation:u,preluActivationWeights:s,leakyreluAlpha:o});y=Hk({inputs:{x:d},backend:r,attrs:{shape:n.outShape}}),b.push(l),b.push(c),b.push(d)}for(const i of b)r.disposeIntermediateTensorInfo(i);return y}function _N({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const{filterWidth:u,filterHeight:l,inChannels:d,outWidth:p,outHeight:h,dataFormat:f}=n,m="channelsLast"===f,g=u*l*d,y=h*p,b=[n.batchSize,g,y],x=[];if(null!=s){const e=EN(s.shape,m);null!=e&&(s=Hk({inputs:{x:s},backend:r,attrs:{shape:e}}),x.push(s))}if(null!=a){const e=EN(a.shape,m);null!=e&&(a=Hk({inputs:{x:a},backend:r,attrs:{shape:e}}),x.push(a))}const v=Hk({inputs:{x:t},backend:r,attrs:{shape:[1,g,c(t.shape)/g]}});x.push(v);const w=new $N(b,n),k=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],I=r.runWebGLProgram(w,[e],"float32",k),N=Hk({inputs:{x:I},backend:r,attrs:{shape:b}});x.push(I),x.push(N);const S=null!=a,T=null!=s,C="leakyrelu"===i,$=i?Pk(i,!0):null,E=new Lk(m?N.shape:v.shape,m?v.shape:N.shape,m?[n.batchSize,y,n.outChannels]:[n.batchSize,n.outChannels,y],!0,!1,S,$,T,C),R=m?[N,v]:[v,N];if(a&&R.push(a),T&&R.push(s),C){const e=r.makeTensorInfo([],"float32",Ar(o,"float32"));R.push(e),x.push(e)}const _=r.runWebGLProgram(E,R,"float32"),A=Hk({inputs:{x:_},backend:r,attrs:{shape:n.outShape}});x.push(_);for(const c of x)r.disposeIntermediateTensorInfo(c);return A}const AN={kernelName:ve,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r,d=bo(u),p=io(a.shape,s.shape,o,l,i,c,!1,d);let h;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(p.strideWidth<=2&&"channelsLast"===d&&V().getBool("WEBGL_EXP_CONV")){const e=new CN(p),t=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];h=n.runWebGLProgram(e,[a,s],"float32",t)}else if(V().getBool("WEBGL_CONV_IM2COL"))h=_N({x:a,filter:s,convInfo:p,backend:n});else{const e=new SN(p);h=n.runWebGLProgram(e,[a,s],"float32")}else h=RN({x:a,filter:s,convInfo:p,backend:n});const f=Hk({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}};class ON{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,s="channelsLast"===e.dataFormat;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${a};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n ${s?"float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);":"float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);"}\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class FN{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s="channelsLast"===e.dataFormat,o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,u=s?1:2,l=s?2:3,c=s?3:1;this.userCode=`\n const ivec2 pads = ivec2(${o}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${s}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class DN{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.padInfo.front,s=e.padInfo.top,o=e.padInfo.left;this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yF = 0; yF < ${e.outDepth}; yF++) {\n int xF = wF + yF * ${t} - ${a};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${n} - ${s};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${r} - ${o};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class MN{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,u=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${i}, ${u}, ${l});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${t}; wF++) {\n float dyF = float(dyFCorner + wF) / ${a}.0;\n\n if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${t} - 1 - wF;\n\n for (int wR = 0; wR < ${n}; wR++) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${n} - 1 - wR;\n\n for (int wC = 0; wC < ${r}; wC++) {\n float dyC = float(dyCCorner + wC) / ${o}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${r} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const PN={kernelName:we,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,filterShape:c}=r,d=bo(u),p=io(a.shape,c,o,1,i,l,!1,d),h=new ON(p);return n.runWebGLProgram(h,[a,s],"float32")}};class LN{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=pb(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,r=t-1-e.padInfo.top,a=n-1-e.padInfo.left;this.userCode=`\n const ivec2 pads = ivec2(${r}, ${a});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n vec4 result = vec4(0.);\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n int wCPerm = ${n} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\n && (fract(dyC) == 0.0);\n int idyC = int(dyC);\n\n float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n dySample : getDy(batch, idyR, idyC2, d2);\n\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n\n dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample2.xy : dySample2.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC2, d2);\n vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n }\n }\n }\n setOutput(result);\n }\n `}}const BN={kernelName:ke,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r,d=bo(l),p=io(o,s.shape,i,1,u,c,!1,d);if(V().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===d){const e=[[p.strideHeight,p.strideWidth]],t=new LN(p);return n.runWebGLProgram(t,[a,s],"float32",e)}{const e=new FN(p);return n.runWebGLProgram(e,[a,s],"float32")}}};const VN={kernelName:Ie,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r,l=uo(a.shape,s.shape,o,u,i),c=new TN(l);return n.runWebGLProgram(c,[a,s],"float32")}};const WN={kernelName:Ne,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,filterShape:u}=r,l=uo(a.shape,u,o,1,i),c=new DN(l);return n.runWebGLProgram(c,[a,s],"float32")}};const zN={kernelName:Se,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:o,strides:i,inputShape:u}=r,l=uo(u,s.shape,i,1,o),c=new MN(l);return n.runWebGLProgram(c,[a,s],"float32")}},UN=Dk({opSnippet:Fk+"\n return cos(x);\n",packedOpSnippet:`\n vec4 result = cos(x);\n bvec4 isNaN = isnan(x);\n ${kk}\n return result;\n`}),GN={kernelName:Te,backendName:"webgl",kernelFunc:UN},HN=Dk({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),jN={kernelName:Ce,backendName:"webgl",kernelFunc:HN};class qN{constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[s,o,i,u]=e,[l]=t,[c,d]=n;this.outputShape=[l,c,d,u];const p="bilinear"===r?1:0,[h,f]=[o-1+".0",i-1+".0"],[m,g,y]=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[b,x,v]=d>1?[""+(i-1)/(d-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${s}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${x};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${h} ) {\n setOutput(float(${a}));\n return;\n }\n float in_x = ${v};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${a}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${p} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const KN={kernelName:Re,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,c=new qN(a.shape,s.shape,i,u,l);return n.runWebGLProgram(c,[a,s,o],"float32")}};var XN,YN;(YN=XN||(XN={})).Prod="*",YN.Sum="+";class QN{constructor(e,t,n,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const a=this.outputShape.length,s=this.op===XN.Prod?"1.0":"0.0",o=n?s:`getX(${ZN(a,"coords",this.op)})`,i=this.outputShape[this.outputShape.length-1];let u="",l="";n?(u=r?"end != "+(i-1):"end != 0",l=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${i}`:"end >= pow2",l=r?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${sb(a)} coords = getOutputCoords();\n int end = ${JN(a,"coords",this.op)};\n float val = ${o};\n int pow2 = int(pow(2.0, index));\n if (${u}) {\n int idx = ${l};\n ${JN(a,"coords",this.op)} = idx;\n val ${this.op}= getX(${ZN(a,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function ZN(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function JN(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function eS(e,t,n,r,a,s){const o=t.shape.length,i=Ni([r],o);let u=t;null!=i&&(u=tI({inputs:{x:t},backend:n,attrs:{perm:i}}));const l=Ti(1,o)[0];if(l!==o-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${r}`);const c=u.shape[l];let d=Nk({inputs:{x:u},backend:n});for(let p=0;p<=Math.ceil(Math.log2(c))-1;p++){const t=new QN(e,u.shape,!1,s),r=[[p]],a=d;d=n.runWebGLProgram(t,[d],d.dtype,r),n.disposeIntermediateTensorInfo(a)}if(a){const t=new QN(e,u.shape,a,s),r=d;d=n.runWebGLProgram(t,[d],d.dtype),n.disposeIntermediateTensorInfo(r)}if(null!=i){const e=tI({inputs:{x:d},backend:n,attrs:{perm:Si(i)}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(u),e}return d}const tS={kernelName:$e,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r;return eS(XN.Prod,a,n,s,o,i)}};const nS={kernelName:Ee,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r;return eS(XN.Sum,a,n,s,o,i)}};const rS={kernelName:_e,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o,binaryOutput:i}=r;if(1===a.shape.length){const e=n.readSync(a.dataId),t=n.readSync(s.dataId),r=ow(e,t,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,r)}if(2===a.shape.length){const e=n.bufferSync(a),t=n.bufferSync(s),r=iw(e,t,o,i);return n.makeTensorInfo(r.shape,s.dtype,r.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}};class aS{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${t};\n int offset_h = imod(h, ${t});\n int in_w = w / ${t};\n int offset_w = imod(w, ${t});\n int offset_d = (offset_h * ${t} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const sS={kernelName:Ae,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:o}=r,i=a.shape[0],u=("NHWC"===o?a.shape[1]:a.shape[2])*s,l=("NHWC"===o?a.shape[2]:a.shape[3])*s,c=("NHWC"===o?a.shape[3]:a.shape[1])/(s*s),d=new aS("NHWC"===o?[i,u,l,c]:[i,c,u,l],s,o);return n.runWebGLProgram(d,[a],a.dtype)}};class oS{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=pb(this.outputShape.length);const s=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels;let u="",l="";n&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,l="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${u}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${i};\n int q = d2 - d1 * ${i};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${s}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${o}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${l}\n setOutput(result);\n }\n `}}class iS{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=pb(this.outputShape.length);const o=e.outChannels/e.inChannels,i=e.padInfo.left,u=e.strideWidth,l=e.dilationWidth,c=e.filterHeight,d=e.filterWidth,p=d;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let s=0;s<d;s++)h+=`\n vec4 xTexelC${2*s};\n int xTexelC${2*s}Ready;\n vec4 xTexelC${2*s+1};\n int xTexelC${2*s+1}Ready;\n vec4 xC${s};`;h+=`\n for (int r = 0; r < ${c}; r++) {\n `;for(let s=0;s<d;s++)h+=`\n xTexelC${2*s} = vec4(0.0);\n xTexelC${2*s}Ready = 0;\n xTexelC${2*s+1} = vec4(0.0);\n xTexelC${2*s+1}Ready = 0;\n xC${s} = vec4(0.0);`;h+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let y=0;y<(p+1)/2;y++){const e=2*y;if(h+=`\n xC = xCCorner + ${e*l};\n `,1===u){if(e<d&&(i%2===1?(h+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${e}Ready == 0) {\n xTexelC${e} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${e}.zw = vec2(0.0);\n }\n xTexelC${e}Ready = 1;\n }\n `,h+=1===l&&e>0?`\n xC${e} = vec4(xTexelC${e-2}.zw, xTexelC${e}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${e} = vec4(previous.zw, xTexelC${e}.xy);\n } else {\n xC${e} = vec4(0.0, 0.0, xTexelC${e}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${e}Ready == 0) {\n xTexelC${e} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${e}.zw = vec2(0.0);\n }\n xTexelC${e}Ready = 1;\n }\n\n xC${e} = xTexelC${e};\n `,e+1<d)){const t=i%2===0?s(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(h+=`\n xCOffset = xC + imod(pads[1], 2) + ${t};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${e+1}Ready == 0) {\n xTexelC${e+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${e+1}.zw = vec2(0.0);\n }\n xTexelC${e+1}Ready = 1;\n }\n `,h+=l>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${e+1} = vec4(previous.zw, xTexelC${e+1}.xy);\n } else {\n xC${e+1} = vec4(0.0, 0.0, xTexelC${e+1}.xy);\n }\n `:`\n xC${e+1} = vec4(xTexelC${e}.zw, xTexelC${e+1}.xy);\n `):h+=1===t?`\n xC${e+1} = xTexelC${e};\n `:`\n xCOffset = xC + ${t};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${e+1}Ready == 0) {\n xTexelC${e+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${e+1}.zw = vec2(0.0);\n }\n xTexelC${e+1}Ready = 1;\n }\n\n xC${e+1} = xTexelC${e+1};\n `}}else e<d&&(i%2===1?(h+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${e}Ready == 0) {\n xTexelC${e} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${e}.zw = vec2(0.0);\n }\n xTexelC${e}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${e+1}Ready == 0) {\n xTexelC${e+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${e+1}.zw = vec2(0.0);\n }\n xTexelC${e+1}Ready = 1;\n }\n\n xC${e} = vec4(xTexelC${e}.zw, xTexelC${e+1}.zw);\n `,e+1<d&&(h+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${e+1} = vec4(xTexelC${e+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${e}Ready == 0) {\n xTexelC${e} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${e}.zw = vec2(0.0);\n }\n xTexelC${e}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${e+1}Ready == 0) {\n xTexelC${e+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${e+1}.zw = vec2(0.);\n }\n xTexelC${e+1}Ready = 1;\n }\n\n xC${e} = vec4(\n xTexelC${e}.xy, xTexelC${e+1}.xy);\n `,e+1<d&&(h+=`\n xC${e+1} = vec4(xTexelC${e}.zw, xTexelC${e+1}.zw);\n `)));e<d&&(h+=`\n wTexel = getW(r, ${e}, d1, q);\n dotProd += xC${e} * vec4(wTexel.xz, wTexel.xz);\n `,e+1<d&&(h+=`\n wTexel = getW(r, ${e+1}, d1, q);\n dotProd += xC${e+1} * vec4(wTexel.xz, wTexel.xz);\n `))}h+="\n }\n ",h+="\n }\n ";let f="",m="";n&&(f=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,m="result = activation(result);");const g=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${f}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${o};\n int q = d2 - d1 * ${o};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${h}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${g}\n ${m}\n setOutput(result);\n }\n `}}const uS={kernelName:Oe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:u,dilations:l,dimRoundingMode:c}=r;let d=l;null==d&&(d=[1,1]),i(go(o,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const p=io(a.shape,s.shape,o,d,u,c,!0);let h;h=V().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?new iS(p):new oS(p);const f=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(h,[a,s],"float32",f)}};class lS{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${s} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${a};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class cS{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${s}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${i}; dm++) {\n int d2 = d1 * ${i} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const dS={kernelName:Fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,filterShape:c}=r,d=io(a.shape,c,o,i,u,l,!0),p=new lS(d);return n.runWebGLProgram(p,[a,s],"float32")}};const pS={kernelName:De,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,inputShape:c}=r,d=io(c,s.shape,o,i,u,l,!0),p=new cS(d);return n.runWebGLProgram(p,[a,s],"float32")}};class hS{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const fS={kernelName:Me,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=[...r.shape,...r.shape],s=c(r.shape),o=Hk({inputs:{x:r},backend:n,attrs:{shape:[s]}}),i=new hS(s),u=n.runWebGLProgram(i,[o],o.dtype),l=Hk({inputs:{x:u},backend:n,attrs:{shape:a}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),l}};class mS{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:a,strideWidth:s,filterHeight:o,filterWidth:i,dilationHeight:u,dilationWidth:l}=e,{top:c,left:d}=r;this.userCode=`\n const ivec2 strides = ivec2(${a}, ${s});\n const ivec2 pads = ivec2(${c}, ${d});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${o}; h++) {\n int hIn = hBeg + h * ${u};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${i}; w++) {\n int wIn = wBeg + w * ${l};\n\n if (wIn >= 0 && wIn < ${n}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `}}const gS={kernelName:Pe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r,l=ao(a.shape,s.shape,o,i,"NHWC",u);let c;const d=new mS(l);c=n.runWebGLProgram(d,[a,s],"float32");const p=Hk({inputs:{x:c},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(c),p}};const yS={kernelName:ze,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:a}=r,s=t,{allDims:o,summedDims:i,idDims:u}=lh(a,s.length);dh(o.length,u,s);const{path:l,steps:c}=ph(i,u),p=c.length;let h=null,f=o.length;const m=[];for(let g=0;g<p;++g){for(const e of c[g]){const{permutationIndices:t,expandDims:r}=ch(f,u[e]);let a;hh(t)?a=s[e]:(a=tI({inputs:{x:s[e]},backend:n,attrs:{perm:t}}),m.push(a));const o=a.shape.slice();for(let e=0;e<r.length;++e)o.splice(r[e],0,1);d(a.shape,o)||(a=Hk({inputs:{x:a},backend:n,attrs:{shape:o}}),m.push(a)),null===h?h=a:(h=Uk({inputs:{a,b:h},backend:n}),m.push(h))}g<p-1&&(l[g]>=0&&(h=Jk({inputs:{x:h},backend:n,attrs:{axis:l[g]-(o.length-f),keepDims:!1}}),m.push(h)),f--)}for(const d of m)d!==h&&n.disposeIntermediateTensorInfo(d);return h}},bS=Dk({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n"}),xS={kernelName:Ue,backendName:"webgl",kernelFunc:bS},vS={kernelName:Ge,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:a}=t,s=V().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ik("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",r.shape,a.shape):new wk("return (b >= 0.0) ? a : a * (b + 1.0);",r.shape,a.shape);return n.runWebGLProgram(s,[r,a],r.dtype)}},wS=Mk({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:pw}),kS={kernelName:je,backendName:"webgl",kernelFunc:wS},IS=Dk({opSnippet:`\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = ${qp};\n float a1 = ${Kp};\n float a2 = ${Xp};\n float a3 = ${Yp};\n float a4 = ${Qp};\n float a5 = ${Zp};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),NS={kernelName:He,backendName:"webgl",kernelFunc:IS},SS=Dk({opSnippet:Fk+"\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:hw,dtype:"float32"}),TS={kernelName:qe,backendName:"webgl",kernelFunc:SS};function CS(e){const{inputs:t,attrs:n,backend:r}=e,{dim:a}=n,{input:s}=t,o=s.shape.length,u=s.shape.slice();let l=a;return a<0&&(i(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),u.splice(l,0,1),Hk({inputs:{x:s},backend:r,attrs:{shape:u}})}const $S={kernelName:Ke,backendName:"webgl",kernelFunc:CS},ES="return exp(x) - 1.0;",RS=Dk({opSnippet:ES,packedOpSnippet:ES,cpuKernelImpl:fw}),_S={kernelName:Xe,backendName:"webgl",kernelFunc:RS};class AS{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const a=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=n?`${r}.0`:"1.0";let o;if("real"===e)o="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);o="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${a};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${o}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${r});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${r}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${s};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function OS(e,t,n){const r=n.texData.get(e.dataId),a=c(e.shape),s=e.shape[e.shape.length-1],o=Hk({inputs:{x:e},backend:n,attrs:{shape:[a/s,s]}}),i=o.shape,u=new AS("real",i,t),l=new AS("imag",i,t),d=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:i},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:i}],p=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=Tk({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);const m=Hk({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(f),m}const FS={kernelName:Ye,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return OS(r,!1,n)}};class DS{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}function MS(e){const{backend:t,attrs:n}=e,{shape:r,value:a}=n;let{dtype:s}=n;if(s=s||N(a),"string"===s){const e=v(s,c(r));return e.fill(a),t.makeTensorInfo(r,s,e)}{const e=new DS(r,a),n=[[a]];return t.runWebGLProgram(e,[],s,n)}}const PS={kernelName:Qe,backendName:"webgl",kernelFunc:MS};class LS{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${t} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${t}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const BS={kernelName:Ze,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,a=new LS(n.shape);return r.runWebGLProgram(a,[n],n.dtype)}},VS="return floor(x);",WS=Dk({opSnippet:VS,packedOpSnippet:VS,cpuKernelImpl:mw}),zS={kernelName:Je,backendName:"webgl",kernelFunc:WS},US=Mk({opSnippet:"\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",packedOpSnippet:"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n",dtype:"int32"}),GS={kernelName:et,backendName:"webgl",kernelFunc:US};class HS{constructor(e){this.variableNames=["A"];const t=zy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class jS{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=zy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const qS={kernelName:Zn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,o="undefined"!==typeof HTMLVideoElement&&a instanceof HTMLVideoElement,i="undefined"!==typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],d=[l,u,s];if(i||o){const e=V().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=KS&&e===XS||(XS=e,KS=document.createElement("canvas").getContext("2d",{willReadFrequently:XS})),KS.canvas.width=u,KS.canvas.height=l,KS.drawImage(a,0,0,u,l),a=KS.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=ly.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),a);const h=V().getBool("WEBGL_PACK")?new jS(d):new HS(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}};let KS,XS=V().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const YS={kernelName:tr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=bo(c),g=io(a.shape,s.shape,u,d,l,p,!1,m);let y;const b=[],x=null!=o,v=null!=i,w="leakyrelu"===h,k=()=>{const e=[a,s],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=Hk({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(o,c)),v&&e.push(t(i,c)),w){const t=n.makeTensorInfo([],"float32",Ar(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&V().getBool("WEBGL_EXP_CONV")){const e=h?Pk(h,!0):null,t=new CN(g,x,e,v,w),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],a=k();y=n.runWebGLProgram(t,a,"float32",r)}else if(V().getBool("WEBGL_CONV_IM2COL"))y=_N({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{const e=h?Pk(h,!1):null,t=new SN(g,x,e,v,w),r=k();y=n.runWebGLProgram(t,r,"float32")}else y=RN({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});const I=Hk({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(e=>n.disposeIntermediateTensorInfo(e)),I}};const QS={kernelName:nr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:u}=t,{strides:l,pad:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=[];let g=d;null==g&&(g=[1,1]),i(go(l,g),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${g}'`);const y=io(a.shape,s.shape,l,g,c,p,!0),b=V().getBool("WEBGL_PACK_DEPTHWISECONV")&&y.strideWidth<=2&&y.outChannels/y.inChannels===1,x=h?Pk(h,b):null,v=[a,s],w=null!=o,k=null!=u,I="leakyrelu"===h;if(w&&v.push(o),k&&v.push(u),I){const e=n.makeTensorInfo([],"float32",Ar(f,"float32"));v.push(e),m.push(e)}let N;N=b?new iS(y,w,x,k,I):new oS(y,w,x,k,I);const S=[[y.padInfo.top,y.padInfo.left],[y.strideHeight,y.strideWidth],[y.dilationHeight,y.dilationWidth],[y.inHeight,y.inWidth]],T=n.runWebGLProgram(N,v,"float32",S);return m.forEach(e=>n.disposeIntermediateTensorInfo(e)),T}};class ZS{constructor(e,t,n,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=n;const a=sb(n.length);let s="\n int index;";for(let o=0;o<this.sliceDim;o++)s+=`\n index = round(getIndices(coords[0], ${o}));\n out_of_bounds = out_of_bounds || index < 0;\n out_of_bounds = out_of_bounds || index >= ${this.paramsShape[o]};\n flattenIndex += index * ${this.strides[o]};`;this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${s}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `}}const JS={kernelName:rt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=a.shape,o=s[s.length-1],i=c(r.shape),[u,l,d,p]=vp(r,a),h=Hk({inputs:{x:a},backend:n,attrs:{shape:[l,o]}}),f=Hk({inputs:{x:r},backend:n,attrs:{shape:[c(r.shape)/d,d]}});if(n.shouldExecuteOnCPU([r,a])||"string"===r.dtype){const e=n.readSync(a.dataId),t=n.bufferSync(r),s=gw(e,t,r.dtype,l,o,d,p,r.shape,i);return n.makeTensorInfo(u,r.dtype,s.values)}const m=new ZS(o,p,[l,d],r.shape),g=n.runWebGLProgram(m,[f,h],f.dtype),y=Hk({inputs:{x:g},backend:n,attrs:{shape:u}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),y}};class eT{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=sb(this.rank),r=function(e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;r<e.length;r++)2===r?n.push("index"):n.push(`${t[r]}`);return n.join()}(e);this.userCode=`\n void main() {\n ${n} resRC = getOutputCoords();\n int index = int(getIndices(resRC.x, resRC.z));\n float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${r}));\n }\n `}}function tT(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:o,batchDims:u}=r,l=y(o,a.shape)[0];if(V().get("DEBUG")){const e=n.readSync(s.dataId),t=a.shape[l];for(let n=0;n<e.length;++n){const r=e[n];i(r<=t-1&&r>=0,()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`)}}const d=$h(a,s,l,u),p=c(s.shape),h=[],f=Hk({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=Hk({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);const g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([a,s])||"string"===a.dtype){const e=n.bufferSync(m),t=n.bufferSync(f),r=yw(t,e,g);return h.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(d.outputShape,r.dtype,r.values)}const b=new eT(f.shape,g),x=n.runWebGLProgram(b,[f,m],f.dtype);h.push(x);const v=Hk({inputs:{x},backend:n,attrs:{shape:d.outputShape}});return h.forEach(e=>n.disposeIntermediateTensorInfo(e)),v}const nT={kernelName:nt,backendName:"webgl",kernelFunc:tT},rT=Mk({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:bw,dtype:"bool"}),aT={kernelName:at,backendName:"webgl",kernelFunc:rT},sT=Mk({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:xw}),oT={kernelName:st,backendName:"webgl",kernelFunc:sT};const iT={kernelName:it,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return OS(r,!0,n)}},uT=Dk({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),lT={kernelName:lt,backendName:"webgl",kernelFunc:uT},cT=Dk({opSnippet:"return float(isinf(x));",dtype:"bool"}),dT={kernelName:ct,backendName:"webgl",kernelFunc:cT},pT=Dk({opSnippet:"return float(isnan(x));",dtype:"bool"}),hT={kernelName:dt,backendName:"webgl",kernelFunc:pT},fT=Mk({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:vw,dtype:"bool"}),mT={kernelName:ht,backendName:"webgl",kernelFunc:fT},gT=Mk({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:ww,dtype:"bool"}),yT={kernelName:ft,backendName:"webgl",kernelFunc:gT};const bT={kernelName:mt,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,o=kw(r,a,s);return t.makeTensorInfo([o.length],"float32",o)}},xT=Dk({opSnippet:Fk+"\n return x < 0.0 ? 0./0. : log(x);\n",packedOpSnippet:"\n vec4 result = log(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\n return result;\n",cpuKernelImpl:Iw}),vT={kernelName:gt,backendName:"webgl",kernelFunc:xT},wT=Dk({opSnippet:Fk+"\n return log(1.0 + x);\n"}),kT={kernelName:yt,backendName:"webgl",kernelFunc:wT},IT=Mk({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),NT={kernelName:bt,backendName:"webgl",kernelFunc:IT},ST=Dk({opSnippet:"return float(!(x >= 1.0));"}),TT={kernelName:xt,backendName:"webgl",kernelFunc:ST},CT=Mk({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n",dtype:"bool"}),$T={kernelName:vt,backendName:"webgl",kernelFunc:CT};class ET{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];const s=t,o=e[3]-1;let i;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;i=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${s}; j <= ${s}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${o}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${i};\n setOutput(val);\n }\n `}}class RT{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const s=t,o=e[3]-1;let i;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;i=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${s};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${s}; j <= ${s}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${i};\n setOutput(result);\n }\n `}}const _T={kernelName:wt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:o,alpha:i,beta:u}=r,l=V().getBool("WEBGL_PACK_NORMALIZATION")?new RT(a.shape,s,o,i,u):new ET(a.shape,s,o,i,u);return n.runWebGLProgram(l,[a],a.dtype)}};class AT{constructor(e,t,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=a,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${t})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${t} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${r}) * norm + float(${n});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${r})\n * float(${a})\n * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${a});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `}}const OT={kernelName:kt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:o}=t,{depthRadius:i,bias:u,alpha:l,beta:c}=r,d=new AT(a.shape,i,u,l,c);return n.runWebGLProgram(d,[a,s,o],a.dtype)}};function FT(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=a.shape.length,u=y(s,a.shape);let l=u;const d=Ni(l,i),p=null!=d,h=n.shouldExecuteOnCPU([a]);let f=a;if(p){if(h){const e=n.texData.get(f.dataId).values,t=new Array(i);for(let n=0;n<t.length;n++)t[n]=a.shape[d[n]];const r=Zw(e,a.shape,a.dtype,d,t);f=n.makeTensorInfo(t,a.dtype);n.texData.get(f.dataId).values=r}else f=Zk(a,d,n);l=Ti(l.length,i)}Ii("max",l,i);const[m,g]=wi(f.shape,l);let b,x=m;if(o&&(x=ki(m,u)),h){const e=n.texData.get(f.dataId).values,t=Nw(e,c(g),x,a.dtype);b=n.makeTensorInfo(x,a.dtype);n.texData.get(b.dataId).values=t}else b=function(e,t,n,r){const a=c(t),s=Hk({inputs:{x:e},attrs:{shape:[c(e.shape)/a,a]},backend:r}),o=Xk(s,e.dtype,"max",r),i=Hk({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(f,g,x,n);return p&&n.disposeIntermediateTensorInfo(f),b}const DT={kernelName:It,backendName:"webgl",kernelFunc:FT},MT=Mk({opSnippet:vk+"\n return max(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(max(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+kk+"\n return result;\n",cpuKernelImpl:Sw}),PT={kernelName:Nt,backendName:"webgl",kernelFunc:MT};const LT={kernelName:St,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;Vy(a,"maxPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:l}=r;i(go(o,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const c=so(a.shape,s,o,1,u,l);if(1===c.filterWidth&&1===c.filterHeight&&d(c.inShape,c.outShape))return Nk({inputs:{x:a},backend:n});const p=new MI(c,"max",!1);return n.runWebGLProgram(p,[a],a.dtype)}};const BT={kernelName:Ct,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dataFormat:u,dimRoundingMode:l}=r,c=oo(a.shape,s,o,[1,1,1],i,l,u),d=new PI(c,"max",!1);return n.runWebGLProgram(d,[a],a.dtype)}};class VT{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,a=e.effectiveFilterHeight,s=e.effectiveFilterWidth,o=a-1-e.padInfo.top,i=s-1-e.padInfo.left,u=a*s-1;this.userCode=`\n const ivec2 pads = ivec2(${o}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${a};\n wR += ${r}) {\n float dyR = float(dyRCorner + wR) / ${t}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${s}; wC++) {\n float dyC = float(dyCCorner + wC) / ${n}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${s} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class WT{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=i-1-e.padInfo.front,d=u-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*u*l-1;this.userCode=`\n const ivec3 pads = ivec3(${c}, ${d}, ${p});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${i};\n wD += ${a}) {\n float dyD = float(dyDCorner + wD) / ${t}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${u};\n wR += ${s}) {\n float dyR = float(dyRCorner + wR) / ${n}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${l};\n wC += ${o}) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${h} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${u} * ${l} +\n wR * ${l} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const zT={kernelName:$t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s,{filterSize:i,strides:u,pad:l,dimRoundingMode:c}=r,d=oo(o.shape,i,u,[1,1,1],l,c),p=new PI(d,"max",!0),h=n.runWebGLProgram(p,[o],o.dtype),f=new WT(d),m=n.runWebGLProgram(f,[a,h],o.dtype);return n.disposeIntermediateTensorInfo(h),m}};const UT={kernelName:Tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:o}=t,i=s;Vy([s,o],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=so(i.shape,u,l,1,c,d),h=new MI(p,"max",!0),f=n.runWebGLProgram(h,[i],i.dtype),m=new VT(p),g=n.runWebGLProgram(m,[a,f],i.dtype);return n.disposeIntermediateTensorInfo(f),g}};const GT={kernelName:Et,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:o,includeBatchInIndex:u}=t,l=n;i(4===r.shape.length,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);const c=[1,1];i(go(s,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);const d=so(r.shape,a,s,c,o),[p,h]=function(e,t,n,r){let a=new MI(n,"max",!1);const s=r.runWebGLProgram(a,[e],"float32");return a=new MI(n,"max",!0,!0,t),[s,r.runWebGLProgram(a,[e],"float32")]}(r,u,d,l);return[p,h]}};const HT={kernelName:Rt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:a,axis:s}=t,o=n,i=r.shape.length,u=y(s,r.shape);let l=u;const d=Ni(l,i),p=null!=d,h=o.shouldExecuteOnCPU([r]),f=[];let m=r;if(p){if(h){const e=o.texData.get(m.dataId).values,t=new Array(i);for(let a=0;a<t.length;a++)t[a]=r.shape[d[a]];const n=Zw(e,r.shape,r.dtype,d,t);m=o.makeTensorInfo(t,r.dtype);o.texData.get(m.dataId).values=n}else m=Zk(r,d,o);f.push(m),l=Ti(l.length,i)}Ii("sum",l,i);const[g,b]=wi(m.shape,l);let x=g;a&&(x=ki(g,u));const v=function(e,t,n,r){const a=c(t),s=Hk({inputs:{x:e},attrs:{shape:[c(e.shape)/a,a]},backend:r}),o=Xk(s,"float32","mean",r),i=Hk({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(m,b,x,o);for(const c of f)o.disposeIntermediateTensorInfo(c);return v}};const jT={kernelName:_t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=y(s,a.shape);let l=u;const d=Ni(l,i);let p=a;null!=d&&(p=tI({inputs:{x:a},backend:n,attrs:{perm:d}}),l=Ti(l.length,a.shape.length)),Ii("min",l,i);const[h,f]=wi(p.shape,l),m=Hk({inputs:{x:p},backend:n,attrs:{shape:[-1,c(f)]}}),g=Xk(m,m.dtype,"min",n);let b;if(o){b=Hk({inputs:{x:g},backend:n,attrs:{shape:ki(h,u)}})}else b=Hk({inputs:{x:g},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=d&&n.disposeIntermediateTensorInfo(p),b}},qT=Mk({opSnippet:vk+"\n return min(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(min(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+kk+"\n return result;\n",cpuKernelImpl:Tw}),KT={kernelName:At,backendName:"webgl",kernelFunc:qT};class XT{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=sb(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===n?0:1;this.userCode=1!==r?`\n ${a} start = ${a}(${s});\n ${a} end = ${a}(${o});\n\n void main() {\n ${a} outC = getOutputCoords();\n for (int i = 0; i < ${r}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${u};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};\n }\n }\n ${a} coords = outC - start;\n setOutput(getX(${i}));\n }\n `:`\n int start = ${s};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${u};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${u};\n }\n setOutput(getX(outC - start));\n }\n `}}class YT{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=sb(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=tk("rc",r),u=tk("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,d="reflect"===n?0:1;let p="";if(1===r){const e=`\n ${a} source = rc;\n if (source < start) {\n source = start * 2 - source - ${d};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${d};\n }\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${c});\n ${i[r-1]} += 1;\n if(${l}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${c});\n }\n `}else{const e=`\n ${a} source = rc;\n ${a} lt = ${a}(lessThan(source, start));\n ${a} gte = ${a}(greaterThanEqual(source, end));\n ${a} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${d}) +\n gte * ((end - 1) * 2 - source + ${d});\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${c});\n ${i[r-1]} += 1;\n if(${l}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${c});\n }\n rc = outputLoc;\n ${i[r-2]} += 1;\n if(${i[r-2]} < ${this.outputShape[r-2]}) {\n ${e}\n result[2] = getChannel(getX(${u.join()}), ${c});\n ${i[r-1]} += 1;\n if(${l}) {\n ${e}\n result[3] = getChannel(getX(${u.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${a} start = ${a}(${s});\n const ${a} end = ${a}(${o});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const QT={kernelName:Ot,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:a,mode:s}=n,o=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new YT(r.shape,a,s):new XT(r.shape,a,s);return t.runWebGLProgram(o,[r],r.dtype)}},ZT=Mk({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n bvec4 isNaN = equal(b, vec4(0.0));\n "+kk+"\n return result;\n"}),JT={kernelName:Ft,backendName:"webgl",kernelFunc:ZT};class eC{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${t-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${t-1}));\n }\n `}}const tC=Mk({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),nC={kernelName:We,backendName:"webgl",kernelFunc:tC},rC="return a - b;",aC=Mk({opSnippet:rC,packedOpSnippet:rC,supportsComplex:!0,cpuKernelImpl:Xw}),sC={kernelName:Vn,backendName:"webgl",kernelFunc:aC};function oC(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=y([s],a.shape),i=FT({inputs:{x:a},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),u=ki(i.shape,o),l=Hk({inputs:{x:i},backend:n,attrs:{shape:u}}),c=aC({inputs:{a,b:l},backend:n}),d=SS({inputs:{x:c},backend:n}),p=Jk({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=Hk({inputs:{x:p},backend:n,attrs:{shape:u}}),f=tC({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}const iC={kernelName:Cn,backendName:"webgl",kernelFunc:oC};const uC={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:o,normalized:i}=r,u=i?a:oC({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),l=u.shape[0],c=u.shape[1],d=new eC(l,c,s),p=[[o]],h=n.runWebGLProgram(d,[u],"int32",p);return i||n.disposeIntermediateTensorInfo(u),h}},lC=lk+"\n return -x;\n";const cC={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.texData.get(r.dataId),[t,a]=$w(e.values,r.shape,r.dtype);return n.makeTensorInfo(a,r.dtype,t)}let a;return a=V().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new fk(r.shape,"\n vec4 result = -x;\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"):new uk(r.shape,lC),n.runWebGLProgram(a,[r],r.dtype)}},dC=rd;const pC={kernelName:Bt,backendName:"webgl",kernelFunc:function(e){rr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=r,l=n.readSync(a.dataId),c=n.readSync(s.dataId),{selectedIndices:d}=dC(l,c,o,i,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},hC=ad;const fC={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){rr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,padToMaxOutputSize:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),{selectedIndices:p,validOutputs:h}=hC(c,d,o,i,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},mC=sd;const gC={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){rr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),p=o,h=i,f=u,m=l,{selectedIndices:g,selectedScores:y}=mC(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class yC{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${r}), float(${n}),\n float(index == coords.y)));\n }\n `}}const bC={kernelName:Ut,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:o,onValue:i,offValue:u}=r,l=c(a.shape),d=new yC(l,o,i,u),p=Hk({inputs:{x:a},backend:n,attrs:{shape:[l]}}),h=n.runWebGLProgram(d,[p],s);n.disposeIntermediateTensorInfo(p);const f=Hk({inputs:{x:h},backend:n,attrs:{shape:[...a.shape,o]}});return n.disposeIntermediateTensorInfo(h),f}};function xC(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=sN({inputs:{input:r},backend:n}),t=xC({inputs:{x:e},backend:n}),a=vN({inputs:{input:r},backend:n}),s=xC({inputs:{x:a},backend:n}),o=Tk({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),o}return MS({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const vC={kernelName:Yn,backendName:"webgl",kernelFunc:xC};const wC={kernelName:zt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===a.dtype){const t=sN({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=vN({inputs:{input:a},backend:r}),o=xC({inputs:{x:s},backend:r}),i=Tk({inputs:{real:n,imag:o},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}return MS({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}};const kC={kernelName:Gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return CS({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach(e=>{u(s,e.shape,"All tensors passed to stack must have matching shapes"),i(o===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const l=[],c=t.map(e=>{const t=CS({inputs:{input:e},backend:n,attrs:{dim:a}});return l.push(t),t}),d=IN({inputs:c,backend:n,attrs:{axis:a}});return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}};class IC{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=sb(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${a} start = ${a}(${s});\n ${a} end = ${a}(${o});\n\n void main() {\n ${a} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${a} coords = outC - start;\n setOutput(getX(${i}));\n }\n }\n `:`\n int start = ${s};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class NC{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=sb(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=tk("rc",r),u=tk("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,d=[`${a} rc = outputLoc;`,`${i[r-1]} += 1;\n if(${l}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${i[r-2]} += 1;\n if(${i[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${i[r-1]} += 1;\n if(${l}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let h="";for(let f=0,m=1===r?2:4;f<m;f++)h+=`\n ${d[f]}\n if (${p}) {\n result[${f}] = float(value);\n } else {\n ${a} source = rc - start;\n result[${f}] = getChannel(getX(${u.join()}), ${c});\n }\n `;h+=1===r?"} ":"}}",this.userCode=`\n const ${a} start = ${a}(${s});\n const ${a} end = ${a}(${o});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${h}\n setOutput(result);\n }\n `}}const SC=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;if(0===c(a.shape)){return MS({backend:n,attrs:{shape:s.map((e,t)=>e[0]+a.shape[t]+e[1]),value:o,dtype:a.dtype}})}const i=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new NC(a.shape,s,o):new IC(a.shape,s,o),u=[[o]];return n.runWebGLProgram(i,[a],a.dtype,u)},TC={kernelName:Ht,backendName:"webgl",kernelFunc:SC},CC=Mk({opSnippet:"\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n bvec4 isNaN1 = lessThan(a, vec4(0.0));\n bvec4 isNaN2 = lessThan(floor(b), b);\n bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n "+kk+"\n return result;\n"}),$C={kernelName:jt,backendName:"webgl",kernelFunc:CC};const EC={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=[],l=y(s,a.shape);let d=l;const p=Ni(d,i);let h,f=a;if(null!=p&&(f=tI({inputs:{x:a},backend:n,attrs:{perm:p}}),d=Ti(d.length,i),u.push(f)),Ii("prod",d,i),n.shouldExecuteOnCPU([f])){const e=n.texData.get(f.dataId).values,{outVals:t,outShape:r,outDtype:a}=Rw(f.shape,f.dtype,e,d);h=n.makeTensorInfo(r,a,t)}else{const[e,t]=wi(f.shape,d),r=c(t),s=Hk({inputs:{x:f},backend:n,attrs:{shape:[-1,r]}}),o=Xk(s,da(a.dtype),"prod",n);h=Hk({inputs:{x:o},backend:n,attrs:{shape:e}}),u.push(s),u.push(o)}if(o){u.push(h);const e=ki(h.shape,l);h=Hk({inputs:{x:h},backend:n,attrs:{shape:e}})}return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),h}};const RC={kernelName:Xt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:o}=t,{outputRaggedRank:i}=r,u=a.map(e=>n.readSync(e.dataId)),l=a.map(e=>e.shape),c=n.readSync(s.dataId),d=n.readSync(o.dataId),[p,h,f]=_w(u,l,c,s.shape,s.dtype,d,o.shape,i),m=p.map(e=>n.makeTensorInfo([e.length],"int32",e)),g=n.makeTensorInfo(f,s.dtype,h);return m.concat([g])}};const _C={kernelName:Yt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:a,deltas:s}=t,o=n.readSync(r.dataId),i=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=Aw(o,r.shape,r.dtype,i,a.shape,u,s.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}};const AC={kernelName:Qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:a,values:s,defaultValue:o,rowPartitionTensors:i}=t,{rowPartitionTypes:u}=r,l=n.readSync(a.dataId),c=n.readSync(s.dataId),d=n.readSync(o.dataId),p=i.map(e=>n.readSync(e.dataId)),h=i.map(e=>e.shape),[f,m]=Ow(l,a.shape,c,s.shape,s.dtype,d,o.shape,p,h,u);return n.makeTensorInfo(f,s.dtype,m)}},OC=e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=Fw(r,a,s,o);return t.makeTensorInfo([i.length],o,i)},FC={kernelName:Zt,backendName:"webgl",kernelFunc:OC},DC=Dk({opSnippet:"return 1.0 / x;"}),MC={kernelName:en,backendName:"webgl",kernelFunc:DC},PC=Dk({opSnippet:lk+"\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),LC={kernelName:tn,backendName:"webgl",kernelFunc:PC},BC=Dk({opSnippet:lk+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),VC={kernelName:un,backendName:"webgl",kernelFunc:BC};class WC{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${d};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class zC{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,\n ${i}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${d};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const UC={kernelName:sn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=V().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new zC(a.shape,u,l,s,o):new WC(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};class GC{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,o]=e,i=[n&&s>1?r-1:r,n&&o>1?a-1:a],u=[n&&s>1?s-1:s,n&&o>1?o-1:o],l=i[0]/u[0],c=i[1]/u[1],d=1/l,p=1/c,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${l});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${h});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${s}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${o}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${a-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const HC={kernelName:on,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=new GC(s.shape,a.shape,o);return n.runWebGLProgram(i,[s],s.dtype)}};class jC{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";let p;p=a?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}class qC{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";let p;p=a?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,\n ${i}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `}}const KC={kernelName:rn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=V().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new qC(a.shape,u,l,s,o):new jC(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],a.dtype)}};class XC{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,o]=e,i=[n&&s>1?r-1:r,n&&o>1?a-1:a],u=[n&&s>1?s-1:s,n&&o>1?o-1:o],l=i[0]/u[0],c=i[1]/u[1],d=1/l,p=1/c,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${l});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${h});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${s}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${o}) {\n continue;\n }\n\n float sourceFracRow =\n float(${i[0]}) *\n (float(dyR) / float(${u[0]}));\n\n float sourceFracCol =\n float(${i[1]}) *\n (float(dyC) / float(${u[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${r}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${a}) - 1),\n ${n} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const YC={kernelName:an,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=new XC(s.shape,a.shape,o);return n.runWebGLProgram(i,[s],s.dtype)}};class QC{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const r=e.map((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r)).join(","),a=sb(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class ZC{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=tk("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=sb(n);var i;function u(n){const r=e.map((r,a)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(a,n));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${a}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${o} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${i=r.slice(),u(i)};\n if(${a}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",u(e)}(r.slice())};\n }\n if(${s}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",u(e)}(r.slice())};\n if(${a}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",u(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const JC={kernelName:ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=a.shape.length,i=y(s,a.shape);if(0===o)return Nk({inputs:{x:a},backend:n});const u=V().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ZC(a.shape,i):new QC(a.shape,i);return n.runWebGLProgram(u,[a],a.dtype)}};class e${constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],r=e[2];this.outputShape=e;let a="";a="number"===typeof t?`float outputValue = ${t.toFixed(2)};`:`\n vec3 fill = vec3(${t.join(",")});\n float outputValue = fill[coords[3]];`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${a}\n if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const t$={kernelName:Jn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:o}=t,i=n,u=new e$(r.shape,s),[l,c]=Bp(o,r.shape[1],r.shape[2]),d=[[l,c,Math.sin(a),Math.cos(a)]];return i.runWebGLProgram(u,[r],r.dtype,d)}},n$=Dk({opSnippet:"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n"}),r$={kernelName:cn,backendName:"webgl",kernelFunc:n$},a$=Dk({opSnippet:"return inversesqrt(x);",cpuKernelImpl:Dw}),s$={kernelName:dn,backendName:"webgl",kernelFunc:a$};class o${constructor(e,t,n,r,a,s,o=!0,i=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;const u=sb(a.length),l=sb(s.length);let c="";1===n?c="i":2===n&&(c="i, j");const d=`getIndices(${c})`;let p="";1===r?p="i":2===r&&(p="i, coords[1]");const h=`getUpdates(${p})`;let f="";i&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`\n ${u} strides = ${u}(${a});\n\n void main() {\n ${l} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${e}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${t}; j++) {\n int index = round(${d});\n flattenedIndex += index * ${g};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${h};\n found = true;\n }\n }\n setOutput(mix(${m}, sum, float(found)));\n }\n `}}class i${constructor(e,t,n,r,a,s,o=!0,i=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;const u=sb(a.length),l=sb(s.length);let c="";1===n?c="i":2===n&&(c="i, j");const d=`getIndices(${c})`;let p="";1===r?p="i":2===r&&(p="i, coords[1]");const h=`getUpdates(${p})`;let f="";i&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`\n ${u} strides = ${u}(${a});\n\n void main() {\n ${l} coords = getOutputCoords();\n vec4 sum = vec4(0.);\n vec4 found = vec4(0.);\n for (int i = 0; i < ${e}; i+=2) {\n ivec2 flattenedIndex = ivec2(0);\n for (int j = 0; j < ${t}; j+=2) {\n ivec4 index = round(${d});\n flattenedIndex += index.xz * ${g};\n if (j + 1 < ${t}) {\n flattenedIndex += index.yw * ${y};\n }\n }\n if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\n flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\n vec4 updVals = ${h};\n if (flattenedIndex[0] == coords[0]) {\n sum.xy += updVals.xy;\n found.xy = vec2(1.);\n } else if (flattenedIndex[0] == coords[0] + 1) {\n sum.zw += updVals.xy;\n found.zw = vec2(1.);\n }\n if (flattenedIndex[1] == coords[0]) {\n sum.xy += updVals.zw;\n found.xy = vec2(1.);\n } else if (flattenedIndex[1] == coords[0] + 1) {\n sum.zw += updVals.zw;\n found.zw = vec2(1.);\n }\n }\n }\n setOutput(mix(${m}, sum, found));\n }\n `}}const u$={kernelName:pn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:o}=r,{sliceRank:i,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=pc(0,a,o),p=[d/l,l];if(0===d)return n.makeTensorInfo(o,a.dtype);const h=Hk({inputs:{x:a},backend:n,attrs:{shape:[u,i]}}),f=Hk({inputs:{x:s},backend:n,attrs:{shape:[u,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=V().getBool("WEBGL_PACK")?new i$(u,i,h.shape.length,f.shape.length,c,p):new o$(u,i,h.shape.length,f.shape.length,c,p);const y=n.runWebGLProgram(g,[f,h,m],f.dtype),b=Hk({inputs:{x:y},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class l${constructor(e,t,n,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const a=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,s=2===V().getNumber("WEBGL_VERSION")?"while (left < right) {":a,o="left"===r?"<":"<=";this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${s}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${o} value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int valueIndex = coords[1];\n\n float value = getValues(batch, valueIndex);\n\n setOutput(float(findBound(batch, value)));\n }\n `}}const c$={kernelName:fn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:s}=t,{side:o}=r,i=new l$(a.shape[0],a.shape[1],s.shape[1],o),u=[[a.shape[1]]];return n.runWebGLProgram(i,[a,s],"int32",u)}};class d${constructor(e,t,n){let r,a;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)a="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[],o=[];for(let r=0;r<t.length;r++)o.push(`${n[r]}`),r<e&&s.push(`${n[r]}`);r=s.join(),a=o.join()}const s=sb(n);this.userCode=`\n void main() {\n ${s} resRC = getOutputCoords();\n float cVal = getC(${r});\n if (cVal >= 1.0) {\n setOutput(getA(${a}));\n } else {\n setOutput(getB(${a}));\n }\n }\n `}}const p$={kernelName:mn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,o=new d$(r.shape.length,a.shape,a.shape.length);return n.runWebGLProgram(o,[r,a,s],ca(a.dtype,s.dtype))}},h$=Dk({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = ${jp};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),f$={kernelName:gn,backendName:"webgl",kernelFunc:h$},m$=Dk({opSnippet:Fk+"\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:Pw}),g$={kernelName:wn,backendName:"webgl",kernelFunc:m$},y$=Dk({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),b$={kernelName:vn,backendName:"webgl",kernelFunc:y$},x$=Dk({opSnippet:Fk+"\n return sin(x);\n",packedOpSnippet:`\n vec4 result = sin(x);\n bvec4 isNaN = isnan(x);\n ${kk}\n return result;\n`}),v$={kernelName:bn,backendName:"webgl",kernelFunc:x$},w$=Dk({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),k$={kernelName:xn,backendName:"webgl",kernelFunc:w$},I$=Dk({opSnippet:"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n"}),N$={kernelName:kn,backendName:"webgl",kernelFunc:I$},S$={kernelName:Sn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;i(a.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const u=s.reduce((e,t)=>e*t),l=[[0,0]];l.push(...o);for(let i=1+s.length;i<a.shape.length;++i)l.push([0,0]);const c=[],d=SC({inputs:{x:a},backend:n,attrs:{paddings:l,constantValue:0}}),p=Vp(d.shape,s,u,!1),h=Wp(p.length,s.length,!1),f=zp(d.shape,s,u,!1),m=Hk({inputs:{x:d},backend:n,attrs:{shape:p}}),g=tI({inputs:{x:m},backend:n,attrs:{perm:h}}),y=Hk({inputs:{x:g},backend:n,attrs:{shape:f}});return c.push(d),c.push(m),c.push(g),c.forEach(e=>n.disposeIntermediateTensorInfo(e)),y}};const T$={kernelName:$n,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:a,denseShape:s,defaultValue:o}=t;if(1!==s.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${s.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Values must be a vector, saw:\n ${a.shape}`);if(0!==o.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${o.shape}`);const i=n.readSync(r.dataId),u=n.readSync(a.dataId),l=n.readSync(s.dataId),c=n.readSync(o.dataId)[0],[d,p,h,f,m]=Vw(i,r.shape,r.dtype,u,a.dtype,l,c);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],a.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(e=>Number(e)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}};const C$={kernelName:En,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:a,newShape:s}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape ${a.shape}`);if(1!==s.shape.length)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);const o=Array.from(n.readSync(a.dataId)),i=n.readSync(r.dataId),u=Array.from(n.readSync(s.dataId)),[l,c,d]=Ww(i,r.shape,r.dtype,o,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}};const $$={kernelName:Rn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:s}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${s.shape}`);const o=n.readSync(r.dataId),i=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=zw(o,r.shape,r.dtype,i,u,!0);return n.makeTensorInfo(c,r.dtype,l)}};const E$={kernelName:_n,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:s}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${s.shape}`);const o=n.readSync(r.dataId),i=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=zw(o,r.shape,r.dtype,i,u);return n.makeTensorInfo(c,r.dtype,l)}};const R$={kernelName:An,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:d,outputSize:p}=pc(0,a,i),h=!1;if("string"===s.dtype){const e=n.bufferSync(a),t=n.bufferSync(s),r=Mr(n.readSync(o.dataId)[0]),f=Mw(e,t,i,p,c,l,u,d,r,h);return n.makeTensorInfo(i,f.dtype,f.values)}const f=new o$(l,u,a.shape.length,s.shape.length,d,[p,1],h),m=n.runWebGLProgram(f,[s,a,o],s.dtype),g=Hk({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(m),g}};const _$={kernelName:Tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=r,i=y(o,a.shape)[0],u=mh(a,s,i),l=a.shape.length,c=new Array(l).fill(0),d=a.shape.slice();return u.map(e=>{const t=[...d];t[i]=e;const r=QI({inputs:{x:a},backend:n,attrs:{begin:c,size:t}});return c[i]+=e,r})}},A$="return sqrt(x);",O$=Dk({opSnippet:A$,packedOpSnippet:A$,cpuKernelImpl:Uw}),F$={kernelName:In,backendName:"webgl",kernelFunc:O$},D$={kernelName:Fn,backendName:"webgl",kernelFunc:Dk({opSnippet:"return x * x;"})},M$="return (a - b) * (a - b);",P$=Mk({opSnippet:M$,packedOpSnippet:M$}),L$={kernelName:On,backendName:"webgl",kernelFunc:P$};const B$={kernelName:Dn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");const s=Eh(n.readSync(a.dataId)),o=Gw(s,"string",r);return n.makeTensorInfo(a.shape,"string",o)}};const V$={kernelName:Qn,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,a=lk+`\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,s=new uk(r.shape,a);return n.runWebGLProgram(s,[r],r.dtype)}};class W${constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=sb(n.length),s=sb(n.length);let o="";if(1===r)o="coords * strides + begin";else{let e=0;o=n.map((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`)).join(",")}this.userCode=`\n ${a} begin = ${a}(${e});\n ${a} strides = ${a}(${t});\n\n void main() {\n ${s} coords = getOutputCoords();\n setOutput(getX(${o}));\n }\n `}}const z$={kernelName:Mn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:u,beginMask:l,endMask:c,ellipsisMask:d,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:v,strides:w}=Tp(a.shape,s,o,u,l,c,d,p,h);let k;if(g)k=Hk({inputs:{x:a},backend:n,attrs:{shape:m}});else if(y||b){i(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);const e=kp(x,v,w),t=QI({inputs:{x:a},backend:n,attrs:{begin:x,size:e}});k=Hk({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([a])){const e=n.readSync(a.dataId),t=Ps(a.shape,a.dtype,e),r=Hw(f,t,w,x);k=n.makeTensorInfo(m,a.dtype,r.values)}else{const e=new W$(x,w,f);k=n.runWebGLProgram(e,[a],a.dtype)}}const I=Hk({inputs:{x:k},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(k),I}};const U$={kernelName:Pn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:s,leftPad:o,rightPad:i,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:d}=t,p=n.readSync(c.dataId),h=n.readSync(d.dataId),[f,m]=jw(p,h,a,s,o,i,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}};const G$={kernelName:Ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:s,delimiter:o}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");if(1!==s.shape.length)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(0!==o.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);const i=n.readSync(s.dataId),u=n.readSync(o.dataId)[0],[l,c,d]=qw(i,u,a),p=c.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(d))]}};const H$={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:a}=r,{input:s}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");const o=n.readSync(s.dataId),i=Kw(o,a);return n.makeTensorInfo(s.shape,"int32",i)}},j$=Dk({opSnippet:"return tan(x);"}),q$={kernelName:Wn,backendName:"webgl",kernelFunc:j$},K$=Dk({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),X$={kernelName:zn,backendName:"webgl",kernelFunc:K$};const Y$={kernelName:hn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{tensor:a,indices:s,updates:o}=t,{sliceRank:i,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=pc(0,s,a.shape),p=[d/l,l];if(0===d)return n.makeTensorInfo(a.shape,s.dtype);const h=Hk({inputs:{x:s},backend:n,attrs:{shape:[u,i]}}),f=Hk({inputs:{x:o},backend:n,attrs:{shape:[u,l]}}),m=Hk({inputs:{x:a},backend:n,attrs:{shape:p}}),g=new o$(u,i,h.shape.length,f.shape.length,c,p,!1,!0),y=n.runWebGLProgram(g,[f,h,m],m.dtype),b=Hk({inputs:{x:y},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class Q${constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;const r=sb(this.rank),a=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let a=0;a<e.length;a++)r.push(`imod(${n[a]}, ${e[a]})`);return r.join()}(e);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${a}));\n }\n `}}function Z$(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reps:s}=r;if("string"===a.dtype||a.shape.length>5){const e=n.readSync(a.dataId),t="string"===a.dtype?e.map(e=>Mr(e)):e,r=Ps(a.shape,a.dtype,t),o=Yw(r,s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}const o=new Q$(a.shape,s);return n.runWebGLProgram(o,[a],a.dtype)}const J$={kernelName:Un,backendName:"webgl",kernelFunc:Z$};class eE{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n "}}class tE{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\n }\n "}}function nE(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function rE(e){let t=1;for(;t<e;)t*=2;return t}const aE={kernelName:Gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:o}=r,i=V().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=V().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=a.shape,d=l[l.length-1];if(n.shouldExecuteOnCPU([a])||d<i||s>u){const e=n.readSync(a.dataId),[t,r]=Qw(e,l,a.dtype,s,o);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(r.shape,r.dtype,r.values)]}if(0===s)return l[l.length-1]=0,[n.makeTensorInfo(l,a.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(1===d)return[a,MS({attrs:{shape:l,dtype:"int32",value:0},backend:n})];const p=n.texData.get(a.dataId),h=null!==p&&p.isPacked,f=h?n.unpackTensor(a):a,m=c(l)/d,g=Hk({inputs:{x:f},attrs:{shape:[m,d]},backend:n});h&&nE(n,f);const y=rE(s),b=rE(d);let x=null;const v=()=>null===x?[g,g]:[g,x],w=(e,t,r)=>{const a=v(),s=new eE(r),o=[[d],[null===x?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],i=x;x=n.runWebGLProgram(s,a,"int32",o),nE(n,i)};for(let c=1;c<y;c*=2){const e=2*c;for(let t=c;t>=1;t/=2)w(e,t,[m,b])}for(let c=b;c>y;c/=2){const e=v(),t=new tE([m,c/2]),r=[[d],[null===x?1:0],[y]],a=x;x=n.runWebGLProgram(t,e,"int32",r),nE(n,a);const s=y/2,o=2*s;for(let n=s;n>=1;n/=2)w(o,n,x.shape)}let k=x;x=QI({inputs:{x},backend:n,attrs:{begin:0,size:[m,s]}}),nE(n,k);let I=tT({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});nE(n,g);const N=l.slice(0,-1);N.push(s),k=x,x=Hk({inputs:{x},attrs:{shape:N},backend:n}),nE(n,k);const S=I;return I=Hk({inputs:{x:I},attrs:{shape:N},backend:n}),nE(n,S),[I,x]}};class sE{constructor(e,t,n,r,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;const o="nearest"===n?1:2;let i;switch(r){case"constant":default:i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${i} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${i} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${i} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${a});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${a});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${t}));\n float mapY = mapCoord(inY, float(${e}));\n\n if (${o} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const oE={kernelName:Hn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,transforms:s}=t,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=r,[c,d,p,h]=a.shape,[f,m]=null!=l?l:[d,p],g=new sE(d,p,o,i,u,[c,f,m,h]);return n.runWebGLProgram(g,[a,s],"float32")}};const iE={kernelName:qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;Vy(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=r.readSync(s.dataId),{outputValues:i,outputShape:u,indices:l}=Jw(o,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}};const uE={kernelName:Kn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a,i=o.shape.length,u=a.shape[s],l=new Array(i-1);let c=0;for(let m=0;m<i;m++)m!==s&&(l[c++]=o.shape[m]);const d=[],p=new Array(i).fill(0),h=o.shape.slice();h[s]=1;const f=new Array(u);for(let m=0;m<f.length;m++){p[s]=m;const e=QI({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),t=Hk({inputs:{x:e},backend:n,attrs:{shape:l}});f[m]=t,d.push(e)}return d.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}};class lE{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,a=e.inSize,s=e.numSegments,o=s*Math.ceil(a/n);this.outputShape=[r,o];const i=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ";let c="";a%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `);let d="";a%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${c}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${d}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${s})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${s})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${i}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${l}\n }\n\n int inIdx = inOffset + ${i};\n if (${1===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${l}\n } else if (${2===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${l}\n } else if (${3===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${l}\n }\n setOutput(sumValue);\n }\n `}}const cE={kernelName:Xn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:o}=r,i=a.shape.length,u=[];let l=0;const d=Ni([l],i);let p=a;null!=d&&(p=tI({inputs:{x:a},backend:n,attrs:{perm:d}}),u.push(p),l=Ti(1,i)[0]);const h=function(e,t,n){const r=[],a=e.length;for(let s=0;s<a;s++)s!==t?r.push(e[s]):r.push(n);return r}(p.shape,l,o),f=c([p.shape[l]]),m=Hk({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}});u.push(m);const g=da(a.dtype),y=(e,t,r,a,s)=>{const o=e.shape[0],i=e.shape[1],l=function(e,t){let n,r=!1;for(e<=30?(n=e,r=!0):n=T(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=T(e,n+1);return n}(i,s),c=new lE({windowSize:l,inSize:i,batchSize:o,numSegments:s},t),d=n.compileAndRun(c,[e,r],a);if(u.push(d),d.shape[1]===s)return d;const p=OC({backend:n,attrs:{start:0,stop:s,step:1,dtype:"float32"}}),h=Z$({inputs:{x:p},backend:n,attrs:{reps:[i/l]}});u.push(p),u.push(h);return y(d,t,h,a,s)},b=Hk({inputs:{x:y(m,"unsortedSegmentSum",s,g,o)},backend:n,attrs:{shape:h}});let x=b;if(null!=d){u.push(b);const e=Si(d);x=tI({inputs:{x},backend:n,attrs:{perm:e}})}return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),x}},dE=[aI,oI,uI,cI,hI,gI,yI,bI,NI,SI,CI,EI,_I,OI,DI,LI,BI,zI,UI,GI,qI,JI,eN,tN,nN,iN,cN,hN,Ck,gN,NN,AN,PN,BN,VN,WN,zN,GN,jN,KN,tS,nS,rS,sS,uS,dS,pS,fS,gS,yS,xS,vS,kS,NS,TS,$S,_S,FS,PS,BS,zS,GS,qS,YS,QS,JS,nT,aT,oT,Sk,iT,wN,lT,dT,hT,Rk,mT,yT,bT,vT,kT,NT,TT,$T,_T,OT,DT,PT,LT,BT,zT,UT,GT,HT,jT,KT,QT,JT,uC,Gk,cC,pC,fC,gC,aN,bC,wC,kC,TC,$C,Ok,EC,RC,_C,AC,FC,oN,nC,MC,LC,VC,jk,UC,HC,KC,YC,JC,t$,r$,s$,u$,c$,p$,f$,g$,b$,v$,k$,ZI,iC,N$,S$,T$,C$,$$,E$,R$,_$,F$,D$,L$,B$,V$,z$,U$,G$,H$,sC,eI,q$,X$,Y$,J$,aE,oE,nI,iE,uE,cE,vC];for(const fO of dE)lr(fO);const pE=wc;class hE extends n{nextDataId(){return hE.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new t(this,La())}write(e,t,n){this.firstUse&&(this.firstUse=!1,V().get("IS_NODE")&&rr("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&I(n[0])){const a=n.map(e=>Dr(e));r=this.write(a,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,r,a){this.data.set(e,{values:t,dtype:r,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return Jp(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map(e=>Mr(e));return Ps(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ps(e.shape,e.dtype,t)}makeOutput(e,t,n){return La().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Fr();e();return{kernelMs:Fr()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){_b([e],"where");const t=this.readSync(e.dataId);return pE(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}hE.nextDataId=0,Ga("cpu",()=>new hE,1);const fE=rx(Ue,e=>e>=0?e:Math.exp(e)-1),mE={kernelName:Ue,backendName:"cpu",kernelFunc:fE};function gE(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r;_b([a],"leakyRelu");const o=c(a.shape),i=n.data.get(a.dataId).values,u=x("float32",o);for(let l=0;l<i.length;l++)u[l]=i[l]<0?s*i[l]:i[l];return n.makeTensorInfo(a.shape,"float32",u)}const yE={kernelName:pt,backendName:"cpu",kernelFunc:gE},bE=Fb((e,t)=>e<0?t*e:e);function xE(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;_b([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=bE(r.shape,a.shape,s,o,"float32");return n.makeTensorInfo(u,"float32",i)}const vE={kernelName:qt,backendName:"cpu",kernelFunc:xE},wE=rx(tn,e=>Math.max(0,e)),kE={kernelName:tn,backendName:"cpu",kernelFunc:wE},IE=rx(un,e=>Math.min(Math.max(0,e),6)),NE={kernelName:un,backendName:"cpu",kernelFunc:IE};function SE(e,t,n,r,a){if("linear"===n)return Lb({inputs:{x:t},backend:e});if("relu"===n)return wE({inputs:{x:t},backend:e});if("elu"===n)return fE({inputs:{x:t},backend:e});if("relu6"===n)return IE({inputs:{x:t},backend:e});if("prelu"===n)return xE({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return gE({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return Tv({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function TE(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=c(a.shape),u=g(s,o),l=c(u);i(o===l,()=>`The new shape (${u}) has ${l} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(a.dataId);const d=n.data.get(a.dataId);if(null!=d.complexTensorInfos){const e=d.complexTensorInfos.real,t=d.complexTensorInfos.imag;e.shape=u,t.shape=u}return{dataId:a.dataId,shape:u,dtype:a.dtype}}const CE={kernelName:nn,backendName:"cpu",kernelFunc:TE};function $E(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:u}=r;_b([a,s],"matMul");const l=a.shape.length,d=s.shape.length,p=o?a.shape[l-2]:a.shape[l-1],h=u?s.shape[d-1]:s.shape[d-2],f=o?a.shape[l-1]:a.shape[l-2],m=u?s.shape[d-2]:s.shape[d-1],g=a.shape.slice(0,-2),y=s.shape.slice(0,-2),b=c(g),x=c(y),v=li(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([f,m]);i(p===h,()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${u} must match.`);const w=u?[x,m,h]:[x,h,m],k=TE({inputs:{x:a},backend:n,attrs:{shape:o?[b,p,f]:[b,f,p]}}),I=TE({inputs:{x:s},backend:n,attrs:{shape:w}}),N=o?k.shape[1]:k.shape[2],S=o?k.shape[2]:k.shape[1],T=u?I.shape[1]:I.shape[2],$=Math.max(b,x),E=n.data.get(k.dataId).values,R=n.data.get(I.dataId).values,_=C(k.shape),A=C(I.shape),[O,F,D]=o?[_[0],1,_[1]]:[_[0],_[1],1],[M,P,L]=u?[1,A[1],A[0]]:[A[1],1,A[0]],B=S*T,V=Ps([$,S,T],k.dtype),W=V.values,z=n.blockSize;for(let i=0;i<$;i++){const e=i%b,t=i%x;for(let n=0;n<S;n+=z){const r=Math.min(n+z,S);for(let a=0;a<T;a+=z){const s=Math.min(a+z,T);for(let o=0;o<N;o+=z){const u=Math.min(o+z,N);for(let l=n;l<r;l++)for(let n=a;n<s;n++){let r=0;for(let a=o;a<u;a++){r+=E[e*O+l*F+a*D]*R[a*M+n*P+t*L]}W[i*B+(l*T+n)]+=r}}}}}return n.disposeIntermediateTensorInfo(k),n.disposeIntermediateTensorInfo(I),n.makeTensorInfo(v,V.dtype,V.values)}const EE={kernelName:le,backendName:"cpu",kernelFunc:$E};const RE={kernelName:er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;let p,h,f;const m=[];p=$E({inputs:{a,b:s},attrs:{transposeA:u,transposeB:l},backend:n}),o&&(h=Xb({inputs:{a:p,b:o},backend:n}),m.push(p),p=h),c&&(f=SE(n,p,c,i,d),m.push(p),p=f);for(const g of m)n.disposeIntermediateTensorInfo(g);return p}},_E=rx(j,e=>Math.acos(e)),AE={kernelName:j,backendName:"cpu",kernelFunc:_E},OE=rx(q,e=>Math.acosh(e)),FE={kernelName:q,backendName:"cpu",kernelFunc:OE};const DE={kernelName:X,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;_b(t,"addN");const a=r.map(e=>n.data.get(e.dataId).values),s=Ps(r[0].shape,r[0].dtype),o=s.values;for(let i=0;i<r.length;i++){const e=a[i];for(let t=0;t<o.length;t++)o[t]+=e[t]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}};const ME={kernelName:Y,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;_b(a,"all");const i=y(s,a.shape);let u=i;const l=Ni(u,a.shape.length);let d=a;null!=l&&(d=sv({inputs:{x:a},backend:n,attrs:{perm:l}}),u=Ti(u.length,a.shape.length)),Ii("all",u,d.shape.length);const[p,h]=wi(d.shape,u),f=c(h),m=_(c(p),d.dtype),g=n.data.get(d.dataId).values;for(let c=0;c<m.length;++c){const e=c*f;let t=g[e];for(let n=0;n<f;++n){const r=g[e+n];t=t&&r}m[c]=t}null!=l&&n.disposeIntermediateTensorInfo(d);const b=n.makeTensorInfo(p,d.dtype,m);if(o){const e=TE({inputs:{x:b},backend:n,attrs:{shape:ki(p,i)}});return n.disposeIntermediateTensorInfo(b),e}return b}};const PE={kernelName:Q,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;_b(a,"any");const i=y(s,a.shape);let u=i;const l=Ni(u,a.shape.length);let d=a;null!=l&&(d=sv({inputs:{x:a},backend:n,attrs:{perm:l}}),u=Ti(u.length,a.shape.length)),Ii("any",u,d.shape.length);const[p,h]=wi(d.shape,u),f=c(h),m=_(c(p),d.dtype),g=n.data.get(d.dataId).values;for(let c=0;c<m.length;++c){const e=c*f;let t=g[e];for(let n=0;n<f;++n){const r=g[e+n];t=t||r}m[c]=t}null!=l&&n.disposeIntermediateTensorInfo(d);const b=n.makeTensorInfo(p,d.dtype,m);if(o){const e=TE({inputs:{x:b},backend:n,attrs:{shape:ki(p,i)}});return n.disposeIntermediateTensorInfo(b),e}return b}};const LE={kernelName:Z,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;_b(a,"argMax");let o=y(s,a.shape);const i=Ni(o,a.shape.length);let u=a;const l=[];null!=i&&(u=sv({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Ti(o.length,u.shape.length)),o=[o[0]],Ii("argMax",o,u.shape.length);const[d,p]=wi(u.shape,o),h=_(c(d),"int32"),f=c(p),m=n.data.get(u.dataId).values;for(let c=0;c<h.length;++c){const e=c*f;let t=m[e],n=0;for(let r=0;r<f;++r){const a=m[e+r];a>t&&(t=a,n=r)}h[c]=n}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(d,"int32",h)}};const BE={kernelName:J,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;_b(a,"argMin");let o=y(s,a.shape);const i=Ni(o,a.shape.length);let u=a;const l=[];null!=i&&(u=sv({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Ti(o.length,u.shape.length)),o=[o[0]],Ii("argMin",o,u.shape.length);const[d,p]=wi(u.shape,o),h=_(c(d),"int32"),f=c(p),m=n.data.get(u.dataId).values;for(let c=0;c<h.length;++c){const e=c*f;let t=m[e],n=0;for(let r=0;r<f;++r){const a=m[e+r];a<t&&(t=a,n=r)}h[c]=n}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(d,"int32",h)}},VE=rx(ee,e=>Math.asin(e)),WE={kernelName:ee,backendName:"cpu",kernelFunc:VE},zE=rx(te,e=>Math.asinh(e)),UE={kernelName:te,backendName:"cpu",kernelFunc:zE},GE=rx(ne,e=>Math.atan(e)),HE={kernelName:ne,backendName:"cpu",kernelFunc:GE},jE=Fb((e,t)=>Math.atan2(e,t)),qE=Hb(ae,jE),KE={kernelName:ae,backendName:"cpu",kernelFunc:qE},XE=rx(re,e=>Math.atanh(e)),YE={kernelName:re,backendName:"cpu",kernelFunc:XE};function QE(e,t,n,r,a,s){const o=a.strideHeight,i=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,d=a.effectiveFilterWidth,p=a.padInfo.top,h=a.padInfo.left,f="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Ps(a.outShape,n),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let v=0;v<a.batchSize;++v){const t=v*y,n=v*r[0];for(let m=0;m<a.inChannels;++m)for(let y=0;y<a.outHeight;++y){const v=y*o-p,w=Math.max(0,v),k=Math.min(a.inHeight,c+v),I=t+y*b;for(let t=0;t<a.outWidth;++t){const o=t*i-h,c=Math.max(0,o),p=Math.min(a.inWidth,d+o);let y=f,b=0,v=0;for(let t=w;t<k;t+=u){const a=n+t*r[1];for(let t=c;t<p;t+=l){const n=e[a+t*r[2]+m];"max"===s&&n>y?y=n:"avg"===s&&(b+=n,v++)}if(isNaN(y))break}g[I+t*x+m]="avg"===s?b/v:y}}}return m}function ZE(e,t,n,r,a=!1,s=!1){const o=Ps(r.outShape,"int32"),i=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,d=r.effectiveFilterHeight,p=r.effectiveFilterWidth,h=r.padInfo.top,f=r.padInfo.left,m=Ps(t,n,e);for(let g=0;g<r.batchSize;++g)for(let e=0;e<r.inChannels;++e)for(let t=0;t<r.outHeight;++t){const n=t*i-h;let y=n;for(;y<0;)y+=l;const b=Math.min(r.inHeight,d+n);for(let i=0;i<r.outWidth;++i){const d=i*u-f;let h=d;for(;h<0;)h+=c;const x=Math.min(r.inWidth,p+d);let v=Number.NEGATIVE_INFINITY,w=-1;for(let t=y;t<b;t+=l){const o=t-n;for(let n=h;n<x;n+=c){const i=n-d,u=m.get(g,t,n,e);u>v&&(v=u,w=a?s?((g*r.inHeight+t)*r.inWidth+n)*r.inChannels+e:(t*r.inWidth+n)*r.inChannels+e:o*p+i)}}o.set(w,g,t,i,e)}}return o}function JE(e,t,n,r,a,s){const o=a.strideDepth,i=a.strideHeight,u=a.strideWidth,l=a.dilationDepth,c=a.dilationHeight,d=a.dilationWidth,p=a.effectiveFilterDepth,h=a.effectiveFilterHeight,f=a.effectiveFilterWidth,m=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,b="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Ps(a.outShape,n),v=x.values,w=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],k=a.outShape[2]*a.outShape[3]*a.outShape[4],I=a.outShape[3]*a.outShape[4],N=a.outShape[4];for(let S=0;S<a.batchSize;++S){const t=S*w,n=S*r[0];for(let x=0;x<a.inChannels;++x)for(let w=0;w<a.outDepth;++w){const S=w*o-m;let T=S;for(;T<0;)T+=l;const C=Math.min(a.inDepth,p+S),$=t+w*k;for(let t=0;t<a.outHeight;++t){const o=t*i-g;let p=o;for(;p<0;)p+=c;const m=Math.min(a.inHeight,h+o),w=$+t*I;for(let t=0;t<a.outWidth;++t){const o=t*u-y;let i=o;for(;i<0;)i+=d;const h=Math.min(a.inWidth,f+o),g=w+t*N;let k=b,I=0,S=0;for(let t=T;t<C;t+=l){const a=n+t*r[1];for(let t=p;t<m;t+=c){const n=a+t*r[2];for(let t=i;t<h;t+=d){const a=e[n+t*r[3]+x];if("max"===s&&a>k?k=a:"avg"===s&&(I+=a,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}v[g+x]="avg"===s?I/Math.max(S,1):k}}}}return x}const eR={kernelName:se,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;_b(a,"avgPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:l}=r;i(go(o,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const c=so(a.shape,s,o,1,u,l);let p;if(1===c.filterWidth&&1===c.filterHeight&&d(c.inShape,c.outShape))p=Lb({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=C(a.shape),r=QE(e,a.shape,a.dtype,t,c,"avg");p=n.makeTensorInfo(c.outShape,a.dtype,r.values)}return p}};const tR={kernelName:ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r;_b(a,"avgPool3d");const c=oo(a.shape,s,o,1,i,u,l),d=JE(n.data.get(a.dataId).values,a.shape,a.dtype,C(a.shape),c,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}};const nR={kernelName:ue,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r;_b([a,s],"avgPool3DGrad");const c=oo(s.shape,o,i,1,u,l),d=c.strideDepth,p=c.strideHeight,h=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,v=c.effectiveFilterDepth,w=c.effectiveFilterHeight,k=c.effectiveFilterWidth,I=v-1-c.padInfo.front,N=k-1-c.padInfo.left,S=w-1-c.padInfo.top,T=Ps(s.shape,"float32"),C=1/(f*m*g),$=n.bufferSync(a);for(let E=0;E<c.batchSize;++E)for(let e=0;e<c.inChannels;++e)for(let t=0;t<c.inDepth;++t)for(let n=0;n<c.inHeight;++n)for(let r=0;r<c.inWidth;++r){const a=t-I,s=n-S,o=r-N;let i=0;for(let t=0;t<v;t+=y){const n=(a+t)/d;if(!(n<0||n>=c.outDepth||Math.floor(n)!==n))for(let t=0;t<w;t+=b){const r=(s+t)/p;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let t=0;t<k;t+=x){const a=(o+t)/h;if(a<0||a>=c.outWidth||Math.floor(a)!==a)continue;i+=$.get(E,n,r,a,e)}}}T.set(i*C,E,t,n,r,e)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}};const rR={kernelName:oe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s;_b([a,s],"avgPoolGrad");const{filterSize:i,strides:u,pad:l}=r,c=so(o.shape,i,u,1,l),d=c.strideHeight,p=c.strideWidth,h=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,v=y-1-c.padInfo.top,w=Ps(o.shape,"float32"),k=1/(h*f),I=n.data.get(a.dataId).values,N=Ps(a.shape,"float32",I);for(let S=0;S<c.batchSize;++S)for(let e=0;e<c.inChannels;++e)for(let t=0;t<c.inHeight;++t)for(let n=0;n<c.inWidth;++n){const r=t-v,a=n-x;let s=0;for(let t=0;t<y;t+=m){const n=(r+t)/d;if(!(n<0||n>=c.outHeight||Math.floor(n)!==n))for(let t=0;t<b;t+=g){const r=(a+t)/p;if(r<0||r>=c.outWidth||Math.floor(r)!==r)continue;s+=N.get(S,n,r,e)}}w.set(s*k,S,t,n,e)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}};const aR={kernelName:tt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,scale:s,offset:o,mean:u,variance:l}=t;i(u.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),i(null==o||u.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),i(null==s||u.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),_b([a,u,l,s,o],"batchNorm");let{varianceEpsilon:c}=r;null==c&&(c=.001);const d=n.data.get(a.dataId).values,p=n.data.get(u.dataId).values,h=n.data.get(l.dataId).values,f=s?n.data.get(s.dataId).values:new Float32Array([1]),m=o?n.data.get(o.dataId).values:new Float32Array([0]),g=new Float32Array(d.length),y=m.length,b=f.length,x=h.length,v=p.length;let w=0,k=0,I=0,N=0;for(let i=0;i<d.length;++i)g[i]=m[w++]+(d[i]-p[k++])*f[I++]/Math.sqrt(h[N++]+c),w>=y&&(w=0),k>=v&&(k=0),I>=b&&(I=0),N>=x&&(N=0);return n.makeTensorInfo(a.shape,a.dtype,g)}};const sR={kernelName:ce,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;_b([a],"batchToSpaceND");const i=s.reduce((e,t)=>e*t),u=Vp(a.shape,s,i),l=Wp(u.length,s.length),c=zp(a.shape,s,i),d=Up(o,s.length),p=Gp(c,o,s.length),h=TE({inputs:{x:a},backend:n,attrs:{shape:u}}),f=sv({inputs:{x:h},backend:n,attrs:{perm:l}}),m=TE({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Ev({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const oR={kernelName:de,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o}=r,i=Qb(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,i)}};const iR={kernelName:he,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,i=li(Array.from(s),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}},uR=rx(ge,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),lR={kernelName:ge,backendName:"cpu",kernelFunc:uR},cR={kernelName:be,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(c(t.shape)),a=n.data.get(t.dataId),s=a.complexTensorInfos.real,o=a.complexTensorInfos.imag,i=n.data.get(s.dataId).values,u=n.data.get(o.dataId).values;for(let l=0;l<i.length;l++){const e=i[l],t=u[l];r[l]=Math.hypot(e,t)}return n.makeOutput(r,t.shape,"float32")}};function dR(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.imag,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}const pR={kernelName:ut,backendName:"cpu",kernelFunc:dR};function hR(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=y(a,t[0].shape)[0],o=t.map(e=>e.shape);Rp(o,s);let i=_p(t.map(e=>e.shape),s);if(0===c(i))return n.makeTensorInfo(i,t[0].dtype,[]);const u=t.filter(e=>c(e.shape)>0);if(1===u.length)return Lb({inputs:{x:u[0]},backend:n});if("complex64"===u[0].dtype){const e=u.map(e=>Vb({inputs:{input:e},backend:n})),t=u.map(e=>dR({inputs:{input:e},backend:n})),r=hR({inputs:e,backend:n,attrs:{axis:s}}),a=hR({inputs:t,backend:n,attrs:{axis:s}}),o=Db({inputs:{real:r,imag:a},backend:n});return e.forEach(e=>n.disposeIntermediateTensorInfo(e)),t.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),o}const l=u.map(e=>{const t=c(e.shape.slice(s));return TE({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})}),d=l.map(e=>({vals:n.data.get(e.dataId).values,shape:e.shape}));i=_p(l.map(e=>e.shape),1);const p=1===l[0].shape[0],h=ux(d,i,t[0].dtype,p),f=_p(u.map(e=>e.shape),s),m=n.makeTensorInfo(f,t[0].dtype,h);return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),m}const fR={kernelName:xe,backendName:"cpu",kernelFunc:hR};function mR(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r;_b([a,s],"conv2d");const d=bo(u),p=io(a.shape,s.shape,o,l,i,c,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,v=new qr(p.outShape,a.dtype),w=C(a.shape),k=C(s.shape),I=w[0],N=x?w[1]:w[2],S=x?w[2]:1,T=x?1:w[1],$=v.strides[0],E=x?v.strides[1]:v.strides[2],R=x?v.strides[2]:1,_=x?1:v.strides[1],A=n.data.get(a.dataId).values,O=n.data.get(s.dataId).values,F=v.values;for(let C=0;C<p.batchSize;++C){const e=C*I,t=C*$;for(let n=0;n<p.outHeight;++n){const r=t+n*E,a=n*p.strideHeight-b;for(let t=0;t<h;++t){const n=a+t*m;if(n<0||n>=p.inHeight)continue;const s=t*k[0],o=e+n*N;for(let e=0;e<p.outWidth;++e){const t=r+e*R,n=e*p.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=p.inWidth)continue;const a=o+r*S;let i=s+e*k[1];for(let e=0;e<p.inChannels;++e){const n=A[a+e*T];for(let e=0;e<p.outChannels;++e)F[t+e*_]+=n*O[i+e];i+=p.outChannels}}}}}}return n.makeTensorInfo(v.shape,v.dtype,F)}const gR={kernelName:ve,backendName:"cpu",kernelFunc:mR};const yR={kernelName:we,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,filterShape:c}=r;_b([a,s],"conv2dBackpropFilter");const d=bo(u),p=io(a.shape,c,o,1,i,l,!1,d),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new qr(p.filterShape,"float32"),x=p.padInfo.left,v=p.padInfo.top,w=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,I=new qr(a.shape,a.dtype,w),N=new qr(s.shape,s.dtype,k);for(let S=0;S<m;++S){const e=Math.max(0,Math.ceil((v-S)/h)),t=Math.min(p.outHeight,(p.inHeight+v-S)/h);for(let n=0;n<g;++n){const r=Math.max(0,Math.ceil((x-n)/f)),a=Math.min(p.outWidth,(p.inWidth+x-n)/f);for(let s=0;s<p.inChannels;++s)for(let o=0;o<p.outChannels;++o){let i=0;for(let u=0;u<p.batchSize;++u)for(let l=e;l<t;++l){const e=S+l*h-v;for(let t=r;t<a;++t){const r=n+t*f-x;i+=y?I.get(u,e,r,s)*N.get(u,l,t,o):I.get(u,s,e,r)*N.get(u,o,l,t)}}b.set(i,S,n,s,o)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const bR={kernelName:ke,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r;_b([a,s],"conv2dBackpropInput");const d=C(s.shape),p=C(a.shape);let h=bo(l);const f=io(o,s.shape,i,1,u,c,!1,h),m=new qr(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[x,v,w]=d,{batchSize:k,filterHeight:I,filterWidth:N,inChannels:S,inHeight:T,inWidth:$,outChannels:E,outHeight:R,outWidth:_,strideHeight:A,strideWidth:O}=f;h=f.dataFormat;const F=I-1-f.padInfo.top,D=N-1-f.padInfo.left,M="channelsLast"===h,P=m.strides[0],L=M?m.strides[1]:m.strides[2],B=M?m.strides[2]:1,V=M?1:m.strides[1],W=p[0],z=M?p[1]:p[2],U=M?p[2]:1,G=M?1:p[1];for(let C=0;C<k;++C)for(let e=0;e<S;++e)for(let t=0;t<T;++t){const n=t-F,r=Math.max(0,Math.ceil(n/A)),a=Math.min(R,(I+n)/A);for(let s=0;s<$;++s){const o=s-D,i=Math.max(0,Math.ceil(o/O)),u=Math.min(_,(N+o)/O);let l=0;for(let t=r;t<a;++t){const r=t*A-n;for(let n=i;n<u;++n){const a=W*C+z*t+U*n,s=x*(I-1-r)+v*(N-1-(n*O-o))+w*e;for(let e=0;e<E;++e){l+=y[a+G*e]*b[s+e]}}}g[P*C+L*t+B*s+V*e]=l}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}};const xR={kernelName:Ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r;_b([a,s],"conv3d");const l=uo(a.shape,s.shape,o,u,i),{filterDepth:c,filterHeight:d,filterWidth:p,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=l,y=g.front,b=g.left,x=g.top,v=new qr(l.outShape,a.dtype),w=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,I=v.values,N=C(a.shape),S=C(s.shape);for(let T=0;T<l.batchSize;++T){const e=T*N[0],t=T*v.strides[0];for(let n=0;n<l.outDepth;++n){const r=t+n*v.strides[1],a=n*l.strideDepth-y;for(let t=0;t<c;++t){const n=a+t*h;if(n<0||n>=l.inDepth)continue;const s=t*S[0],o=e+n*N[1];for(let e=0;e<l.outHeight;++e){const t=r+e*v.strides[2],n=e*l.strideHeight-x;for(let e=0;e<d;++e){const r=n+e*f;if(r<0||r>=l.inHeight)continue;const a=s+e*S[1],i=o+r*N[2];for(let e=0;e<l.outWidth;++e){const n=t+e*l.outChannels,r=e*l.strideWidth-b;for(let e=0;e<p;++e){const t=r+e*m;if(t<0||t>=l.inWidth)continue;const s=a+e*S[2],o=i+t*l.inChannels;let u=s;for(let e=0;e<l.inChannels;++e){const t=w[o+e];for(let e=0;e<l.outChannels;++e)I[n+e]+=t*k[u+e];u+=l.outChannels}}}}}}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}};const vR={kernelName:Ne,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,filterShape:u}=r;_b([a,s],"conv3dBackpropFilterV2");const l=C(a.shape),c=C(s.shape),d=uo(a.shape,u,o,1,i),p=d.strideDepth,h=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,y=d.filterWidth,b=new qr(d.filterShape,"float32"),x=b.values,[v,w,k,I]=b.strides,N=n.data.get(s.dataId).values,[S,T,$,E]=c,R=n.data.get(a.dataId).values,[_,A,O,F]=l,D=d.padInfo.front,M=d.padInfo.left,P=d.padInfo.top;for(let C=0;C<m;++C){const e=Math.max(0,Math.ceil((D-C)/p)),t=Math.min(d.outDepth,(d.inDepth+D-C)/p),n=C*v;for(let r=0;r<g;++r){const a=Math.max(0,Math.ceil((P-r)/h)),s=Math.min(d.outHeight,(d.inHeight+P-r)/h),o=r*w+n;for(let n=0;n<y;++n){const i=Math.max(0,Math.ceil((M-n)/f)),u=Math.min(d.outWidth,(d.inWidth+M-n)/f),l=n*k+o;for(let o=0;o<d.inChannels;++o){const c=o*I+l;for(let l=0;l<d.outChannels;++l){let m=0;for(let c=0;c<d.batchSize;++c){const d=c*_,g=c*S;for(let c=e;c<t;++c){const e=(C+c*p-D)*A+d,t=c*T+g;for(let c=a;c<s;++c){const a=(r+c*h-P)*O+e,s=c*$+t;for(let e=i;e<u;++e){const t=e*E+s;m+=R[(n+e*f-M)*F+a+o]*N[t+l]}}}}x[c+l]=m}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const wR={kernelName:Se,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:o,strides:i,inputShape:u}=r;_b([a],"conv3dBackpropInputV2");const l=C(a.shape),c=C(s.shape),d=uo(u,s.shape,i,1,o),p=new qr(d.inShape,"float32"),h=p.values,[f,m,g,y]=p.strides,b=n.data.get(a.dataId).values,[x,v,w,k]=l,I=n.data.get(s.dataId).values,[N,S,T,$]=c,{batchSize:E,filterDepth:R,filterHeight:_,filterWidth:A,inChannels:O,inDepth:F,inHeight:D,inWidth:M,outChannels:P,outDepth:L,outHeight:B,outWidth:V,strideDepth:W,strideHeight:z,strideWidth:U}=d,G=R-1-d.padInfo.front,H=_-1-d.padInfo.top,j=A-1-d.padInfo.left;for(let C=0;C<E;++C)for(let e=0;e<O;++e)for(let t=0;t<F;++t){const n=t-G,r=Math.max(0,Math.ceil(n/W)),a=Math.min(L,(R+n)/W);for(let s=0;s<D;++s){const o=s-H,i=Math.max(0,Math.ceil(o/z)),u=Math.min(B,(_+o)/z);for(let l=0;l<M;++l){const c=l-j,d=Math.max(0,Math.ceil(c/U)),p=Math.min(V,(A+c)/U);let E=0;for(let t=r;t<a;++t){const r=t*W-n;for(let n=i;n<u;++n){const a=n*z-o;for(let s=d;s<p;++s){const o=x*C+v*t+w*n+k*s,i=N*(R-1-r)+S*(_-1-a)+T*(A-1-(s*U-c))+$*e;for(let e=0;e<P;++e){E+=b[o+e]*I[i+e]}}}}h[f*C+m*t+g*s+y*l+e]=E}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}},kR=rx(Te,e=>Math.cos(e)),IR={kernelName:Te,backendName:"cpu",kernelFunc:kR},NR=rx(Ce,e=>Math.cosh(e)),SR={kernelName:Ce,backendName:"cpu",kernelFunc:NR};const TR={kernelName:Re,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,[c,d,p,h]=a.shape,f=s.shape[0],[m,g]=i,y=Ps([f,m,g,h],"float32"),b=n.data.get(s.dataId).values,x=n.data.get(o.dataId).values,v=n.data.get(a.dataId).values,w=C(a.shape),k=C(y.shape);for(let I=0;I<f;I++){const e=4*I,t=b[e],n=b[e+1],r=b[e+2],a=b[e+3],s=x[I];if(s>=c)continue;const o=m>1?(r-t)*(d-1)/(m-1):0,i=g>1?(a-n)*(p-1)/(g-1):0;for(let c=0;c<m;c++){const e=m>1?t*(d-1)+c*o:.5*(t+r)*(d-1);if(e<0||e>d-1)for(let t=0;t<g;t++)for(let e=0;e<h;e++){const n=e+t*k[2]+c*k[1]+I*k[0];y.values[n]=l}else if("bilinear"===u){const t=Math.floor(e),r=Math.ceil(e),o=e-t;for(let e=0;e<g;e++){const u=g>1?n*(p-1)+e*i:.5*(n+a)*(p-1);if(u<0||u>p-1){for(let t=0;t<h;t++){const n=t+e*k[2]+c*k[1]+I*k[0];y.values[n]=l}continue}const d=Math.floor(u),f=Math.ceil(u),m=u-d;for(let n=0;n<h;n++){let a=n+d*w[2]+t*w[1]+s*w[0];const i=v[a];a=n+f*w[2]+t*w[1]+s*w[0];const u=v[a];a=n+d*w[2]+r*w[1]+s*w[0];const l=v[a];a=n+f*w[2]+r*w[1]+s*w[0];const p=i+(u-i)*m,h=l+(v[a]-l)*m;a=n+e*k[2]+c*k[1]+I*k[0],y.values[a]=p+(h-p)*o}}}else for(let t=0;t<g;++t){const r=g>1?n*(p-1)+t*i:.5*(n+a)*(p-1);if(r<0||r>p-1){for(let e=0;e<h;e++){const n=e+t*k[2]+c*k[1]+I*k[0];y.values[n]=l}continue}const o=Math.round(r),u=Math.round(e);for(let e=0;e<h;e++){const n=e+o*w[2]+u*w[1]+s*w[0],r=e+t*k[2]+c*k[1]+I*k[0];y.values[r]=v[n]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}};const CR={kernelName:$e,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r;_b(a,"cumprod");const u=Ni([s],a.shape.length);let l=a;null!=u&&(l=sv({inputs:{x:a},backend:n,attrs:{perm:u}}));const d=Ti(1,a.shape.length)[0];if(d!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${d}`);const p=ca(l.dtype,"int32"),h=R(c(l.shape),p),f=n.data.get(l.dataId).values,m=l.shape[l.shape.length-1],g=i?(e,t)=>e+m-t-1:(e,t)=>e+t;for(let c=0;c<f.length;c+=m)for(let e=0;e<m;e++){const t=g(c,e);if(0===e)h[t]=o?1:f[t];else{const n=g(c,e-1);h[t]=o?f[n]*h[n]:f[t]*h[n]}}const y=n.makeTensorInfo(l.shape,p,h);if(null!=u){const e=sv({inputs:{x:y},backend:n,attrs:{perm:Si(u)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(l),e}return y}};const $R={kernelName:Ee,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r;_b(a,"cumsum");const u=Ni([s],a.shape.length);let l=a;null!=u&&(l=sv({inputs:{x:a},backend:n,attrs:{perm:u}}));const d=Ti(1,a.shape.length)[0];if(d!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${d}`);const p=ca(l.dtype,"int32"),h=_(c(l.shape),p),f=n.data.get(l.dataId).values,m=l.shape[l.shape.length-1],g=i?(e,t)=>e+m-t-1:(e,t)=>e+t;for(let c=0;c<f.length;c+=m)for(let e=0;e<m;e++){const t=g(c,e);if(0===e)h[t]=o?0:f[t];else{const n=g(c,e-1);h[t]=o?f[n]+h[n]:f[t]+h[n]}}const y=n.makeTensorInfo(l.shape,p,h);if(null!=u){const e=sv({inputs:{x:y},backend:n,attrs:{perm:Si(u)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(l),e}return y}};const ER={kernelName:_e,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o,binaryOutput:i}=r;if(1===a.shape.length){const e=Qb(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,e)}if(2===a.shape.length){const e=Zb(n.bufferSync(a),n.bufferSync(s),o,i);return n.makeTensorInfo(e.shape,s.dtype,e.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}};const RR={kernelName:Ae,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:o}=r;i("NHWC"===o,()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);const u=a.shape[0],l=a.shape[1],c=a.shape[2],d=a.shape[3],p=l*s,h=c*s,f=d/(s*s),m=n.data.get(a.dataId).values,g=new Float32Array(u*p*h*f);let y=0;for(let i=0;i<u;++i)for(let e=0;e<p;++e){const t=Math.floor(e/s),n=e%s;for(let e=0;e<h;++e){const r=Math.floor(e/s),a=(n*s+e%s)*f;for(let e=0;e<f;++e){const n=e+a+d*(r+c*(t+l*i));g[y++]=m[n]}}}return n.makeTensorInfo([u,p,h,f],a.dtype,g)}};function _R(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:u,dilations:l,dimRoundingMode:c}=r;_b([a,s],"depthwiseConv2DNative");const d=C(a.shape),p=C(s.shape);let h=l;null==h&&(h=[1,1]),i(go(o,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${h}'`);const f=io(a.shape,s.shape,o,h,u,c,!0),{filterHeight:m,filterWidth:g,dilationHeight:y,dilationWidth:b,padInfo:x}=f,v=x.left,w=x.top,k=f.outChannels/f.inChannels,I=new qr(f.outShape,a.dtype),N=n.data.get(a.dataId).values,S=n.data.get(s.dataId).values,T=I.values;for(let i=0;i<f.batchSize;++i){const e=i*d[0],t=i*I.strides[0];for(let n=0;n<f.outHeight;++n){const r=t+n*I.strides[1],a=n*f.strideHeight-w;for(let t=0;t<m;++t){const n=a+t*y;if(n<0||n>=f.inHeight)continue;const s=t*p[0],o=e+n*d[1];for(let e=0;e<f.outWidth;++e){const t=r+e*I.strides[2],n=e*f.strideWidth-v;for(let e=0;e<g;++e){const r=n+e*b;if(r<0||r>=f.inWidth)continue;const a=s+e*p[1],i=o+r*f.inChannels;let u=t,l=a;for(let e=0;e<f.inChannels;++e){const t=N[i+e];for(let e=0;e<k;++e)T[u+e]+=t*S[l+e];u+=k,l+=k}}}}}}return n.makeTensorInfo(I.shape,I.dtype,I.values)}const AR={kernelName:Oe,backendName:"cpu",kernelFunc:_R};const OR={kernelName:Fe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,filterShape:c}=r;_b([a,s],"depthwiseConv2dNativeBackpropFilter");const d=io(a.shape,c,o,i,u,l,!0),{strideHeight:p,strideWidth:h,filterHeight:f,filterWidth:m}=d,g=new qr(d.filterShape,"float32"),y=d.padInfo.left,b=d.padInfo.top,x=d.outChannels/d.inChannels,v=n.data.get(a.dataId).values,w=new qr(a.shape,a.dtype,v),k=n.data.get(s.dataId).values,I=new qr(s.shape,s.dtype,k);for(let N=0;N<f;++N){const e=Math.max(0,Math.ceil((b-N)/p)),t=Math.min(d.outHeight,(d.inHeight+b-N)/p);for(let n=0;n<m;++n){const r=Math.max(0,Math.ceil((y-n)/h)),a=Math.min(d.outWidth,(d.inWidth+y-n)/h);for(let s=0;s<d.outChannels;++s){const o=Math.trunc(s/x),i=s%x;let u=0;for(let l=0;l<d.batchSize;++l)for(let i=e;i<t;++i){const e=N+i*p-b;for(let t=r;t<a;++t){const r=n+t*h-y;u+=w.get(l,e,r,o)*I.get(l,i,t,s)}}g.set(u,N,n,o,i)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}};const FR={kernelName:De,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,inputShape:c}=r;_b([a,s],"depthwiseConv2DNativeBackpropInput");const d=C(a.shape),p=C(s.shape),h=io(c,s.shape,o,i,u,l,!0),f=new qr(h.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(a.dataId).values,[v,w,k]=d,I=n.data.get(s.dataId).values,[N,S,T]=p,{batchSize:$,filterHeight:E,filterWidth:R,inChannels:_,inHeight:A,inWidth:O,outChannels:F,outHeight:D,outWidth:M,strideHeight:P,strideWidth:L}=h,B=E-1-h.padInfo.top,V=R-1-h.padInfo.left,W=F/_;for(let C=0;C<$;++C)for(let e=0;e<_;++e)for(let t=0;t<A;++t){const n=t-B,r=Math.max(0,Math.ceil(n/P)),a=Math.min(D,(E+n)/P);for(let s=0;s<O;++s){const o=s-V,i=Math.max(0,Math.ceil(o/L)),u=Math.min(M,(R+o)/L);let l=0;for(let t=r;t<a;++t){const r=t*P-n;for(let n=i;n<u;++n){const a=v*C+w*t+k*n,s=N*(E-1-r)+S*(R-1-(n*L-o))+T*e;for(let t=0;t<W;++t){l+=x[a+(e*W+t)]*I[s+t]}}}m[g*C+y*t+b*s+e]=l}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}};const DR={kernelName:Me,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=c(r.shape),s=n.data.get(r.dataId).values,o=Ps([a,a],r.dtype),i=o.values;for(let l=0;l<s.length;l++)i[l*a+l]=s[l];const u=[...r.shape,...r.shape];return n.makeTensorInfo(u,o.dtype,o.values)}},MR={kernelName:Pe,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a}=e,{strides:s,pad:o,dilations:i}=n,u=t,l=u.data.get(r.dataId).values,d=r.shape.length,p=u.data.get(a.dataId).values,h=a.shape.length,{batchSize:f,inHeight:m,inWidth:g,inChannels:y,outHeight:b,outWidth:x,padInfo:w,strideHeight:k,strideWidth:I,filterHeight:N,filterWidth:S,dilationHeight:T,dilationWidth:$,outShape:E}=ao(r.shape,a.shape,s,o,"NHWC",i),R=c(E),_=E.length,A=v(r.dtype,R);for(let c=0;c<f;++c)for(let e=0;e<b;++e){const t=e*k-w.top;for(let n=0;n<x;++n){const s=n*I-w.left;for(let o=0;o<y;++o){let i=Number.MIN_SAFE_INTEGER;for(let e=0;e<N;++e){const n=t+e*T;if(n>=0&&n<m)for(let t=0;t<S;++t){const u=s+t*$;if(u>=0&&u<g){const s=F([c,n,u,o],d,C(r.shape)),f=F([e,t,o],h,C(a.shape)),m=l[s]+p[f];m>i&&(i=m)}}}A[F([c,e,n,o],_,C(E))]=i}}}return{dataId:u.write(Or(A,r.dtype),E,r.dtype),shape:E,dtype:r.dtype}}},PR={kernelName:Be,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:o,pad:u,dilations:l}=n,c=t,d=E(r.shape,c.data.get(r.dataId).values),p=E(a.shape,c.data.get(a.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:v,strideWidth:w,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:T}=ao(r.shape,a.shape,o,u,"NHWC",l);i(s.rank===T.length,()=>`Error in ${Be}, dy must have the same rank as output ${T.length}, but got ${s.rank}`);const C=E(T,c.data.get(s.dataId).values),$=A(a.shape,a.dtype);for(let i=0;i<h;++i)for(let e=0;e<y;++e){const t=e*v-x.top;for(let n=0;n<b;++n){const r=n*w-x.left;for(let a=0;a<g;++a){let s=Number.MIN_SAFE_INTEGER,o=0,u=0;for(let e=0;e<k;++e){const n=t+e*N;if(n>=0&&n<f)for(let t=0;t<I;++t){const l=r+t*S;if(l>=0&&l<m){const r=d[i][n][l][a]+p[e][t][a];r>s&&(s=r,o=e,u=t)}}}$[o][u][a]+=C[i][e][n][a]}}}return{dataId:c.write(Or($,r.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},LR={kernelName:Le,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:o,pad:u,dilations:l}=n,c=t,d=E(r.shape,c.data.get(r.dataId).values),p=E(a.shape,c.data.get(a.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:v,strideWidth:w,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:T}=ao(r.shape,a.shape,o,u,"NHWC",l);i(s.rank===T.length,()=>`Error in ${Le}, dy must have the same rank as output ${T.length}, but got ${s.rank}`);const C=E(T,c.data.get(s.dataId).values),$=A(r.shape,r.dtype);for(let i=0;i<h;++i)for(let e=0;e<y;++e){const t=e*v-x.top;for(let n=0;n<b;++n){const r=n*w-x.left;for(let a=0;a<g;++a){let s=Number.MIN_SAFE_INTEGER,o=t<0?0:t,u=r<0?0:r;for(let e=0;e<k;++e){const n=t+e*N;if(n>=0&&n<f)for(let t=0;t<I;++t){const l=r+t*S;if(l>=0&&l<m){const r=d[i][n][l][a]+p[e][t][a];r>s&&(s=r,o=n,u=l)}}}$[i][o][u][a]+=C[i][e][n][a]}}}return{dataId:c.write(Or($,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};const BR={kernelName:Ve,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{canvas:s,options:o}=r,{contextOptions:i,imageOptions:u}=o||{},l=(null===u||void 0===u?void 0:u.alpha)||1,c=(null===i||void 0===i?void 0:i.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${i.contextType} is not supported by the CPU backend.`);const d=s.getContext(c,(null===i||void 0===i?void 0:i.contextAttributes)||{});if(null==d)throw new Error(`Could not get the context with ${c} type.`);const[p,h]=a.shape.slice(0,2),f=2===a.shape.length?1:a.shape[2],m=n.data.get(a.dataId).values,g="float32"===a.dtype?255:1,y=new Uint8ClampedArray(h*p*4);for(let x=0;x<p*h;++x){const e=[0,0,0,255*l];for(let n=0;n<f;n++){const t=m[x*f+n];if("float32"===a.dtype){if(t<0||t>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${t}.`)}else if("int32"===a.dtype&&(t<0||t>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${t}.`);1===f?(e[0]=t*g,e[1]=t*g,e[2]=t*g):e[n]=t*g}const t=4*x;y[t+0]=Math.round(e[0]),y[t+1]=Math.round(e[1]),y[t+2]=Math.round(e[2]),y[t+3]=Math.round(e[3])}s.width=h,s.height=p;const b=new ImageData(y,h,p);return d.putImageData(b,0,0),a}};function VR(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;_b(a,"sum"),i="bool"===a.dtype?Ub({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):Lb({inputs:{x:a},backend:n});const u=i.shape.length,l=y(s,i.shape),d=Ni(l,u);let p=l,h=i;null!=d&&(h=sv({inputs:{x:i},backend:n,attrs:{perm:d}}),p=Ti(p.length,u)),Ii("sum",p,h.shape.length);const[f,m]=wi(h.shape,p);let g=Pb(n,f,ca(h.dtype,"int32"));const b=c(m),x=n.data.get(g.dataId).values,v=n.data.get(h.dataId).values;for(let c=0;c<x.length;++c){const e=c*b;let t=0;for(let n=0;n<b;++n)t+=v[e+n];x[c]=t}if(o){const e=g;g=TE({inputs:{x:g},backend:n,attrs:{shape:ki(g.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(i),null!=d&&n.disposeIntermediateTensorInfo(h),g}const WR={kernelName:Nn,backendName:"cpu",kernelFunc:VR};const zR={kernelName:ze,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:a}=r,s=t,{allDims:o,summedDims:i,idDims:u}=lh(a,s.length);dh(o.length,u,s);const{path:l,steps:c}=ph(i,u),p=c.length;let h=null,f=o.length;const m=[];for(let g=0;g<p;++g){for(const e of c[g]){const{permutationIndices:t,expandDims:r}=ch(f,u[e]);let a;hh(t)?a=s[e]:(a=sv({inputs:{x:s[e]},backend:n,attrs:{perm:t}}),m.push(a));const o=a.shape.slice();for(let e=0;e<r.length;++e)o.splice(r[e],0,1);d(a.shape,o)||(a=TE({inputs:{x:a},backend:n,attrs:{shape:o}}),m.push(a)),null===h?h=a:(h=Qx({inputs:{a,b:h},backend:n}),m.push(h))}g<p-1&&(l[g]>=0&&(h=VR({inputs:{x:h},backend:n,attrs:{axis:l[g]-(o.length-f),keepDims:!1}}),m.push(h)),f--)}for(const d of m)d!==h&&n.disposeIntermediateTensorInfo(d);return h}};const UR={kernelName:Ge,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:a}=t;_b([r,a],"eluGrad");const s=new Float32Array(c(a.shape)),o=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values;for(let u=0;u<o.length;++u){const e=o[u];s[u]=e>=0?i[u]:i[u]*(e+1)}return n.makeTensorInfo(a.shape,"float32",s)}},GR=qp,HR=Kp,jR=Xp,qR=Yp,KR=Qp,XR=Zp,YR=rx(He,e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+GR*n);return t*(1-((((XR*r+KR)*r+qR)*r+jR)*r+HR)*r*Math.exp(-n*n))}),QR={kernelName:He,backendName:"cpu",kernelFunc:YR};function ZR(e){const{inputs:t,backend:n,attrs:r}=e,{input:a}=t,{dim:s}=r,o=a.shape.length,u=a.shape.slice();let l=s;return s<0&&(i(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+s+1),u.splice(l,0,1),TE({inputs:{x:a},backend:n,attrs:{shape:u}})}const JR={kernelName:Ke,backendName:"cpu",kernelFunc:ZR},e_=Fb((e,t)=>e/t),t_=Hb(We,e_),n_={kernelName:We,backendName:"cpu",kernelFunc:t_};function r_(e,t,n){const r=e.shape,a=r[0],s=r[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,u=o.complexTensorInfos.imag,l=[a,s],d=c(l),p=x("float32",d),h=x("float32",d);for(let c=0;c<a;c++){const e=Ev({inputs:{x:i},backend:n,attrs:{begin:[c,0],size:[1,s]}}),r=Ev({inputs:{x:u},backend:n,attrs:{begin:[c,0],size:[1,s]}}),a=Db({inputs:{real:e,imag:r},backend:n}),{real:o,imag:l}=a_(a,t,n),d=Jp(o,l);for(let t=0;t<s;t++){const e=rh(d,t);p[c*s+t]=e.real,h[c*s+t]=e.imag}n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a)}const f=n.makeTensorInfo(l,"float32",p),m=n.makeTensorInfo(l,"float32",h),g=Db({inputs:{real:f,imag:m},backend:n});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}function a_(e,t,n){const r=c(e.shape),a=n.data.get(e.dataId),s=n.data.get(a.complexTensorInfos.real.dataId).values,o=n.data.get(a.complexTensorInfos.imag.dataId).values;if(0===((i=r)&i-1)){const a=s_(s,o,r,t,n),i=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(i,"float32",a.real),t=n.makeTensorInfo(i,"float32",a.imag),s=n.makeTensorInfo([],"float32",Ar(r,"float32")),o=Lb({inputs:{x:s},backend:n}),u=n_.kernelFunc({inputs:{a:e,b:s},backend:n}),l=n_.kernelFunc({inputs:{a:t,b:o},backend:n}),c=n.data.get(u.dataId).values,d=n.data.get(l.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),{real:c,imag:d}}return a}{const e=function(e,t,n){const r=new Float32Array(2*t);for(let a=0;a<t;a++){let s=0,o=0;for(let r=0;r<t;r++){const i=oh(a*r,t,n),u=rh(e,r);s+=u.real*i.real-u.imag*i.imag,o+=u.real*i.imag+u.imag*i.real}n&&(s/=t,o/=t),ah(r,s,o,a)}return r}(Jp(s,o),r,t);return eh(e)}var i}function s_(e,t,n,r,a){if(1===n)return{real:e,imag:t};const s=Jp(e,t),o=n/2,i=th(s),u=i.real,l=i.imag,c=[u.length],d=a.makeTensorInfo(c,"float32",u),p=a.makeTensorInfo(c,"float32",l),h=Db({inputs:{real:d,imag:p},backend:a}),f=nh(s),m=f.real,g=f.imag,y=[m.length],b=a.makeTensorInfo(y,"float32",m),x=a.makeTensorInfo(y,"float32",g),v=Db({inputs:{real:b,imag:x},backend:a}),w=s_(u,l,o,r,a),k=w.real,I=w.imag,N=[k.length],S=a.makeTensorInfo(N,"float32",k),T=a.makeTensorInfo(N,"float32",I),C=Db({inputs:{real:S,imag:T},backend:a}),$=s_(m,g,o,r,a),E=$.real,R=$.imag,_=[E.length],A=a.makeTensorInfo(_,"float32",E),O=a.makeTensorInfo(_,"float32",R),F=Db({inputs:{real:A,imag:O},backend:a}),D=sh(n,r),M=[D.real.length],P=a.makeTensorInfo(M,"float32",D.real),L=a.makeTensorInfo(M,"float32",D.imag),B=Db({inputs:{real:P,imag:L},backend:a}),V=Qx({inputs:{a:B,b:F},backend:a}),W=Xb({inputs:{a:C,b:V},backend:a}),z=Qv({inputs:{a:C,b:V},backend:a}),U=Vb({inputs:{input:W},backend:a}),G=Vb({inputs:{input:z},backend:a}),H=dR({inputs:{input:W},backend:a}),j=dR({inputs:{input:z},backend:a}),q=hR({inputs:[U,G],backend:a,attrs:{axis:0}}),K=hR({inputs:[H,j],backend:a,attrs:{axis:0}}),X=a.data.get(q.dataId).values,Y=a.data.get(K.dataId).values;return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(b),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(v),a.disposeIntermediateTensorInfo(S),a.disposeIntermediateTensorInfo(T),a.disposeIntermediateTensorInfo(C),a.disposeIntermediateTensorInfo(A),a.disposeIntermediateTensorInfo(O),a.disposeIntermediateTensorInfo(F),a.disposeIntermediateTensorInfo(P),a.disposeIntermediateTensorInfo(L),a.disposeIntermediateTensorInfo(B),a.disposeIntermediateTensorInfo(V),a.disposeIntermediateTensorInfo(W),a.disposeIntermediateTensorInfo(z),a.disposeIntermediateTensorInfo(U),a.disposeIntermediateTensorInfo(H),a.disposeIntermediateTensorInfo(G),a.disposeIntermediateTensorInfo(j),a.disposeIntermediateTensorInfo(q),a.disposeIntermediateTensorInfo(K),{real:X,imag:Y}}const o_={kernelName:Ye,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=c(r.shape),s=r.shape[r.shape.length-1],o=TE({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),i=r_(o,!1,n),u=TE({inputs:{x:i},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),u}};function i_(e){const{backend:t,attrs:n}=e,{shape:r,value:a,dtype:s}=n,o=s||N(a),i=v(o,c(r));return function(e,t){e.fill(t)}(i,a),t.makeTensorInfo(r,o,i)}const u_={kernelName:Qe,backendName:"cpu",kernelFunc:i_};const l_={kernelName:Ze,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,a=n,s=x(r.dtype,c(r.shape)),[o,i,u,l]=r.shape,d=a.data.get(r.dataId).values;for(let c=0;c<o;c++){const e=c*u*i*l;for(let t=0;t<i;t++){const n=t*(u*l);for(let t=0;t<u;t++){const r=t*l;for(let a=0;a<l;a++){const o=Math.round(u-t-1),i=e+n+r+a;let c=d[i];if(o>=0&&o<u){c=d[e+n+o*l+a]}s[i]=c}}}}return{dataId:a.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};const c_={kernelName:tr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=mR({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(o){const e=m;if("NCHW"===c&&1===o.shape.length&&1!==o.shape[0]){const e=TE({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=Xb({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=Xb({inputs:{a:m,b:o},backend:n});n.disposeIntermediateTensorInfo(e)}if(h){const e=m;if("NCHW"===c&&"prelu"===h&&1===i.shape.length&&1!==i.shape[0]){const e=TE({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=SE(n,m,h,e,f),n.disposeIntermediateTensorInfo(e)}else m=SE(n,m,h,i,f);n.disposeIntermediateTensorInfo(e)}return m}};const d_={kernelName:nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=_R({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(o){const e=m;m=Xb({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=SE(n,m,h,i,f),n.disposeIntermediateTensorInfo(e)}return m}};const p_={kernelName:rt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=c(r.shape),o=a.shape,i=o[o.length-1],[u,l,d,p]=vp(r,a);if(0===l)return n.makeTensorInfo(u,r.dtype,[]);const h=Nx(n.data.get(a.dataId).values,n.bufferSync(r),r.dtype,l,i,d,p,r.shape,s);return n.makeTensorInfo(u,r.dtype,h.values)}};const h_={kernelName:nt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:o,batchDims:u}=r;_b([a,s],"gatherV2");const l=y(o,a.shape)[0],d=n.data.get(s.dataId).values,p=a.shape[l];for(let c=0;c<d.length;++c){const e=d[c];i(e<=p-1&&e>=0,()=>`GatherV2: the index value ${e} is not in [0, ${p-1}]`)}let h=u;null==u&&(h=0);const f=c(s.shape),m=$h(a,s,l,h),g=TE({inputs:{x:a},backend:n,attrs:{shape:[m.batchSize,m.outerSize,m.dimSize,m.sliceSize]}}),b=TE({inputs:{x:s},backend:n,attrs:{shape:[m.batchSize,f/m.batchSize]}}),x=[m.batchSize,m.outerSize,f/m.batchSize,m.sliceSize],v=n.bufferSync(b),w=Sx(n.bufferSync(g),v,x);return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(b),n.makeTensorInfo(m.outputShape,w.dtype,w.values)}};const f_={kernelName:it,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=c(r.shape),s=r.shape[r.shape.length-1],o=TE({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),i=r_(o,!0,n),u=TE({inputs:{x:i},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),u}},m_=rx(lt,e=>Number.isFinite(e)?1:0,"bool"),g_={kernelName:lt,backendName:"cpu",kernelFunc:m_},y_=rx(ct,e=>Math.abs(e)===1/0?1:0,"bool"),b_={kernelName:ct,backendName:"cpu",kernelFunc:y_},x_=rx(dt,e=>Number.isNaN(e)?1:0,"bool"),v_={kernelName:dt,backendName:"cpu",kernelFunc:x_};const w_={kernelName:mt,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,o=Lx(r,a,s);return t.makeTensorInfo([o.length],"float32",o)}},k_=rx(yt,e=>Math.log1p(e)),I_={kernelName:yt,backendName:"cpu",kernelFunc:k_},N_=Fb((e,t)=>e&&t),S_=Hb(bt,N_,null,"bool"),T_={kernelName:bt,backendName:"cpu",kernelFunc:S_},C_=rx(xt,e=>e?0:1,"bool"),$_={kernelName:xt,backendName:"cpu",kernelFunc:C_},E_=Fb((e,t)=>e||t),R_=Hb(vt,E_,null,"bool"),__={kernelName:vt,backendName:"cpu",kernelFunc:R_};const A_={kernelName:wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:o,alpha:i,beta:u}=r;_b(a,"LRN");const l=a.shape[3],d=l-1,p=n.data.get(a.dataId).values,h=c(a.shape),f=new Float32Array(h);function m(e){const t=e%l;let n=e-t+Math.max(0,t-s);const r=e-t+Math.min(t+s,d);let a=0;for(;n<=r;n++){const e=p[n];a+=e*e}return a}for(let c=0;c<h;c++){const e=m(c),t=p[c]*Math.pow(o+i*e,-u);f[c]=t}return n.makeTensorInfo(a.shape,a.dtype,f)}};const O_={kernelName:kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:o}=t,{depthRadius:i,bias:u,alpha:l,beta:d}=r;_b(o,"LRNGrad");const p=c(o.shape),h=o.shape[3],f=n.data.get(o.dataId).values,m=n.data.get(a.dataId).values,g=n.data.get(s.dataId).values,y=new Float32Array(p),b=p;for(let c=0;c<b;c++){const e=c%h,t=c-e+Math.max(0,e-i),n=c-e+Math.min(h,e+i+1);let r=0;for(let a=t;a<n;a++)r+=Math.pow(m[a],2);r=l*r+u;for(let a=t;a<n;a++){let e=-2*l*d*m[a]*g[c]/r;c===a&&(e+=Math.pow(r,-d)),e*=f[c],y[a]+=e}}return n.makeTensorInfo(o.shape,a.dtype,y)}};function F_(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=n;let u=a.shape;const l=u.length,d=y(s,u);let p=d;const h=Ni(p,l);let f=i.data.get(a.dataId).values;if(null!=h){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[h[t]];f=av(f,u,a.dtype,h,e),p=Ti(p.length,l),u=e}_b(a,"max"),Ii("max",p,l);const[m,g]=wi(u,p),b=zx(f,c(g),m,a.dtype),x=i.write(b,m,a.dtype);let v=m;if(o){v=ki(m,d)}return{dataId:x,shape:v,dtype:a.dtype}}const D_={kernelName:It,backendName:"cpu",kernelFunc:F_};const M_={kernelName:St,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;_b(a,"maxPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:l}=r;i(go(o,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const c=so(a.shape,s,o,1,u,l);let p;if(1===c.filterWidth&&1===c.filterHeight&&d(c.inShape,c.outShape))p=Lb({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=C(a.shape),r=QE(e,a.shape,a.dtype,t,c,"max");p=n.makeTensorInfo(c.outShape,a.dtype,r.values)}return p}};const P_={kernelName:Ct,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r;_b(a,"maxPool3d");const c=oo(a.shape,s,o,1,i,u,l),d=JE(n.data.get(a.dataId).values,a.shape,a.dtype,C(a.shape),c,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}};const L_={kernelName:$t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r;_b([a,s],"maxPool3DGrad");const c=oo(s.shape,o,i,1,u,l),d=function(e,t){const n=Ps(t.outShape,"int32"),r=t.strideDepth,a=t.strideHeight,s=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,u=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*r-p;let x=b;for(;x<0;)x+=o;const v=Math.min(t.inDepth,l+b);for(let r=0;r<t.outHeight;++r){const l=r*a-h;let p=l;for(;p<0;)p+=i;const w=Math.min(t.inHeight,c+l);for(let a=0;a<t.outWidth;++a){const h=a*s-f;let k=h;for(;k<0;)k+=u;const I=Math.min(t.inWidth,d+h);let N=Number.NEGATIVE_INFINITY,S=-1;for(let t=x;t<v;t+=o){const n=t-b;for(let r=p;r<w;r+=i){const a=r-l;for(let s=k;s<I;s+=u){const o=s-h,i=e.get(m,t,r,s,g);i>=N&&(N=i,S=n*c*d+a*c+o)}}}n.set(S,m,y,r,a,g)}}}return n}(n.bufferSync(s),c),p=c.strideDepth,h=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,v=c.effectiveFilterWidth,w=b-1-c.padInfo.front,k=v-1-c.padInfo.left,I=x-1-c.padInfo.top,N=Ps(s.shape,"float32"),S=n.bufferSync(a);for(let T=0;T<c.batchSize;++T)for(let e=0;e<c.inChannels;++e)for(let t=0;t<c.inDepth;++t)for(let n=0;n<c.inHeight;++n)for(let r=0;r<c.inWidth;++r){const a=t-w,s=n-I,o=r-k;let i=0;for(let t=0;t<b;t+=m){const n=(a+t)/p;if(!(n<0||n>=c.outDepth||Math.floor(n)!==n))for(let r=0;r<x;r+=g){const a=(s+r)/h;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let s=0;s<v;s+=y){const u=(o+s)/f;if(u<0||u>=c.outWidth||Math.floor(u)!==u)continue;const l=b*x*v-1-d.get(T,n,a,u,e)===t*x*v+r*v+s?1:0;if(0===l)continue;i+=S.get(T,n,a,u,e)*l}}}N.set(i,T,t,n,r,e)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}};const B_={kernelName:Tt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:o}=t,i=s;_b([s,o],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=so(i.shape,u,l,1,c,d),h=n.data.get(i.dataId).values,f=Ps(p.outShape,i.dtype,ZE(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,v=p.effectiveFilterWidth,w=v-1-p.padInfo.left,k=x-1-p.padInfo.top,I=Ps(i.shape,"float32"),N=n.data.get(a.dataId).values,S=Ps(a.shape,"float32",N);for(let T=0;T<p.batchSize;++T)for(let e=0;e<p.inChannels;++e)for(let t=0;t<p.inHeight;++t)for(let n=0;n<p.inWidth;++n){const r=t-k,a=n-w;let s=0;for(let t=0;t<x;t+=y){const n=(r+t)/m;if(!(n<0||n>=p.outHeight||Math.floor(n)!==n))for(let r=0;r<v;r+=b){const o=(a+r)/g;if(o<0||o>=p.outWidth||Math.floor(o)!==o)continue;const i=x*v-1-f.get(T,n,o,e)===t*v+r?1:0;if(0===i)continue;s+=S.get(T,n,o,e)*i}}I.set(s,T,t,n,e)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}};const V_={kernelName:Et,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:o,includeBatchInIndex:i}=t,u=n;_b(r,"MaxPoolWithArgmax");const l=u.data.get(r.dataId).values,c=so(r.shape,a,s,[1,1],o),[d,p]=function(e,t,n,r,a){const s=QE(e,0,n,C(t),a,"max"),o=ZE(e,t,n,a,!0,r);return[s.values,o.values]}(l,r.shape,r.dtype,i,c),h=u.write(d,c.outShape,r.dtype),f=u.write(p,c.outShape,r.dtype);return[{dataId:h,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};const W_={kernelName:Rt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=y(s,a.shape),u=c(wi(a.shape,i)[1]),l=[],d=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(d);const p=Ub({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(p);const h=t_({inputs:{a:p,b:d},backend:n});l.push(h);const f=VR({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}};const z_={kernelName:_t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;_b(a,"min");const i=y(s,a.shape);let u=i;const l=Ni(u,a.shape.length);let d=a;null!=l&&(d=sv({inputs:{x:a},backend:n,attrs:{perm:l}}),u=Ti(u.length,a.shape.length)),Ii("min",u,d.shape.length);const[p,h]=wi(d.shape,u),f=c(h),m=_(c(p),d.dtype),g=n.data.get(d.dataId).values;for(let c=0;c<m.length;++c){const e=c*f;let t=g[e];for(let n=0;n<f;++n){const r=g[e+n];(Number.isNaN(r)||r<t)&&(t=r)}m[c]=t}null!=l&&n.disposeIntermediateTensorInfo(d);const b=n.makeTensorInfo(p,d.dtype,m);if(o){const e=TE({inputs:{x:b},backend:n,attrs:{shape:ki(p,i)}});return n.disposeIntermediateTensorInfo(b),e}return b}};const U_={kernelName:Ot,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,mode:o}=r;_b(a,"mirrorPad");const i=s.map((e,t)=>e[0]+a.shape[t]+e[1]),u=s.map(e=>e[0]),l=s.map((e,t)=>e[0]+a.shape[t]),d="reflect"===o?0:1,p=n.data.get(a.dataId).values,h=a.shape.length,f=C(a.shape),m=c(i),g=i.length,y=C(i),b=x(a.dtype,m);for(let c=0;c<m;c++){let e=D(c,g,y);for(let n=0;n<g;n++)e[n]<u[n]?e[n]=2*u[n]-e[n]-d:e[n]>=l[n]&&(e[n]=2*(l[n]-1)-e[n]+d);e=e.map((e,t)=>e-u[t]);const t=F(e,h,f);b[c]=p[t]}return{dataId:n.write(b,i,a.dtype),shape:i,dtype:a.dtype}}},G_=Fb((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),H_=Hb(Ft,G_),j_={kernelName:Ft,backendName:"cpu",kernelFunc:H_};function q_(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=a.shape.length;let i=s;if(-1===i&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);const u=y([i],a.shape),l=F_({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=ki(l.shape,u),d=TE({inputs:{x:l},backend:n,attrs:{shape:c}}),p=Qv({inputs:{a,b:d},backend:n}),h=hx({inputs:{x:p},backend:n}),f=VR({inputs:{x:h},backend:n,attrs:{axis:u,keepDims:!1}}),m=TE({inputs:{x:f},backend:n,attrs:{shape:c}}),g=t_({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const K_={kernelName:Cn,backendName:"cpu",kernelFunc:q_};const X_={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:o,normalized:i}=r;_b(a,"multinomial");const u=i?a:q_({inputs:{logits:a},backend:n,attrs:{dim:-1}}),l=u.shape[0],d=u.shape[1],p=n.data.get(u.dataId).values,h=[l,s],f=_(c(h),"int32");for(let c=0;c<l;++c){const e=c*d,t=new Float32Array(d-1);t[0]=p[e];for(let a=1;a<t.length;++a)t[a]=t[a-1]+p[e+a];const n=ml.alea(o.toString()),r=c*s;for(let a=0;a<s;++a){const e=n();f[r+a]=t.length;for(let n=0;n<t.length;n++)if(e<t[n]){f[r+a]=n;break}}}return i||n.disposeIntermediateTensorInfo(u),n.makeTensorInfo(h,"int32",f)}},Y_=rd;const Q_={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=r;_b(a,"NonMaxSuppression");const l=n.data.get(a.dataId).values,c=n.data.get(s.dataId).values,{selectedIndices:d}=Y_(l,c,o,i,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},Z_=ad;const J_={kernelName:Vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,padToMaxOutputSize:l}=r;_b(a,"NonMaxSuppressionPadded");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,{selectedIndices:p,validOutputs:h}=Z_(c,d,o,i,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},eA=sd;const tA={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=r;_b(a,"NonMaxSuppressionWithScore");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,p=o,h=i,f=u,m=l,{selectedIndices:g,selectedScores:y}=eA(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const nA={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:o,onValue:i,offValue:u}=r;_b(a,"oneHot");const l=c(a.shape),d=new Float32Array(l*o);d.fill(u);const p=n.data.get(a.dataId).values;for(let c=0;c<l;++c)p[c]>=0&&p[c]<o&&(d[c*o+p[c]]=i);return n.makeTensorInfo([...a.shape,o],s,d)}};function rA(e){const{inputs:t,backend:n}=e,{x:r}=t;if("string"===r.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===r.dtype){const e=Vb({inputs:{input:r},backend:n}),t=rA({inputs:{x:e},backend:n}),a=dR({inputs:{input:r},backend:n}),s=rA({inputs:{x:a},backend:n}),o=Db({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),o}return i_({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const aA={kernelName:Yn,backendName:"cpu",kernelFunc:rA};const sA={kernelName:zt,backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===a.dtype){const t=Vb({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=dR({inputs:{input:a},backend:r}),o=rA({inputs:{x:s},backend:r}),i=Db({inputs:{real:n,imag:o},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}return i_({backend:r,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}};function oA(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return ZR({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach(e=>{u(s,e.shape,"All tensors passed to stack must have matching shapes"),i(o===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const l=[],c=t.map(e=>{const t=ZR({inputs:{input:e},backend:n,attrs:{dim:a}});return l.push(t),t}),d=hR({inputs:c,backend:n,attrs:{axis:a}});return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}const iA={kernelName:Gt,backendName:"cpu",kernelFunc:oA};const uA={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;_b(a,"pad");const i=s.map((e,t)=>e[0]+a.shape[t]+e[1]),u=s.map(e=>e[0]),l=n.data.get(a.dataId).values,d=c(a.shape),p=a.shape.length,h=C(a.shape),f=c(i),m=i.length,g=C(i),y=x(a.dtype,f);0!==o&&y.fill(o);for(let c=0;c<d;c++){y[F(D(c,p,h).map((e,t)=>e+u[t]),m,g)]=l[c]}return{dataId:n.write(y,i,a.dtype),shape:i,dtype:a.dtype}}},lA=Fb((e,t)=>Math.pow(e,t)),cA=Hb(jt,lA),dA={kernelName:jt,backendName:"cpu",kernelFunc:cA};const pA={kernelName:Xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:o}=t,{outputRaggedRank:i}=r,u=a.map(e=>n.data.get(e.dataId).values),l=a.map(e=>e.shape),c=n.data.get(s.dataId).values,d=n.data.get(o.dataId).values,[p,h,f]=pv(u,l,c,s.shape,s.dtype,d,o.shape),m=p.map(e=>n.makeTensorInfo([e.length],"int32",e)),g=n.makeTensorInfo(f,s.dtype,h);return m.concat([g])}};const hA={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:a,deltas:s}=t,o=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=fv(o,r.shape,r.dtype,i,a.shape,u,s.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}};const fA={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:a,values:s,defaultValue:o,rowPartitionTensors:i}=t,{rowPartitionTypes:u}=r,l=n.data.get(a.dataId).values,c=n.data.get(s.dataId).values,d=n.data.get(o.dataId).values,p=i.map(e=>n.data.get(e.dataId).values),h=i.map(e=>e.shape),[f,m]=xv(l,a.shape,c,s.shape,s.dtype,d,o.shape,p,h,u);return n.makeTensorInfo(f,s.dtype,m)}};const mA={kernelName:Zt,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,dtype:s,step:o}=n,i=vv(r,a,o,s);return t.makeTensorInfo([i.length],s,i)}},gA=rx(en,e=>1/e),yA={kernelName:en,backendName:"cpu",kernelFunc:gA};const bA={kernelName:sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;_b(a,"resizeBilinear");const u=C(a.shape),[l,d]=i,[p,h,f,m]=a.shape,g=n.data.get(a.dataId).values,y=new Float32Array(c([p,l,d,m])),b=[s&&l>1?h-1:h,s&&d>1?f-1:f],x=[s&&l>1?l-1:l,s&&d>1?d-1:d];let v=0;const w=b[0]/x[0],k=b[1]/x[1];for(let c=0;c<p;c++)for(let e=0;e<l;e++){let t;t=o?w*(e+.5)-.5:w*e;const n=Math.max(0,Math.floor(t)),r=t-n,a=Math.min(h-1,Math.ceil(t)),s=c*u[0]+n*u[1],i=c*u[0]+a*u[1];for(let e=0;e<d;e++){let t;t=o?k*(e+.5)-.5:k*e;const n=Math.max(0,Math.floor(t)),a=t-n,l=Math.min(f-1,Math.ceil(t)),c=s+n*u[2],d=i+n*u[2],p=s+l*u[2],h=i+l*u[2];for(let e=0;e<m;e++){const t=g[c+e],n=g[d+e],s=t+(g[p+e]-t)*a,o=s+(n+(g[h+e]-n)*a-s)*r;y[v++]=o}}}return n.makeTensorInfo([p,l,d,m],"float32",y)}};const xA={kernelName:on,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r;_b([s,a],"resizeBilinearGrad");const i=C(a.shape),[u,l,c,d]=a.shape,[,p,h]=s.shape,f=new Float32Array(u*l*c*d),m=[o&&p>1?l-1:l,o&&h>1?c-1:c],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(s.dataId).values;let v=0;for(let w=0;w<u;w++){const e=w*i[0];for(let t=0;t<p;t++){const n=t*y,r=Math.floor(n),a=Math.min(Math.ceil(n),l-1),s=e+r*i[1],o=e+a*i[1],u=n-r,p=1-u;for(let e=0;e<h;e++){const t=e*b,n=Math.floor(t),r=Math.min(Math.ceil(t),c-1),a=t-n,l=1-a,h=s+n*i[2],m=s+r*i[2],g=o+n*i[2],y=o+r*i[2],w=p*l,k=p*a,I=u*l,N=u*a;for(let e=0;e<d;e++){const t=x[v++];f[h+e]+=t*w,f[m+e]+=t*k,f[g+e]+=t*I,f[y+e]+=t*N}}}}return n.makeTensorInfo([u,c,l,d],"float32",f)}};const vA={kernelName:rn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;_b(a,"resizeNearestNeighbor");const u=C(a.shape),[l,c]=i,[d,p,h,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(d*l*c*f),y=[s&&l>1?p-1:p,s&&c>1?h-1:h],b=[s&&l>1?l-1:l,s&&c>1?c-1:c],x=y[0]/b[0],v=y[1]/b[1];let w=0;for(let k=0;k<d;k++){const e=k*u[0];for(let t=0;t<l;t++){const n=o?x*(t+.5):x*t;let r=Math.min(p-1,s?Math.round(n):Math.floor(n));o&&(r=Math.max(0,r));const a=e+r*u[1];for(let e=0;e<c;e++){const t=o?v*(e+.5):v*e;let n=Math.min(h-1,s?Math.round(t):Math.floor(t));o&&(n=Math.max(0,n));const r=a+n*u[2];for(let e=0;e<f;e++){const t=m[r+e];g[w++]=t}}}}return n.makeTensorInfo([d,l,c,f],a.dtype,g)}};const wA={kernelName:an,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r;_b([s,a],"resizeNearestNeighborGrad");const i=C(a.shape),u=C(s.shape),[l,c,d,p]=a.shape,[,h,f]=s.shape,m=new Float32Array(l*c*d*p),g=n.data.get(s.dataId).values,y=[o&&h>1?c-1:c,o&&f>1?d-1:d],b=[o&&h>1?h-1:h,o&&f>1?f-1:f],x=y[0]/b[0],v=y[1]/b[1],w=1/x,k=1/v,I=2*Math.ceil(w)+2,N=2*Math.ceil(k)+2;for(let S=0;S<l;S++){const e=S*i[0];for(let t=0;t<c;t++){const n=e+t*i[1],r=Math.floor(t*w),a=Math.floor(r-I/2);for(let s=0;s<d;s++){const r=n+s*i[2],l=Math.floor(s*k),y=Math.floor(l-N/2);for(let n=0;n<p;n++){let i=0;for(let r=0;r<I;r++){const l=r+a;if(l<0||l>=h)continue;const p=e+l*u[1],m=l*x;if(t===Math.min(c-1,o?Math.round(m):Math.floor(m)))for(let e=0;e<N;e++){const t=e+y;if(t<0||t>=f)continue;const r=p+t*u[2],a=t*v;s===Math.min(d-1,o?Math.round(a):Math.floor(a))&&(i+=g[r+n])}}m[r+n]=i}}}}return n.makeTensorInfo(a.shape,a.dtype,m)}};const kA={kernelName:ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;_b(a,"reverse");const o=a.shape.length,i=y(s,a.shape);if(0===o)return Lb({inputs:{x:a},backend:n});const u=new qr(a.shape,a.dtype),l=n.bufferSync(a);for(let c=0;c<u.size;c++){const e=u.indexToLoc(c),t=e.slice();i.forEach(e=>t[e]=a.shape[e]-1-t[e]),u.set(l.get(...t),...e)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},IA={kernelName:Jn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:o}=t,i=n,u=x(r.dtype,c(r.shape)),[l,d,p,h]=r.shape,[f,m]=Bp(o,d,p),g=Math.sin(a),y=Math.cos(a),b=i.data.get(r.dataId).values;for(let c=0;c<l;c++){const e=c*p*d*h;for(let t=0;t<d;t++){const n=t*(p*h);for(let r=0;r<p;r++){const a=r*h;for(let o=0;o<h;o++){const i=[l,t,r,o],c=i[2],x=i[1];let v=(c-f)*y-(x-m)*g,w=(c-f)*g+(x-m)*y;v=Math.round(v+f),w=Math.round(w+m);let k=s;if("number"!==typeof s&&(k=3===o?255:s[o]),v>=0&&v<p&&w>=0&&w<d){k=b[e+w*(p*h)+v*h+o]}u[e+n+a+o]=k}}}}return{dataId:i.write(u,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},NA=rx(cn,e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),SA={kernelName:cn,backendName:"cpu",kernelFunc:NA};const TA={kernelName:pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:o}=r,{sliceRank:i,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=pc(0,a,o),p=Nv(n.bufferSync(a),n.bufferSync(s),o,d,l,u,i,c,0,!0);return n.makeTensorInfo(o,p.dtype,p.values)}};function CA(e,t){let n=0,r=e.length,a=0;for(;n<r;)a=Math.floor((n+r)/2),e[a]<t?n=a+1:r=a;return r}function $A(e,t){let n=0,r=e.length,a=0;for(;n<r;)a=Math.floor((n+r)/2),e[a]<=t?n=a+1:r=a;return r}const EA={kernelName:fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:s}=t,{side:o}=r,i=function(e,t,n,r,a,s){const o=v("int32",n*a);for(let i=0;i<n;++i){const n=e.slice(i*r,(i+1)*r),u=i*a;for(let e=0;e<a;++e)o[u+e]="left"===s?CA(n,t[e+u]):$A(n,t[e+u])}return o}(n.data.get(a.dataId).values,n.data.get(s.dataId).values,a.shape[0],a.shape[1],s.shape[1],o);return n.makeTensorInfo(s.shape,"int32",i)}};const RA={kernelName:mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t;_b([r,a,s],"select");const o=r.shape.length,i=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(s.dataId).values,d=ca(a.dtype,s.dtype),p=_(c(a.shape),d);let h=0;const f=0===o||o>1||1===a.shape.length?1:c(a.shape.slice(1));for(let c=0;c<i.length;c++)for(let e=0;e<f;e++)1===i[c]?p[h++]=u[c]:p[h++]=l[c];return n.makeTensorInfo(a.shape,d,p)}},_A=Hp,AA=jp,OA=rx(gn,e=>e>=0?AA*e:_A*(Math.exp(e)-1)),FA={kernelName:gn,backendName:"cpu",kernelFunc:OA},DA=rx(vn,e=>e<0?-1:e>0?1:0),MA={kernelName:vn,backendName:"cpu",kernelFunc:DA},PA=rx(bn,e=>Math.sin(e)),LA={kernelName:bn,backendName:"cpu",kernelFunc:PA},BA=rx(xn,e=>Math.sinh(e)),VA={kernelName:xn,backendName:"cpu",kernelFunc:BA},WA=Math.log(1.1920928955078125e-7)+2,zA=rx(kn,e=>{const t=e>-WA,n=e<WA,r=Math.exp(e);let a;return a=n?r:t?e:Math.log(1+r),a}),UA={kernelName:kn,backendName:"cpu",kernelFunc:zA};const GA={kernelName:Sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;_b([a],"spaceToBatchND");const i=c(s),u=[[0,0]];u.push(...o);for(let c=1+s.length;c<a.shape.length;++c)u.push([0,0]);const l=uA.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),d=Vp(l.shape,s,i,!1),p=Wp(d.length,s.length,!1),h=zp(l.shape,s,i,!1),f=TE({inputs:{x:l},backend:n,attrs:{shape:d}}),m=sv({inputs:{x:f},backend:n,attrs:{perm:p}}),g=TE({inputs:{x:m},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const HA={kernelName:$n,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:a,denseShape:s,defaultValue:o}=t;if(1!==s.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${s.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Values must be a vector, saw:\n ${a.shape}`);if(0!==o.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${o.shape}`);const i=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(s.dataId).values,c=n.data.get(o.dataId).values[0],[d,p,h,f,m]=_v(i,r.shape,r.dtype,u,a.dtype,l,c);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],a.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(e=>Number(e)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}};const jA={kernelName:En,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:a,newShape:s}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);const o=Array.from(n.data.get(a.dataId).values),i=n.data.get(r.dataId).values,u=Array.from(n.data.get(s.dataId).values),[l,c,d]=Av(i,r.shape,r.dtype,o,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}};const qA={kernelName:Rn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:s}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");const o=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=Ov(o,r.shape,r.dtype,i,u,!0);return n.makeTensorInfo(c,r.dtype,l)}};const KA={kernelName:_n,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:s}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");const o=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=Ov(o,r.shape,r.dtype,i,u);return n.makeTensorInfo(c,r.dtype,l)}};const XA={kernelName:An,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:d,outputSize:p}=pc(0,a,i),h=!1,f=n.bufferSync(a);let m;switch(s.dtype){case"bool":m=Nv(f,n.bufferSync(s),i,p,c,l,u,d,Boolean(n.data.get(o.dataId).values[0]),h);break;case"float32":m=Nv(f,n.bufferSync(s),i,p,c,l,u,d,n.data.get(o.dataId).values[0],h);break;case"int32":m=Nv(f,n.bufferSync(s),i,p,c,l,u,d,n.data.get(o.dataId).values[0],h);break;case"string":m=Nv(f,n.bufferSync(s),i,p,c,l,u,d,Mr(n.data.get(o.dataId).values[0]),h);break;default:throw new Error(`Unsupported type ${s.dtype}`)}return n.makeTensorInfo(i,m.dtype,m.values)}};const YA={kernelName:Tn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=r,i=y(o,a.shape)[0],u=mh(a,s,i),l=new Array(a.shape.length).fill(0),c=a.shape.slice();return u.map(e=>{const t=[...c];t[i]=e;const r=Ev({inputs:{x:a},backend:n,attrs:{begin:l,size:t}});return l[i]+=e,r})}},QA={kernelName:Fn,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;_b(n,"square");const a=r.data.get(n.dataId).values,s=new Float32Array(a.length);for(let o=0;o<a.length;++o){const e=a[o];s[o]=e*e}return{dataId:r.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},ZA=rx(Qn,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),JA={kernelName:Qn,backendName:"cpu",kernelFunc:ZA};const eO={kernelName:Mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:u,beginMask:l,endMask:c,ellipsisMask:d,newAxisMask:p,shrinkAxisMask:h}=r;_b(a,"stridedSlice");const{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:v,strides:w}=Tp(a.shape,s,o,u,l,c,d,p,h);let k;if(g)k=TE({inputs:{x:a},backend:n,attrs:{shape:m}});else if(y||b){i(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);const e=kp(x,v,w),t=Ev({inputs:{x:a},backend:n,attrs:{begin:x,size:e}});k=TE({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{const e=Uv(f,n.bufferSync(a),w,x);k=n.makeTensorInfo(m,e.dtype,e.values)}return k}};const tO={kernelName:Pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:s,leftPad:o,rightPad:i,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:d}=t,p=n.data.get(c.dataId).values,h=n.data.get(d.dataId).values,[f,m]=Hv(p,h,a,s,o,i,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}};const nO={kernelName:Ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:s,delimiter:o}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");if(1!==s.shape.length)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(0!==o.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);const i=n.data.get(s.dataId).values,u=n.data.get(o.dataId).values[0],[l,c,d]=qv(i,u,a),p=c.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(d))]}};const rO={kernelName:Bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:a}=r,{input:s}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");const o=Kv(n.data.get(s.dataId).values,a);return n.makeTensorInfo(s.shape,"int32",o)}},aO=rx(Wn,e=>Math.tan(e)),sO={kernelName:Wn,backendName:"cpu",kernelFunc:aO},oO=rx(zn,e=>Math.tanh(e));function iO(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return a(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return a(0,n,t-1)}(e,t);case"nearest":return function(e,t){return a(0,e,t-1)}(e,t);default:return function(e){return e}(e)}}function uO(e,t,n,r,a,s,o,i,u,l,c){return 0<=i&&i<t&&0<=u&&u<n?e[o*r+i*a+u*s+l]:c}function lO(e,t,n,r,a,s,o,i,u,l,c){return uO(e,t,n,r,a,s,o,Math.round(i),Math.round(u),l,c)}function cO(e,t,n,r,a,s,o,i,u,l,c){const d=Math.floor(i),p=Math.floor(u),h=d+1,f=p+1;return(h-i)*((f-u)*uO(e,t,n,r,a,s,o,d,p,l,c)+(u-p)*uO(e,t,n,r,a,s,o,d,f,l,c))+(i-d)*((f-u)*uO(e,t,n,r,a,s,o,h,p,l,c)+(u-p)*uO(e,t,n,r,a,s,o,h,f,l,c))}const dO={kernelName:Xn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:o}=r;_b(a,"unsortedSegmentSum");const i=[],u=[],l=a.shape.length-s.shape.length;let c=s;for(let p=0;p<l;++p){const e=ZR({inputs:{input:c},backend:n,attrs:{dim:p+1}});c=e,u.push(e)}for(let p=0;p<o;++p){const e=Ar(p,"int32"),t=n.makeTensorInfo([],"int32",e),r=cx({inputs:{a:t,b:c},backend:n}),s=Ub({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),o=Qx({inputs:{a:s,b:a},backend:n}),l=VR({inputs:{x:o},backend:n,attrs:{axis:0,keepDims:!1}});i.push(l),u.push(t),u.push(r),u.push(s),u.push(o),u.push(l)}const d=oA({inputs:i,backend:n,attrs:{axis:0}});return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}},pO=[RE,Ob,AE,FE,Yb,DE,ME,PE,LE,BE,WE,UE,HE,KE,YE,eR,tR,nR,rR,EE,aR,sR,oR,tx,iR,Gb,ix,lR,Mb,cR,fR,gR,yR,bR,xR,vR,wR,IR,SR,TR,CR,$R,ER,RR,AR,OR,FR,DR,MR,PR,LR,BR,zR,mE,UR,dx,QR,fx,JR,yx,o_,u_,l_,vx,Ix,c_,d_,p_,h_,$x,_x,Bb,f_,pR,g_,b_,v_,yE,Fx,Px,w_,Wx,I_,T_,$_,__,A_,O_,D_,Hx,M_,P_,L_,B_,V_,W_,z_,Kx,U_,j_,X_,Zx,ev,Q_,J_,tA,rv,nA,sA,iA,uA,dA,vE,uv,pA,hA,fA,mA,Wb,n_,yA,kE,NE,CE,bA,xA,vA,wA,kA,IA,SA,Iv,TA,EA,RA,FA,Cv,MA,LA,VA,Rv,K_,UA,GA,HA,jA,qA,KA,XA,YA,Mv,QA,Bv,zv,JA,eO,tO,nO,rO,Zv,WR,sO,{kernelName:zn,backendName:"cpu",kernelFunc:oO},{kernelName:hn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:r,indices:a,updates:s}=t,{sliceRank:o,numUpdates:i,sliceSize:u,strides:l,outputSize:c}=pc(0,a,r.shape),d=n.bufferSync(a),p=n.bufferSync(s),h=n.bufferSync(r),f=Nv(d,p,r.shape,c,u,i,o,l,h,!1);return n.makeTensorInfo(r.shape,f.dtype,f.values)}},{kernelName:Un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reps:s}=r;_b(a,"tile");const o=Jv(n.bufferSync(a),s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}},{kernelName:Gn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:o}=r;_b(a,"topk");const i=n.data.get(a.dataId).values,[u,l]=nw(i,a.shape,a.dtype,s,o);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}},{kernelName:Hn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{image:a,transforms:s}=t,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=n,[d,p,h,f]=a.shape,[m,g]=null!=l?l:[p,h],y=[d,m,g,f],b=C(a.shape),v=b[0],w=b[1],k=b[2],I=C(y),N=I[0],S=I[1],T=I[2],$=x(a.dtype,c(y));$.fill(u);const E=r.data.get(a.dataId).values,R=r.data.get(s.dataId).values;for(let c=0;c<d;++c){const e=1===s.shape[0]?R:R.subarray(8*c,8*c+8);for(let t=0;t<m;++t)for(let n=0;n<g;++n)for(let r=0;r<f;++r){let a;const s=e[6]*n+e[7]*t+1;if(0===s)continue;const l=(e[0]*n+e[1]*t+e[2])/s,d=(e[3]*n+e[4]*t+e[5])/s,f=iO(l,h,i),m=iO(d,p,i);switch(o){case"nearest":a=lO(E,p,h,v,w,k,c,m,f,r,u);break;case"bilinear":a=cO(E,p,h,v,w,k,c,m,f,r,u);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${o}`)}$[c*N+t*S+n*T+r]=a}return r.makeTensorInfo(y,a.dtype,$)}return{dataId:r.write($,y,a.dtype),shape:a.shape,dtype:a.dtype}}},ov,{kernelName:qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;_b(s,"unique");const o=r.data.get(s.dataId).values,{outputValues:i,outputShape:u,indices:l}=rw(o,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}},{kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape.length,i=a.shape[s],u=new Array(o-1);let l=0;for(let h=0;h<o;h++)h!==s&&(u[l++]=a.shape[h]);const c=new Array(o).fill(0),d=a.shape.slice();d[s]=1;const p=new Array(i);for(let h=0;h<p.length;h++){c[s]=h;const e=Ev({inputs:{x:a},backend:n,attrs:{begin:c,size:d}});p[h]=TE({inputs:{x:e},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(e)}return p}},dO,aA];for(const fO of pO)lr(fO);return function(e={}){return t=>{const{template:{$video:n,$danmuku:r}}=t;let a=null,s=null,o=null,i=null,u=!1;const l={solutionPath:e.solutionPath||"https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation",modelSelection:e.modelSelection||1,smoothSegmentation:void 0===e.smoothSegmentation||e.smoothSegmentation,minDetectionConfidence:e.minDetectionConfidence||.5,minTrackingConfidence:e.minTrackingConfidence||.5,selfieMode:e.selfieMode||!1,drawContour:e.drawContour||!1,foregroundThreshold:e.foregroundThreshold||.5,opacity:e.opacity||1,maskBlurAmount:e.maskBlurAmount||3};async function c(){await async function(){try{await za("webgl")}catch(e){console.warn("WebGL backend not available, falling back to CPU",e.message),await za("cpu")}}();const e=zg.MediaPipeSelfieSegmentation,t={runtime:"mediapipe",modelType:"general",solutionPath:l.solutionPath,modelSelection:l.modelSelection,smoothSegmentation:l.smoothSegmentation,minDetectionConfidence:l.minDetectionConfidence,minTrackingConfidence:l.minTrackingConfidence,selfieMode:l.selfieMode};try{a=await function(e,t){return lm(this,0,void 0,function(){var n,r;return cm(this,function(a){switch(e){case zg.MediaPipeSelfieSegmentation:if(n=void 0,null!=(r=t)){if("tfjs"===r.runtime)return[2,Hg(r)];if("mediapipe"===r.runtime)return[2,Ag(r)];n=r.runtime}throw new Error("Expect modelConfig.runtime to be either 'tfjs' or 'mediapipe', but got "+n);case zg.BodyPix:return[2,Cg(r=t)];default:throw new Error(e+" is not a supported model name.")}})})}(e,t),u=!0}catch(n){console.error("Error initializing segmenter:",n),u=!1}}async function d(){if(!u||n.paused||n.ended)i=requestAnimationFrame(d);else{try{s.width=n.videoWidth,s.height=n.videoHeight;const e=await a.segmentPeople(n);if(!e||0===e.length)return void(i=requestAnimationFrame(d));const t={r:255,g:255,b:255,a:255},u={r:0,g:0,b:0,a:255},c=await function(e,t,n,r,a,s){return void 0===t&&(t={r:0,g:0,b:0,a:0}),void 0===n&&(n={r:0,g:0,b:0,a:255}),void 0===r&&(r=!1),void 0===a&&(a=.5),void 0===s&&(s=Array.from(Array(256).keys())),lm(this,0,void 0,function(){var o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return 0===(o=Array.isArray(e)?e:[e]).length?[2,null]:[4,Promise.all(o.map(function(e){return e.mask.toImageData()}))];case 1:for(i=v.sent(),u=i[0],l=u.width,c=u.height,d=new Uint8ClampedArray(l*c*4),p=Math.round(255*a),h=new Array(256).fill(!1),s.forEach(function(e){return h[e]=!0}),f=0;f<c;f++)for(m=0;m<l;m++)for(d[4*(g=f*l+m)+0]=n.r,d[4*g+1]=n.g,d[4*g+2]=n.b,d[4*g+3]=n.a,y=0,b=i;y<b.length;y++)x=b[y],h[x.data[4*g]]&&x.data[4*g+3]>=p&&(d[4*g]=t.r,d[4*g+1]=t.g,d[4*g+2]=t.b,d[4*g+3]=t.a,r&&f-1>=0&&f+1<c&&m-1>=0&&m+1<l&&ny(x.data,f,m,l,h,p)&&ty(d,f,m,l,1));return[2,new ImageData(d,l,c)]}})})}(e,t,u,l.drawContour,l.foregroundThreshold);await ry(s,n,c,l.opacity,l.maskBlurAmount);const p=o.getImageData(0,0,s.width,s.height);o.putImageData(function(e){const t=e.data;for(let n=0;n<t.length;n+=4)t[n]>250&&t[n+1]>250&&t[n+2]>250&&(t[n+3]=0);return e}(p),0,0),r.style.maskImage=`url(${s.toDataURL()})`}catch(e){console.error("Error in segmentBody:",e)}i=requestAnimationFrame(d)}}async function p(){u||await c(),s||(s=document.createElement("canvas"),o=s.getContext("2d")),Object.assign(r.style,{maskMode:"alpha",maskSize:"contain",maskRepeat:"no-repeat",backgroundSize:"contain",backgroundRepeat:"no-repeat"}),d()}function h(){r.style.maskImage="none",i&&(cancelAnimationFrame(i),i=null)}return t.on("ready",p),t.on("destroy",h),{name:"artplayerPluginDanmukuMask",start:p,stop:h}}}});
|